Mastering Building PWA in Rails Learn and Master How to Build Progressive Web Apps (PWAs) using Ruby on Rails Written by Chetan Mittal Edition: First. Published in 2025.

  • Move Chapter 1: Introduction to Progressive Web Apps (PWA)
    Open Chapter 1: Introduction to Progressive Web Apps (PWA)

    Chapter 1: Introduction to Progressive Web Apps (PWA)

    Chapter 1: Introduction to Progressive Web Apps (PWA)
  • Move Understanding PWAs: What Makes an App "Progressive"?
    Open Understanding PWAs: What Makes an App "Progressive"?

    Understanding PWAs: What Makes an App "Progressive"?

    Progressive Web Apps (PWAs) are a modern approach to web application development that combines the best aspects of web and native mobile apps.

    Unlike traditional web applications, PWAs leverage modern browser capabilities to provide an installable, fast, and engaging user experience.

    The main difference between a Web Application and a Progressive Web App (PWA) is that a PWA offers a mobile-app-like experience with offline capabilities, better performance, and device integration, whereas a traditional web application requires an internet connection and lacks advanced features like push notifications and installation.

    PWAs provide a seamless experience across desktop and mobile devices.

    Examples include:

    • Spotify PWA
    • Starbucks PWA
    • Uber PWA

    Key Differences Between a Web App and a PWA

    Feature Web Application Progressive Web App (PWA)
    Understanding PWAs: What Makes an App "Progressive"? 978 words
  • Move How Ruby on Rails Complements PWA Capabilities?
    Open How Ruby on Rails Complements PWA Capabilities?

    How Ruby on Rails Complements PWA Development?

    Ruby on Rails is a powerful framework for web application development, known for its convention over configuration approach.

    Combining Rails with PWA technology results in a highly efficient, scalable, and maintainable web application.

    Why Rails is a Good Fit for PWA Development?

    1. Rapid Development – Rails provides built-in tools like generators, scaffolding, and a convention-over-configuration approach, allowing developers to build and iterate quickly.
    2. API-Ready Architecture – Rails makes it easy to build RESTful or GraphQL APIs, which PWAs rely on for dynamic content fetching and data storage.
    3. Efficient Asset Management – With modern asset-handling solutions like Importmaps and Propshaft, Rails ensures efficient loading of JavaScript, CSS, and images, reducing the complexity of managing front-end assets.
    4. Real-Time Capabilities – ActionCable enables WebSockets for real-time features like live notifications, messa
    How Ruby on Rails Complements PWA Capabilities? 425 words
  • Move What are the Core Technologies of PWAs?
    Open What are the Core Technologies of PWAs?

    Core Technologies of PWAs: Service Workers, Web App Manifests, and Caching Strategies

    To fully implement a PWA, you need to understand its core technologies:

    • Service Workers – JavaScript scripts that run in the background to handle caching, push notifications, and offline functionality.
    • Web App Manifest – A JSON file that tells the browser how the app should behave when installed on a device.
    • Caching Strategies – Various approaches to storing assets and API responses to improve performance and enable offline access.

    Service Workers

    A service worker enables background processes like caching and push notifications. The following example demonstrates a cache-first strategy:

    self.addEventListener('fetch', (event) => {
      event.respondWith(
        caches.match(event.request).then((cachedResponse) => {
          return cachedResponse || fetch(event.request);
        })
      );
    });
    

    This ensures that previously loaded resources are *served from cache first

    What are the Core Technologies of PWAs? 428 words
  • Move Can We Use StimulusJS for PWA Development in Rails?
    Open Can We Use StimulusJS for PWA Development in Rails?

    Can We Use StimulusJS for PWA Development in Rails?

    Yes, StimulusJS can be used alongside a Rails PWA, but it does not replace Service Workers.

    StimulusJS enhances frontend interactions, while Service Workers handle caching, offline support, and push notifications at the browser level.

    How StimulusJS Can Help in PWA Development?

    Here’s how Stimulus can complement your PWA:

    • ✅ Registering a Service Worker Dynamically
    • ✅ Triggering Background Sync Events
    • ✅ Handling Push Notifications in the UI
    • ✅ Updating the UI When Network Status Changes

    Example: Using Stimulus to Register a Service Worker

    Instead of writing raw JavaScript in application.html.erb, you can create a Stimulus controller for managing the Service Worker.

    1. Create a Stimulus Controller

    rails generate stimulus pwa
    

    2. Implement Service Worker Registration in Stimulus

    Edit pwa_controller.js:

    import { Controller } from "@hotwired/stimulus
    
    Can We Use StimulusJS for PWA Development in Rails? 331 words
  • Move Chapter 2: Setting Up a Rails Project for PWA Development
    Open Chapter 2: Setting Up a Rails Project for PWA Development

    Chapter 2: Setting Up a Rails Project for PWA Development

    Chapter 2: Setting Up a Rails Project for PWA Development
  • Move Installing and Configuring Rails for PWA
    Open Installing and Configuring Rails for PWA

    Installing and Configuring Rails for PWA

    To begin, we need to set up a new Rails project with essential dependencies for PWA functionality.

    Step 1: Create a New Rails Application

    Ensure you have the latest version of Rails installed:

    gem install rails
    

    Then, create a new Rails project:

    rails new rails_pwa --webpack=esbuild
    cd rails_pwa
    

    Here, we use --webpack=esbuild to enable JavaScript bundling.

    Step 2: Install Required Gems

    To support PWA development, add these gems to your Gemfile:

    #Gemfile
    gem 'webpacker', '~> 5.4' # If using Webpacker instead of esbuild
    gem 'pwa', '~> 0.1.0' # PWA helper gem
    

    Run bundle install to install dependencies.

    Step 3: Set Up Webpack and JavaScript Environment

    Ensure Webpack is correctly installed for JavaScript handling:

    bin/rails webpacker:install
    

    Now, Rails is ready for PWA development. Next, we will integrate Webpack and Stimulus.js for modern front-end interac

    Installing and Configuring Rails for PWA 151 words
  • Move Adding Webpack and Stimulus.js
    Open Adding Webpack and Stimulus.js

    Adding Webpack and Stimulus.js

    Modern Rails applications use JavaScript frameworks for interactivity.

    Stimulus.js is a lightweight framework designed for Rails applications, making it a great fit for PWAs.

    Step 1: Install Stimulus.js

    Rails applications using Webpack (or esbuild) can install Stimulus with:

    bin/rails stimulus:install
    

    This creates a controllers directory in app/javascript.

    Step 2: Example Stimulus Controller

    Create a file at app/javascript/controllers/hello_controller.js:

    import { Controller } from "@hotwired/stimulus";
    
    export default class extends Controller {
      connect() {
        console.log("Hello from Stimulus!");
      }
    }
    

    Then, link it in application.js:

    import { Application } from "@hotwired/stimulus";
    import HelloController from "./controllers/hello_controller";
    
    const application = Application.start();
    application.register("hello", HelloController);
    

    Now, any HTML element ca

    Adding Webpack and Stimulus.js 146 words
  • Move Configuring HTTPS for Local Development
    Open Configuring HTTPS for Local Development

    Configuring HTTPS for Local Development

    Why HTTPS?

    Service workers require a secure context (https://) to function.

    While Rails applications typically use http://localhost:3000, we need HTTPS for PWA development.

    Step 1: Generate a Self-Signed SSL Certificate

    Run the following command to generate a local SSL certificate:

    mkdir -p config/ssl
    openssl req -x509 -newkey rsa:2048 -keyout config/ssl/key.pem -out config/ssl/cert.pem -days 365 -nodes -subj "/CN=localhost"
    

    This generates a key and certificate valid for one year.

    Step 2: Configure Rails to Use HTTPS

    Modify config/puma.rb to use the certificate:

    ssl_bind '127.0.0.1', '3001', {
      key: "config/ssl/key.pem",
      cert: "config/ssl/cert.pem"
    }
    

    Start the server with:

    bin/rails s -b 'ssl://127.0.0.1:3001?key=config/ssl/key.pem&cert=config/ssl/cert.pem'
    

    Now, your local Rails app runs at https://127.0.0.1:3001 with HTTPS enabled.

    Configuring HTTPS for Local Development 123 words
  • Move Chapter 3: Implementing the Web App Manifest in Rails
    Open Chapter 3: Implementing the Web App Manifest in Rails

    Chapter 3: Implementing the Web App Manifest in Rails

    Chapter 3: Implementing the Web App Manifest in Rails
  • Move What is a Web App Manifest?
    Open What is a Web App Manifest?

    What is a Web App Manifest?

    A critical aspect of Progressive Web Apps (PWAs) is their ability to provide an app-like experience on mobile and desktop devices.

    One key component that enables this behavior is the Web App Manifest—a JSON file that defines how the PWA appears and behaves when installed on a user’s device.

    Defining the Web App Manifest

    The Web App Manifest is a simple JSON file that provides metadata about a web application. It allows a PWA to be installed on a device and defines how it should appear in the app launcher or home screen.

    The manifest file typically includes the following properties:

    • name: The full name of the application.
    • short_name: A shorter version of the name for display in tight spaces.
    • start_url: The URL that should load when the app is opened.
    • display: Defines how the app should appear (standalone, fullscreen, minimal-ui, etc.).
    • background_color: The background color of the splash screen.
    • *theme_color
    What is a Web App Manifest? 283 words
  • Move Generating and Serving the Manifest in Rails
    Open Generating and Serving the Manifest in Rails

    Generating and Serving the Manifest in Rails

    Now that we understand the purpose of a Web App Manifest, we need to create and serve this file dynamically in our Rails application.

    1. Creating the manifest.json File

    We will store the manifest file in the app/views/layouts directory and serve it dynamically using Rails' render method.

    Create a new file at app/views/layouts/manifest.json.jbuilder and define its structure:

    json.name "Rails PWA"
    json.short_name "PWA"
    json.start_url root_url
    json.display "standalone"
    json.background_color "#ffffff"
    json.theme_color "#ff5722"
    json.icons [
      {
        src: image_url("icons/icon-192x192.png"),
        sizes: "192x192",
        type: "image/png"
      },
      {
        src: image_url("icons/icon-512x512.png"),
        sizes: "512x512",
        type: "image/png"
      }
    ]
    

    2. Creating a Route for the Manifest

    Next, we need to define a route in config/routes.rb to serve the manifest file:

    get "/manifest.json", to: "manifest
    
    Generating and Serving the Manifest in Rails 235 words
  • Move Customizing App Icons and Splash Screens
    Open Customizing App Icons and Splash Screens

    Customizing App Icons and Splash Screens

    For a PWA to feel truly native, it must have high-quality icons and a custom splash screen that displays when the app is launched.

    1. Creating App Icons

    PWAs require icons in multiple sizes to support different devices. The most common sizes are:

    • 192x192px (for Android home screen)
    • 512x512px (for installation on desktops and larger devices)

    You can generate these icons manually or use an online tool like Real Favicon Generator.

    Place the icons inside app/assets/images/icons/, ensuring the filenames match those referenced in manifest.json.jbuilder.

    2. Generating a Splash Screen for iOS

    Unlike Android, iOS does not fully support the Web App Manifest. Instead, we need to manually define Apple Touch Startup Images.

    Create different splash screen images in PNG format for various screen sizes. Then, add the following lines to application.html.erb inside <head>:

    Customizing App Icons and Splash Screens 212 words
  • Move Chapter 4: Building Service Workers in Rails
    Open Chapter 4: Building Service Workers in Rails

    Chapter 4: Building Service Workers in Rails

    Chapter 4: Building Service Workers in Rails
  • Move Introduction to Service Workers
    Open Introduction to Service Workers

    Introduction to Service Workers

    A key component of Progressive Web Apps (PWAs) is service workers, which enable offline functionality, background sync, and caching.

    Service workers act as a proxy between the browser and the network, allowing PWAs to work even when the user has limited or no internet access.

    1. What Are Service Workers?

    A service worker is a JavaScript file that runs in the background, separate from the main web page.

    Unlike traditional scripts, it operates independently and doesn’t have direct access to the DOM.

    Instead, it intercepts network requests, manages caching, and enables offline capabilities.

    2. Key Features of Service Workers

    Service workers offer several powerful features that make them an essential component of Progressive Web Apps (PWAs):

    i. Offline Support

    One of the most important features of a PWA is the ability to work offline. A service worker intercepts network requests and stores responses in

    Introduction to Service Workers 577 words
  • Move Registering and Installing a Service Worker in Rails
    Open Registering and Installing a Service Worker in Rails

    Registering and Installing a Service Worker in Rails

    To use a service worker in a Rails application, we need to follow a structured approach:

    1. Create a service worker file to define caching behavior and event listeners.
    2. Register the service worker in the front-end code.
    3. Ensure Rails serves the service worker file correctly.

    By integrating service workers, a Rails PWA can intercept network requests, cache assets, and provide an offline experience.

    1. Creating the Service Worker File in Rails

    In a Rails application, service workers should be stored in the app/assets/javascripts or app/javascript directory, depending on whether the app uses the asset pipeline or Webpacker/esbuild.

    Basic Service Worker Script

    Create a new file:

    touch app/javascript/service_worker.js
    

    Now, open service_worker.js and define basic event listeners:

    const CACHE_NAME = "rails-pwa-cache-v1";
    const ASSETS_TO_CACHE = [
      "/",
      "/offline.html",
      "/
    
    Registering and Installing a Service Worker in Rails 485 words
  • Move Handling Events in Service Workers
    Open Handling Events in Service Workers

    Handling Events in Service Workers

    Once a service worker is installed and registered, we need to handle key events like:

    • Fetch Events: Serve cached resources when offline.
    • Update Events: Ensure users get the latest version of the app.
    • Cache Management: Remove old caches to free up storage.

    1. Handling Fetch Events for Offline Access

    When a user requests a resource, the service worker should check if it’s cached. If it is, the service worker serves the cached version instead of making a network request.

    Modify service_worker.js to intercept network requests:

    self.addEventListener("fetch", (event) => {
      event.respondWith(
        caches.match(event.request).then((response) => {
          return response || fetch(event.request);
        })
      );
    });
    
    • If the requested resource is in the cache, it is served immediately.
    • Otherwise, the request is sent to the network.

    This approach allows pages and assets to load even when the user is offline.

    Handling Events in Service Workers 453 words
  • Move Chapter 5: Implementing Caching Strategies for Offline Support
    Open Chapter 5: Implementing Caching Strategies for Offline Support

    Chapter 5: Implementing Caching Strategies for Offline Support

    Chapter 5: Implementing Caching Strategies for Offline Support
  • Move Understanding Caching Strategies
    Open Understanding Caching Strategies

    Understanding Caching Strategies

    Caching is critical in PWAs to ensure fast load times and offline availability.

    Different caching strategies can be used depending on the type of content being served.

    1. Cache-First Strategy

    The cache-first strategy serves resources from the cache first and only requests from the network if the cached version is unavailable. This is ideal for static assets such as JavaScript, CSS, and images.

    Implementation Example

    Modify service_worker.js to use cache-first for static assets:

    self.addEventListener("fetch", (event) => {
      if (event.request.url.includes("/assets/")) {
        event.respondWith(
          caches.match(event.request).then((cachedResponse) => {
            return cachedResponse || fetch(event.request);
          })
        );
      }
    });
    
    • If the requested asset is cached, it is served immediately.
    • Otherwise, it is fetched from the network.

    2. Network-First Strategy

    The network-first strategy is best

    Understanding Caching Strategies 310 words
  • Move Adding Rails API Caching with Service Workers
    Open Adding Rails API Caching with Service Workers

    Adding Rails API Caching with Service Workers

    A PWA often interacts with a Rails API to fetch dynamic data. Efficient caching of API responses is key to delivering an offline experience.

    1. Enabling Caching in Rails API

    In Rails, enable server-side caching by configuring config/environments/production.rb:

    config.action_controller.perform_caching = true
    config.cache_store = :memory_store
    

    For an API endpoint, use caching with expires_in:

    class ArticlesController < ApplicationController
      def index
        articles = Rails.cache.fetch("articles", expires_in: 1.hour) do
          Article.all.to_json
        end
        render json: articles
      end
    end
    

    2. Caching API Responses in the Service Worker

    Modify service_worker.js to cache API responses:

    self.addEventListener("fetch", (event) => {
      if (event.request.url.includes("/api/articles")) {
        event.respondWith(
          caches.open("api-cache").then((cache) => {
            return fetch(e
    
    Adding Rails API Caching with Service Workers 152 words
  • Move Handling Dynamic and Static Content Offline
    Open Handling Dynamic and Static Content Offline

    Handling Dynamic and Static Content Offline

    A fully functional offline PWA must cache both static assets and dynamic content.

    1. Caching HTML Pages for Offline Use

    To cache full pages dynamically, modify service_worker.js:

    self.addEventListener("fetch", (event) => {
      if (event.request.mode === "navigate") {
        event.respondWith(
          fetch(event.request)
            .then((response) => {
              return caches.open("pages-cache").then((cache) => {
                cache.put(event.request, response.clone());
                return response;
              });
            })
            .catch(() => caches.match("/offline.html"))
        );
      }
    });
    

    This ensures that:

    • HTML pages are cached when first visited.
    • If offline, an offline fallback page is displayed.

    2. Preloading Key Static Assets

    To make the app available offline instantly, pre-cache key assets during the service worker’s installation:

    const STATIC_CACHE_NAME = "static-assets-v1";
    
    Handling Dynamic and Static Content Offline 274 words
  • Move Chapter 6: Enabling Push Notifications in Rails PWAs
    Open Chapter 6: Enabling Push Notifications in Rails PWAs

    Chapter 6: Enabling Push Notifications in Rails PWAs

    Chapter 6: Enabling Push Notifications in Rails PWAs
  • Move Introduction to Web Push Notifications
    Open Introduction to Web Push Notifications

    Introduction to Web Push Notifications

    Push notifications are a crucial feature of Progressive Web Apps (PWAs) that keep users engaged by delivering timely updates even when the application is not open.

    1. What Are Web Push Notifications?

    Web push notifications are messages sent from a web application to a user’s device, even if the web page is not open. They allow PWAs to re-engage users with updates, reminders, and personalized messages.

    Key Benefits of Web Push in PWAs:

    • ✔️ Real-time engagement – Notify users of new content instantly.
    • ✔️ Works offline – Notifications can be delivered even when the app is closed.
    • ✔️ No app store dependency – Unlike mobile push notifications, no installation is needed.

    2. How Web Push Works

    A web push system consists of:

    • Push Service: A third-party server (like Firebase Cloud Messaging - FCM) that delivers notifications to users.
    • Service Worker: A script that listens for push events and
    Introduction to Web Push Notifications 291 words
  • Move Setting Up Push Notifications in Rails
    Open Setting Up Push Notifications in Rails

    Setting Up Push Notifications in Rails

    1. Installing Web Push Gem

    Rails does not have built-in support for push notifications, so we use the web-push gem:

    bundle add web-push
    

    Next, generate VAPID (Voluntary Application Server Identification) keys, which authenticate push requests:

    webpush generate_key
    

    This outputs a public and private key. Add them to config/secrets.yml:

    development:
      vapid_public_key: "YOUR_PUBLIC_KEY"
      vapid_private_key: "YOUR_PRIVATE_KEY"
    

    2. Setting Up Subscription Endpoints

    In the Rails backend, create an API endpoint to store push subscriptions. This will handle incoming subscription data from the frontend, which typically includes the endpoint URL and encryption keys.

    class PushSubscriptionsController < ApplicationController
      def create
        subscription = PushSubscription.find_or_initialize_by(endpoint: params[:endpoint])
        subscription.update!(keys: params[:keys].to_json)
    
    
    Setting Up Push Notifications in Rails 577 words
  • Move Handling Notifications with Service Workers
    Open Handling Notifications with Service Workers

    Handling Notifications with Service Workers

    1. Registering the Service Worker

    A Service Worker acts as a background script that allows our Progressive Web App (PWA) to handle push notifications, caching, and background syncing.

    The first step is to register the service worker.

    // In app/javascript/packs/application.js or another entry file
    
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("/service_worker.js").then((registration) => {
        console.log("Service Worker registered with scope:", registration.scope);
      }).catch((error) => {
        console.error("Service Worker registration failed:", error);
      });
    }
    

    We only need to register the service worker once, so there’s no need to register it again within the service_worker.js file itself.


    2. Listening for Push Events in the Service Worker

    Inside the service_worker.js file, we’ll handle the push event. The service worker listens for push events and shows notifications to the

    Handling Notifications with Service Workers 906 words
  • Move Chapter 7: Enhancing User Experience with Background Sync and IndexedDB!
    Open Chapter 7: Enhancing User Experience with Background Sync and IndexedDB!

    Chapter 7: Enhancing User Experience with Background Sync and IndexedDB!

    Chapter 7: Enhancing User Experience with Background Sync and IndexedDB!
  • Move What is Background Sync? Making Requests When the User Regains Connectivity
    Open What is Background Sync? Making Requests When the User Regains Connectivity

    What is Background Sync? Making Requests When the User Regains Connectivity

    1. Understanding Background Sync in PWAs

    Background Sync is a feature that allows web applications to defer network requests until the user has a stable internet connection. This ensures that important actions—such as form submissions or API updates—are not lost due to connectivity issues.

    This feature is crucial for PWAs as it helps provide a seamless user experience by handling network interruptions gracefully. Instead of showing an error when a user submits a form offline, Background Sync queues the request and automatically sends it when the connection is restored.


    2. How Background Sync Works

    • User triggers an action (e.g., submitting a form or saving a draft).
    • Service worker intercepts the request and stores it in IndexedDB if the user is offline.
    • Background Sync API schedules a sync event once the connection is available.
    • Service worker sends the request to the
    What is Background Sync? Making Requests When the User Regains Connectivity 316 words
  • Move Implementing IndexedDB for Persistent Storage
    Open Implementing IndexedDB for Persistent Storage

    Implementing IndexedDB for Persistent Storage

    1. Why Use IndexedDB?

    IndexedDB is a low-level API for storing structured data in the browser.

    Unlike localStorage, it can handle large amounts of data and supports advanced queries.

    Use cases for IndexedDB in a PWA:

    • Caching user-generated data (e.g., form inputs, drafts).
    • Storing API responses to make data available offline.
    • Saving preferences or session information for a personalized experience.

    2. Setting Up IndexedDB in a PWA

    First, we need to open a database and create an object store:

    async function openDatabase() {
      return new Promise((resolve, reject) => {
        const request = indexedDB.open("pwa_db", 1);
    
        request.onupgradeneeded = (event) => {
          const db = event.target.result;
          if (!db.objectStoreNames.contains("requests")) {
            db.createObjectStore("requests", { keyPath: "id" });
          }
        };
    
        request.onsuccess = (event) => resolve(event.target.r
    
    Implementing IndexedDB for Persistent Storage 226 words
  • Move Combining Sync Strategies for Seamless User Experience
    Open Combining Sync Strategies for Seamless User Experience

    Combining Sync Strategies for Seamless User Experience

    To create a truly offline-first experience, we need to combine Background Sync and IndexedDB to ensure users never lose data.

    1. Syncing Data When the User Returns Online

    A common approach is to listen for network status changes and sync data automatically:

    window.addEventListener("online", async () => {
      console.log("Back online! Syncing data...");
      await syncFormData();
    });
    

    This ensures that any pending actions are completed as soon as an internet connection is restored.


    2. Implementing a Cache-First Strategy for Faster Data Access

    Instead of always making network requests, we can cache API responses and serve them from IndexedDB when offline:

    async function fetchWithCache(url) {
      try {
        const response = await fetch(url);
        const data = await response.json();
        await saveDataLocally(url, data);
        return data;
      } catch (error) {
        console.log("Fetching fro
    
    Combining Sync Strategies for Seamless User Experience 300 words
  • Move Chapter 8: Deploying and Hosting a Rails PWA
    Open Chapter 8: Deploying and Hosting a Rails PWA

    Chapter 8: Deploying and Hosting a Rails PWA

    Chapter 8: Deploying and Hosting a Rails PWA
  • Move Choosing the Right Hosting Provider
    Open Choosing the Right Hosting Provider

    Choosing the Right Hosting Provider

    Best Hosting Providers for Rails PWAs

    • Heroku – Simple deployment, automatic scaling, but limited file storage.
    • Render – Similar to Heroku but offers free static hosting.
    • Hetzner / DigitalOcean / Linode / AWS EC2 – Full control over the server but requires manual setup.
    • Fly.io – Optimized for Rails applications with built-in support for WebSockets.

    I personally use Hetzner VPS to host all my personal and professional software projects because I get 100% control over my server.

    You can use Digitalocean or Linode too BUT Hetzner provides same config VPS at half the price than these.


    Why Hetzner for Rails PWA?

    Hetzner Cloud is an excellent hosting option for Rails 8 Progressive Web Apps because it provides:

    • Affordable yet powerful VPS instances with dedicated resources.
    • Full control over the server for containerized deployments.
    • Built-in support for Docker, which Kamal 2 leverages.

    Choosing the Right Hosting Provider 230 words
  • Move Deploying a Rails PWA with Kamal 2 on Hetzner
    Open Deploying a Rails PWA with Kamal 2 on Hetzner

    Deploying a Rails PWA with Kamal 2 on Hetzner

    Kamal 2: Built-In with Rails 8

    Rails 8 includes Kamal 2 out of the box, meaning:

    • The app generator provides a Dockerfile and kamal deploy.yml.
    • Kamal manages zero-downtime deployments using Docker.
    • It automates SSL setup, server configuration, and app updates.

    Dockerfile for Rails 8 PWA (with SQLite)

    #syntax=docker/dockerfile:1
    #check=error=true
    
    #Base Ruby image (Rails 8 compatible)
    ARG RUBY_VERSION=3.3.6
    FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base
    
    #Set working directory
    WORKDIR /rails
    
    #Install required system dependencies
    RUN apt-get update -qq && \
        apt-get install --no-install-recommends -y \
          curl libjemalloc2 libvips sqlite3 \
          nodejs npm yarn && \
        rm -rf /var/lib/apt/lists /var/cache/apt/archives
    
    #Set production environment variables
    ENV RAILS_ENV="production" \
        BUNDLE_DEPLOYMENT="1" \
        BUNDLE_PATH="/usr/local/bundle" \
        BUNDLE
    
    Deploying a Rails PWA with Kamal 2 on Hetzner 568 words
  • Move Configuring SSL and Security Best Practices
    Open Configuring SSL and Security Best Practices

    Configuring SSL and Security Best Practices

    1. Automatic SSL with Kamal 2’s Proxy

    Security is critical for PWAs, and HTTPS is a mandatory requirement for service workers, push notifications, and background sync.

    Kamal 2 simplifies SSL setup by integrating a built-in proxy that:

    • Automatically provisions SSL certificates via Let's Encrypt.
    • Handles SSL renewal without manual intervention.
    • Enforces HTTPS by default, redirecting HTTP traffic securely.

    How Kamal 2 Sets Up SSL Automatically

    Unlike traditional setups where SSL required manual Nginx configuration or third-party services like Certbot, Kamal 2 does everything for you.

    Once Kamal is configured and the proxy is enabled, it will:

    1. Request an SSL certificate for your domain.
    2. Configure the web proxy to serve traffic only over HTTPS.
    3. Renew the certificate before it expires.

    This is particularly useful because browsers **block many PWA features on non-secure origins (HTT

    Configuring SSL and Security Best Practices 645 words
  • Move Chapter 9: Performance Optimization and SEO for Rails PWAs
    Open Chapter 9: Performance Optimization and SEO for Rails PWAs

    Chapter 9: Performance Optimization and SEO for Rails PWAs

    Chapter 9: Performance Optimization and SEO for Rails PWAs
  • Move Optimizing Rails Assets for PWA Performance
    Open Optimizing Rails Assets for PWA Performance

    Optimizing Rails Assets for PWA Performance

    Why Asset Optimization is Crucial for PWAs

    Performance is a core requirement of Progressive Web Apps. Google’s Core Web Vitals emphasize fast loading times, smooth interactions, and visual stability, all of which are affected by asset sizes and loading strategies.

    Optimizing assets in a Rails PWA means:

    • Faster initial load times → Essential for first-time visitors.
    • Better Lighthouse and Core Web Vitals scores → Affects SEO ranking.
    • Reduced bandwidth usage → Important for mobile users.

    1. Asset Compression in Rails 8

    Rails 8 uses Importmaps and Propshaft for asset management. To reduce asset sizes:

    • Kamal 2 Deployments (Thruster + Puma): Asset compression and delivery are automatically handled by the web server.
    • Ensure Precompressed Assets: Kamal 2 typically runs asset compilation within the Dockerfile or deploy configuration, so manual execution is unnecessary.

    Enab

    Optimizing Rails Assets for PWA Performance 431 words
  • Move Ensuring SEO and Indexability of PWAs
    Open Ensuring SEO and Indexability of PWAs

    Ensuring SEO and Indexability of PWAs

    1. Enabling Search Engine Crawling

    By default, PWAs use client-side rendering (CSR), which is bad for SEO unless handled correctly. Solutions include:

    • Server-Side Rendering (SSR) → Use Turbo Streams to render critical content server-side.
    • Pre-rendering with prerender.io → Generates static HTML snapshots for search engines.

    Modify robots.txt to allow search engine crawling:

    User-agent: *
    Allow: /
    

    2. Adding Structured Data for Google Search

    Use JSON-LD structured data to help Google understand your content. Add this in app/views/layouts/application.html.erb:

    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "WebApplication",
      "name": "My Rails PWA",
      "url": "https://myrailsapp.com",
      "operatingSystem": "All",
      "applicationCategory": "WebApplication"
    }
    </script>
    

    This helps your app appear as an installable PWA in

    Ensuring SEO and Indexability of PWAs 213 words
  • Move Measuring and Improving Performance with Lighthouse
    Open Measuring and Improving Performance with Lighthouse

    Measuring and Improving Performance with Lighthouse

    1. Running a Lighthouse Audit

    Google’s Lighthouse tool evaluates:

    • Performance → Speed, asset loading, lazy loading.
    • SEO → Indexability, metadata, structured data.
    • PWA compliance → Installability, service worker usage.

    Run a Lighthouse audit in Chrome DevTools:

    • Open DevTools (F12) → Lighthouse Tab.
    • Select Performance, PWA, SEO.
    • Click "Generate Report".

    2. Analyzing Lighthouse Scores

    Your score will be rated out of 100 for:

    • Performance (aim for 90+)
    • SEO (aim for 100)
    • PWA compliance (must be 100)

    3. Fixing Common Lighthouse Issues

    • ✅ "Reduce Unused JavaScript" → Tree-shake your JavaScript files in Webpack.
    • ✅ "Eliminate Render-Blocking Resources" → Use async and defer for JavaScript:
      • <script src="application.js" defer></script>
    • ✅ "Serve Images in Next-Gen Formats" → Use WebP instead of PNG/JPG:
    Measuring and Improving Performance with Lighthouse 237 words
  • Move Chapter 10: Advanced Topics and Future Trends in Rails PWAs
    Open Chapter 10: Advanced Topics and Future Trends in Rails PWAs

    Chapter 10: Advanced Topics and Future Trends in Rails PWAs

    Chapter 10: Advanced Topics and Future Trends in Rails PWAs
  • Move Integrating PWA with Rails Hotwire and Turbo Streams
    Open Integrating PWA with Rails Hotwire and Turbo Streams

    Integrating PWA with Rails Hotwire and Turbo Streams

    Why Combine Hotwire and PWAs?

    Hotwire, introduced by Rails 7+, provides Turbo and Stimulus for building interactive, real-time applications without excessive JavaScript.

    Combining Hotwire with PWA features enhances performance while keeping development efficient.


    1. How Turbo Streams Enhance PWAs

    PWAs rely on fast, seamless interactions, and Turbo Streams provide:

    • Server-side rendering with WebSockets → Faster updates without full page reloads.
    • Reduced JavaScript complexity → Eliminates unnecessary React or Vue dependencies.
    • Offline-friendly updates → Works with service workers for caching.

    2. Setting Up Turbo Streams in Rails 8

    First, add Turbo Streams to a model (e.g., Message in a chat app):

    class Message < ApplicationRecord
      after_create_commit -> { broadcast_append_to "chat", target: "messages" }
    end
    

    In the view:

    <div id="
    
    Integrating PWA with Rails Hotwire and Turbo Streams 226 words
  • Move Exploring Progressive Web App Features Beyond Basics
    Open Exploring Progressive Web App Features Beyond Basics

    Exploring Progressive Web App Features Beyond Basics

    PWAs are evolving, with new APIs expanding their capabilities.


    1. App Shortcuts for Quick Access

    PWA shortcuts allow users to launch actions directly from the home screen.

    Add the following to manifest.json:

    "shortcuts": [
      {
        "name": "New Post",
        "short_name": "Post",
        "description": "Create a new post quickly",
        "url": "/posts/new",
        "icons": [{ "src": "/icons/post.png", "sizes": "192x192", "type": "image/png" }]
      }
    ]
    

    Users can now long-press the app icon to directly access /posts/new.


    2. Web Payments API for Seamless Checkout

    The Web Payments API allows direct credit card or Google Pay/Apple Pay payments without leaving the PWA.

    Add this to JavaScript inside a Rails checkout page:

    if (window.PaymentRequest) {
      const payment = new PaymentRequest(
        [{ supportedMethods: "basic-card" }],
        { total: { label: "Total", amount: 
    
    Exploring Progressive Web App Features Beyond Basics 228 words
  • Move The Future of PWA and Rails Development
    Open The Future of PWA and Rails Development

    The Future of PWA and Rails Development

    PWAs continue to evolve, and Rails 8+ is well-equipped to embrace modern web standards.


    1. Emerging Web Capabilities

    • 🚀 File System Access API → Allows PWAs to edit local files (ideal for editors, IDEs).
    • 🚀 Web Bluetooth & WebUSB → Connect PWAs directly to hardware devices.
    • 🚀 Background Fetch → Large downloads continue even when the PWA is closed.

    These APIs make PWAs feel even closer to native mobile apps.


    2. Rails Adapting to Modern Web Trends

    Rails 8+ focuses on:

    • More Hotwire adoption → Replacing complex frontend frameworks.
    • Built-in PWA support → New Rails generators for PWA setups.
    • Better deployment with Kamal 2 → Auto-configured SSL, containerized apps, and multi-region scaling.

    Rails developers should invest in mastering PWAs, as they are only going to grow in importance.

    The Future of PWA and Rails Development 150 words
  • Move Example App
    Open Example App

    Example App

    Example App
  • Move TodosTiger PWA
    Open TodosTiger PWA

    TodosTiger PWA

    TodoTiger PWA is a Progressive Web App demonstrating a PWA with Ruby on Rails version 8.

    It uses TailwindCSS 3, ImportMaps, Stimulus, Turbo Streams, Propshaft, etc. to manage the assets, styles, and todos.

    Screenshot from 2025-03-03 13-04-09.png

    Implementing manifest.js and service_workers.js

    The PWA uses its own Rails Controller to provide manifest.js and service_workers.js, and a stimulus controller to provide the install app button.

    Screenshot from 2025-03-03 13-09-10.png

    Implementing the Install App button

    Screenshot from 2025-03-03 13-11-49.png

    Source Code

    The source code can be accessed from [https://github.com/cmittal790/todostiger-pwa](http

    TodosTiger PWA 92 words
  • Move Resources
    Resources
  • Move Articles and Videos
    Articles and Videos 113 words