Back to journal

    Developer journal

    Building an Offline-First PWA with React and Vite: Service Workers, Caching, and Data Synchronization

    Learn how to build an offline-first Progressive Web App with React and Vite using service workers, Workbox caching strategies, IndexedDB, offline fallbacks, and reliable data synchronization.

    29 min read48 sections
    Building an Offline-First PWA with React and Vite: Service Workers, Caching, and Data Synchronization article cover
    In this article48 sectionsBrowse sections
    29 min read · 5,626 words

    Building an Offline-First PWA with React and Vite: Service Workers, Caching, and Data Synchronization

    A modern web application should not become completely unusable just because a user's internet connection disappears.

    Consider a job portal. A user might be reading job listings on a train, filling out an application in an area with poor connectivity, or trying to revisit a page after losing their connection. If every screen depends on a successful network request, the experience quickly becomes frustrating.

    Progressive Web Apps (PWAs) help solve this problem by bringing capabilities such as service workers, caching, and local storage to web applications.

    However, adding a service worker does not automatically make an application offline-first. A reliable implementation needs a deliberate strategy for static assets, API requests, local data, queued operations, synchronization, and application updates.

    In this guide, we will build an offline-first foundation using React, Vite, vite-plugin-pwa, Workbox, and IndexedDB.

    1. Understanding Offline-First Architecture

    An offline-first application is designed to remain useful even when the network is unavailable.

    Instead of treating the network as the only source of application data, it uses local resources whenever appropriate and synchronizes with the server when connectivity is available.

    A typical architecture looks like this:

                        React Application
                               |
                   Application Data Layer
                               |
                 +-------------+-------------+
                 |             |             |
              API Client    IndexedDB    Cache Storage
                 |             |             |
                 |        Pending Queue      |
                 |             |             |
                 +-------------+-------------+
                               |
                         Service Worker
                               |
                        Network Requests
                               |
                          Backend API
    

    Each component has a different responsibility:

    ComponentResponsibility
    ReactUser interface and application state
    API clientCommunicates with backend services
    Service workerIntercepts requests and manages caching
    Cache APIStores request/response pairs
    IndexedDBStores structured application data and pending operations
    BackendAuthoritative data and synchronization

    The important distinction is that Cache Storage and IndexedDB are not interchangeable.

    • Cache Storage is designed to store HTTP requests and responses.
    • IndexedDB stores structured data, records, files, and application-managed queues.
    • Local storage is suitable for small synchronous key-value settings, not large offline datasets or transactional queues.

    For a deeper understanding of PWA capabilities, see the MDN Progressive Web Apps guide.

    2. Creating the React and Vite Project

    If you already have a React and Vite project, you can skip the project creation step.

    Otherwise, create one:

    npm create vite@latest offline-pwa -- --template react
    cd offline-pwa
    npm install
    

    Install the PWA plugin:

    npm install -D vite-plugin-pwa
    

    For the IndexedDB examples, we will also use the lightweight idb library:

    npm install idb
    

    The vite-plugin-pwa package integrates Workbox with Vite and can generate the web app manifest, service worker, and registration code.

    Official documentation: Vite Plugin PWA.

    3. Configuring the Web App Manifest

    The web app manifest provides information about your application, including its name, icons, theme, and preferred display mode.

    Create your manifest through the manifest option in vite.config.js.

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import { VitePWA } from 'vite-plugin-pwa'
    
    export default defineConfig({
      plugins: [
        react(),
    
        VitePWA({
          registerType: 'prompt',
    
          manifest: {
            name: 'Offline First App',
            short_name: 'OfflineApp',
            description: 'An offline-first React application',
            theme_color: '#111827',
            background_color: '#111827',
            display: 'standalone',
            start_url: '/',
            scope: '/',
            icons: [
              {
                src: '/icons/pwa-192x192.png',
                sizes: '192x192',
                type: 'image/png',
              },
              {
                src: '/icons/pwa-512x512.png',
                sizes: '512x512',
                type: 'image/png',
              },
              {
                src: '/icons/pwa-512x512.png',
                sizes: '512x512',
                type: 'image/png',
                purpose: 'any maskable',
              },
            ],
          },
        }),
      ],
    })
    

    Place the corresponding icon files inside the Vite public/icons directory.

    public/
      icons/
        pwa-192x192.png
        pwa-512x512.png
    

    The plugin generates the manifest and connects it to the application.

    A few important manifest properties:

    • name: Full application name.
    • short_name: Compact name used where space is limited.
    • display: Defines how the installed application is presented.
    • start_url: The URL opened when launching the application.
    • scope: Defines the navigation scope of the installed application.
    • theme_color: Browser and application theme color.
    • background_color: Background used while the application loads.
    • icons: Application icons in supported sizes and formats.

    A manifest does not provide offline functionality by itself. Offline behavior comes primarily from the service worker and the caching architecture.

    4. Understanding the Service Worker Lifecycle

    A service worker is a JavaScript file that runs separately from the main browser thread.

    It can intercept supported network requests, manage cached responses, and handle certain background events.

    Unlike normal application JavaScript, a service worker:

    • Cannot directly access the DOM.
    • Cannot use window or localStorage.
    • Can be terminated by the browser when idle.
    • Must communicate with application pages through supported messaging mechanisms.
    • Requires a secure context, normally HTTPS (localhost is permitted for development).

    A service worker generally follows three lifecycle stages.

    4.1 Install

    The browser downloads the service worker and triggers its install event.

    This is commonly where required offline resources are prepared.

    4.2 Activate

    After installation, the browser activates the new worker when lifecycle conditions permit.

    This is a suitable time to clean up obsolete caches and prepare the new worker.

    4.3 Fetch

    Once the service worker controls a page, it can intercept requests made by that page within its scope.

    This is where caching strategies become important.

    The lifecycle matters when deploying updates. A newly downloaded service worker may remain waiting while older application tabs are still controlled by the previous worker.

    Do not assume that publishing a new build immediately replaces every active application session.

    Reference: MDN — Service Worker API.

    5. Understanding Service Worker Caching Strategies

    Different resources need different caching strategies.

    Caching an application logo and caching a user's account information should not be treated the same way.

    Here are the most commonly used strategies.

    5.1 Cache First

    The application checks the cache before accessing the network.

    Request
       |
    Check Cache
       |
       +-- Found --> Return Cached Response
       |
       +-- Missing --> Fetch From Network
                             |
                        Cache Response
                             |
                        Return Response
    

    Best suited for:

    • Fonts.
    • Logos.
    • Static images.
    • Versioned assets.
    • Resources that rarely change.

    The main advantage is speed and offline availability.

    The disadvantage is that cached content may become outdated unless an expiration or invalidation policy exists.

    5.2 Network First

    The application tries the network first and falls back to the cache if the network request fails.

    Request
       |
    Try Network
       |
       +-- Success --> Cache Response --> Return
       |
       +-- Failure --> Check Cache
                             |
                             +-- Found --> Return Cached Response
                             |
                             +-- Missing --> Offline Fallback
    

    Best suited for:

    • Public API responses.
    • Frequently changing content.
    • Data where freshness is important.

    This strategy provides fresher data when connectivity is available while still allowing cached responses to be used offline.

    5.3 Stale While Revalidate

    The application returns an existing cached response immediately while updating the cache using a network request.

    Request
       |
    Check Cache
       |
       +-- Found --> Return Cached Response
       |                  |
       |              Fetch Network
       |                  |
       |              Update Cache
       |
       +-- Missing --> Fetch Network
    

    Best suited for:

    • Public content.
    • Blog articles.
    • Product catalogues.
    • Images and other frequently reused resources.

    The user receives a fast response, but the returned content might not be the latest version.

    5.4 Network Only

    Always access the network.

    Best suited for:

    • Payment processing.
    • Sensitive account operations.
    • Authentication-related operations.
    • Real-time transactions.
    • Operations that must not use stale cached responses.

    5.5 Cache Only

    Always return a previously cached resource.

    Best suited for:

    • Precached application assets.
    • Offline fallback resources.
    • Resources explicitly downloaded for offline use.

    The right strategy depends on the resource, not simply on whether the application supports offline mode.

    6. Configuring Workbox with Vite

    Workbox provides service worker utilities that simplify caching and offline behavior.

    The vite-plugin-pwa plugin integrates Workbox into the Vite build process.

    We can configure runtime caching directly through the plugin.

    Update vite.config.js:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import { VitePWA } from 'vite-plugin-pwa'
    
    export default defineConfig({
      plugins: [
        react(),
    
        VitePWA({
          registerType: 'prompt',
    
          includeAssets: [
            'favicon.ico',
            'offline.html',
            'icons/pwa-192x192.png',
            'icons/pwa-512x512.png',
          ],
    
          manifest: {
            name: 'Offline First App',
            short_name: 'OfflineApp',
            description: 'An offline-first React application',
            theme_color: '#111827',
            background_color: '#111827',
            display: 'standalone',
            start_url: '/',
            scope: '/',
            icons: [
              {
                src: '/icons/pwa-192x192.png',
                sizes: '192x192',
                type: 'image/png',
              },
              {
                src: '/icons/pwa-512x512.png',
                sizes: '512x512',
                type: 'image/png',
              },
            ],
          },
    
          workbox: {
            navigateFallback: 'index.html',
    
            globPatterns: [
              '**/*.{js,css,html,ico,png,svg,woff2}',
            ],
    
            runtimeCaching: [
              {
                // Static images
                urlPattern: /\.(?:png|jpg|jpeg|svg|webp|avif)$/i,
    
                handler: 'CacheFirst',
    
                options: {
                  cacheName: 'static-images',
    
                  expiration: {
                    maxEntries: 100,
                    maxAgeSeconds: 30 * 24 * 60 * 60,
                  },
    
                  cacheableResponse: {
                    statuses: [0, 200],
                  },
                },
              },
    
              {
                // Public, read-only API endpoints only
                urlPattern: ({
                  url,
                  request,
                }) => {
                  return (
                    url.origin === 'https://api.example.com' &&
                    url.pathname.startsWith('/api/public/') &&
                    request.method === 'GET'
                  )
                },
    
                handler: 'NetworkFirst',
    
                options: {
                  cacheName: 'public-api-cache',
    
                  networkTimeoutSeconds: 5,
    
                  expiration: {
                    maxEntries: 50,
                    maxAgeSeconds: 5 * 60,
                  },
    
                  cacheableResponse: {
                    statuses: [200],
                  },
                },
              },
            ],
          },
        }),
      ],
    })
    

    Replace https://api.example.com with your actual backend API origin.

    This configuration demonstrates:

    • Precache generation for application build assets.
    • Cache-first behavior for images.
    • Network-first behavior for selected public API GET requests.
    • An application-shell fallback for navigation requests.
    • Automatic cleanup of expired and excess cached entries through Workbox expiration policies.

    Important: The API caching rule deliberately targets only public, read-only endpoints. Do not blindly cache authenticated user data, payment responses, private account information, or responses containing sensitive information.

    For cross-origin APIs, ensure the backend's CORS configuration allows the frontend origin. Also verify that responses have appropriate HTTP cache headers and that your service worker's cache policy does not expose data across user sessions.

    Official reference: Vite Plugin PWA — Configuration.

    7. Creating a Useful Offline Fallback

    An offline application should communicate what happened instead of showing a generic browser error or an empty screen.

    Create public/offline.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta name="theme-color" content="#111827" />
    
      <title>You're Offline</title>
    
      <style>
        body {
          margin: 0;
          min-height: 100vh;
          display: grid;
          place-items: center;
          padding: 24px;
          background: #111827;
          color: white;
          font-family: system-ui, sans-serif;
          text-align: center;
        }
    
        main {
          max-width: 420px;
        }
    
        button {
          padding: 12px 20px;
          border: 0;
          border-radius: 8px;
          background: #6366f1;
          color: white;
          cursor: pointer;
        }
      </style>
    </head>
    
    <body>
      <main>
        <h1>You're currently offline</h1>
    
        <p>
          Your internet connection is unavailable.
          Check your connection and try again.
        </p>
    
        <button onclick="location.reload()">
          Try Again
        </button>
      </main>
    </body>
    </html>
    

    The includeAssets option adds this file to the precache.

    There is an important distinction between an offline document and an application-shell fallback.

    • offline.html is a standalone fallback resource.
    • index.html is the entry point for a React single-page application.

    The navigateFallback: 'index.html' configuration serves the application shell for supported navigation requests. It does not automatically replace failed API requests with offline.html.

    For a complete implementation, handle failed API requests in the application data layer and display an appropriate offline state within React.

    Also make sure your server does not rewrite missing JavaScript, API, or asset requests into index.html incorrectly.

    8. Handling Offline States in React

    The browser exposes navigator.onLine and the online and offline events.

    These are useful signals, but they do not guarantee that your backend is reachable.

    For example, a device may be connected to Wi-Fi while the router has no internet access.

    A simple React hook can track the browser's connectivity state.

    Create src/hooks/useNetworkStatus.js:

    import { useEffect, useState } from 'react'
    
    export function useNetworkStatus() {
      const [isOnline, setIsOnline] = useState(
        () => navigator.onLine
      )
    
      useEffect(() => {
        const handleOnline = () => setIsOnline(true)
        const handleOffline = () => setIsOnline(false)
    
        window.addEventListener('online', handleOnline)
        window.addEventListener('offline', handleOffline)
    
        return () => {
          window.removeEventListener('online', handleOnline)
          window.removeEventListener('offline', handleOffline)
        }
      }, [])
    
      return isOnline
    }
    

    Use it inside a component:

    import { useNetworkStatus } from './hooks/useNetworkStatus'
    
    function NetworkStatus() {
      const isOnline = useNetworkStatus()
    
      if (isOnline) {
        return null
      }
    
      return (
        <div
          role="status"
          className="fixed bottom-4 left-4 right-4
                     rounded-lg bg-yellow-100 p-3
                     text-center text-yellow-900"
        >
          You're offline. Some features may be unavailable.
        </div>
      )
    }
    
    export default NetworkStatus
    

    Render the component near the root of your application.

    For a production application, distinguish between:

    1. Browser reports offline.
    2. Browser reports online, but the backend is unreachable.
    3. Backend responds with a server error.
    4. Backend responds with a gateway error.
    5. Request times out.
    6. Request fails because of authentication or authorization.

    These are different failure conditions and should not all be presented as an offline error.

    A lightweight health-check endpoint can help determine backend availability when necessary.

    9. Using IndexedDB for Offline Data

    Cache Storage works well for HTTP responses, but it is not the right solution for managing structured application data.

    Consider a job portal where a user saves a job while offline.

    The application needs to remember:

    • Which job was saved.
    • Which user performed the operation.
    • When the operation was created.
    • Whether it has been synchronized.
    • Whether synchronization failed.
    • How many attempts have been made.

    This is a structured data problem, making IndexedDB a better choice.

    We will use the idb package to simplify IndexedDB operations.

    Create src/db/database.js:

    import { openDB } from 'idb'
    
    export const dbPromise = openDB('offline-app-db', 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains('pending-actions')) {
          const store = db.createObjectStore('pending-actions', {
            keyPath: 'id',
          })
    
          store.createIndex('createdAt', 'createdAt')
        }
    
        if (!db.objectStoreNames.contains('saved-jobs')) {
          db.createObjectStore('saved-jobs', {
            keyPath: 'jobId',
          })
        }
      },
    })
    

    This creates two object stores:

    • pending-actions: Stores operations waiting for synchronization.
    • saved-jobs: Stores locally available saved-job data.

    You can extend the database schema as your application grows.

    Saving Data Locally

    Create src/db/jobStorage.js:

    import { dbPromise } from './database'
    
    export async function saveJobLocally(job) {
      const db = await dbPromise
    
      await db.put('saved-jobs', {
        ...job,
        updatedAt: Date.now(),
      })
    }
    
    export async function getSavedJobs() {
      const db = await dbPromise
    
      return db.getAll('saved-jobs')
    }
    

    Now the application can display previously saved job information without requiring an API request.

    Remember that local data may become outdated. Your interface should make it clear when the displayed information was last synchronized.

    10. Building an Offline Action Queue

    Storing data locally is only part of the problem.

    If a user performs an operation while offline, the application needs a reliable way to send it to the backend later.

    For example:

    User saves a job
           |
    Check Network
           |
           +-- Online --> Send API Request
           |
           +-- Offline --> Save Action in IndexedDB
                                 |
                            Wait for Connection
                                 |
                            Retry Synchronization
                                 |
                            Backend Confirms
                                 |
                            Remove Pending Action
    

    Create src/db/actionQueue.js:

    import { dbPromise } from './database'
    
    export async function addPendingAction(action) {
      const db = await dbPromise
    
      const item = {
        id: crypto.randomUUID(),
        type: action.type,
        payload: action.payload,
        createdAt: Date.now(),
        attempts: 0,
        status: 'pending',
        idempotencyKey: crypto.randomUUID(),
      }
    
      await db.add('pending-actions', item)
    
      return item
    }
    
    export async function getPendingActions() {
      const db = await dbPromise
    
      return db.getAll('pending-actions')
    }
    
    export async function removePendingAction(id) {
      const db = await dbPromise
    
      await db.delete('pending-actions', id)
    }
    
    export async function updatePendingAction(id, updates) {
      const db = await dbPromise
    
      const existing = await db.get('pending-actions', id)
    
      if (!existing) {
        return
      }
    
      await db.put('pending-actions', {
        ...existing,
        ...updates,
      })
    }
    

    Each action has a unique ID and an idempotency key.

    The idempotency key is important because retrying a request does not guarantee that the previous attempt failed before reaching the server.

    For example:

    1. The client sends a request.
    2. The backend processes it successfully.
    3. The response is lost because the network disconnects.
    4. The client retries the request.

    Without idempotency protection, the backend might process the same operation twice.

    The backend should recognize repeated idempotency keys and return the previously recorded result instead of repeating the operation.

    An idempotency key generated by the client is not sufficient by itself. The server must implement and persist the corresponding idempotency behavior.

    11. Synchronizing Pending Actions

    Create a synchronization service that reads pending actions from IndexedDB and sends them to the backend.

    Create src/services/syncService.js:

    import {
      getPendingActions,
      removePendingAction,
      updatePendingAction,
    } from '../db/actionQueue'
    
    const API_URL = import.meta.env.VITE_API_URL
    
    async function processAction(action) {
      const response = await fetch(
        `${API_URL}/api/jobs/${action.payload.jobId}/save`,
        {
          method: 'POST',
    
          headers: {
            'Content-Type': 'application/json',
    
            'Idempotency-Key': action.idempotencyKey,
          },
    
          body: JSON.stringify(action.payload),
          credentials: 'include',
        }
      )
    
      if (!response.ok) {
        const error = new Error(
          `Synchronization failed: ${response.status}`
        )
    
        error.status = response.status
    
        throw error
      }
    
      return response.json()
    }
    
    export async function synchronizePendingActions() {
      if (!navigator.onLine) {
        return
      }
    
      const actions = await getPendingActions()
    
      for (const action of actions) {
        try {
          await processAction(action)
    
          await removePendingAction(action.id)
        } catch (error) {
          const attempts = action.attempts + 1
    
          await updatePendingAction(action.id, {
            attempts,
            lastAttemptAt: Date.now(),
            lastError: error.message,
            status: 'pending',
          })
    
          // Do not retry indefinitely for permanent errors.
          if (
            error.status >= 400 &&
            error.status < 500 &&
            error.status !== 408 &&
            error.status !== 429
          ) {
            await updatePendingAction(action.id, {
              status: 'needs-attention',
            })
          }
    
          // Stop if connectivity or the server is unavailable.
          if (!navigator.onLine || error.status >= 500) {
            break
          }
        }
      }
    }
    

    This is a simplified synchronization example. A production queue should also implement:

    • Maximum retry attempts.
    • Exponential backoff with jitter.
    • Retry scheduling.
    • Authentication refresh and session-expiration handling.
    • Permanent failure handling.
    • Conflict resolution.
    • Queue limits and storage management.
    • Server-side idempotency enforcement.

    A failed operation should not automatically be retried forever.

    For example, a validation error or an authorization failure usually requires user intervention rather than another identical request.

    Trigger Synchronization When Connectivity Returns

    Create src/hooks/useOfflineSync.js:

    import { useEffect } from 'react'
    import { synchronizePendingActions } from '../services/syncService'
    
    export function useOfflineSync() {
      useEffect(() => {
        const sync = () => {
          synchronizePendingActions().catch(console.error)
        }
    
        window.addEventListener('online', sync)
    
        sync()
    
        return () => {
          window.removeEventListener('online', sync)
        }
      }, [])
    }
    

    Call this hook once in your root application component.

    import { useOfflineSync } from './hooks/useOfflineSync'
    import NetworkStatus from './components/NetworkStatus'
    
    function App() {
      useOfflineSync()
    
      return (
        <>
          <NetworkStatus />
    
          {/* Application routes */}
        </>
      )
    }
    
    export default App
    

    This approach retries queued operations while the application is running.

    It is a useful baseline, but it does not guarantee that synchronization will happen while the application is closed.

    12. Background Synchronization

    The Background Synchronization API can allow a service worker to retry certain operations when the browser determines that connectivity is available.

    The general process is:

    1. The application stores a pending operation in IndexedDB.
    2. The application registers a background synchronization task.
    3. The browser dispatches a synchronization event when appropriate.
    4. The service worker reads the pending operation.
    5. The service worker sends it to the backend.
    6. The queue is updated after the result is handled.

    However, Background Sync has limited browser availability. It is not supported consistently across all major browsers.

    You should treat it as an enhancement rather than a mandatory dependency.

    For compatibility, retain foreground synchronization through:

    • The online event.
    • Application startup.
    • Page visibility changes.
    • Explicit retry actions.
    • Periodic checks while the application is active.

    Do not assume the browser will run background synchronization at an exact time or guarantee delivery.

    Reference: MDN — Background Synchronization API.

    13. Handling Axios and Service Worker Requests

    Many React applications use Axios instead of the native Fetch API.

    For example:

    import axios from 'axios'
    
    const api = axios.create({
      baseURL: import.meta.env.VITE_API_URL,
      timeout: 15000,
      withCredentials: true,
    })
    
    export default api
    

    Axios requests are still network requests and can be intercepted by the service worker when they fall within its scope.

    You do not need to replace Axios with fetch() simply to use service worker caching.

    However, there are important differences between the responsibilities of these layers.

    LayerResponsibility
    AxiosAPI requests, headers, interceptors, response handling
    Service workerRequest interception and cache strategies
    IndexedDBDurable local application data and retry queues
    ReactUI states, errors, loading, offline indicators

    A common mistake is attempting to implement the entire offline architecture inside Axios interceptors.

    Axios interceptors run in the application context. They are not a replacement for service worker lifecycle events or persistent background processing.

    A better approach is to use a dedicated data layer.

    For example:

    import api from './api'
    import { addPendingAction } from '../db/actionQueue'
    
    export async function saveJob(jobId) {
      const payload = { jobId }
    
      try {
        const response = await api.post(
          `/api/jobs/${jobId}/save`,
          payload
        )
    
        return {
          success: true,
          queued: false,
          data: response.data,
        }
      } catch (error) {
        const status = error.response?.status
    
        const isNetworkFailure =
          !error.response &&
          (
            error.code === 'ERR_NETWORK' ||
            error.code === 'ECONNABORTED'
          )
    
        if (!isNetworkFailure) {
          throw error
        }
    
        const queuedAction = await addPendingAction({
          type: 'SAVE_JOB',
          payload,
        })
    
        return {
          success: true,
          queued: true,
          data: queuedAction,
        }
      }
    }
    

    This example queues an operation only when the request fails at the network level.

    It deliberately does not queue every failed request. HTTP errors such as 400, 401, 403, and 500 need different handling.

    Also, a timeout does not prove that the server did not process the request. That is another reason why server-side idempotency is essential.

    For a production application, define which operations are safe to queue and make the UI communicate that an action is pending rather than already confirmed by the server.

    14. Handling Service Worker Updates in React

    One of the most overlooked PWA problems is application updates.

    Imagine a user has your application open for several hours. During that time, you deploy a new frontend build.

    The browser downloads the updated service worker, but the old worker may continue controlling the existing page until the lifecycle allows the new worker to activate.

    This can lead to situations where:

    • The HTML is from an older build.
    • Some JavaScript assets belong to a newer build.
    • A user continues using outdated application logic.
    • API response formats change while old frontend code remains active.

    The vite-plugin-pwa React integration provides a convenient way to handle update notifications.

    Install the required helper:

    npm install -D workbox-window
    

    Add the React type declaration if your project uses TypeScript:

    /// <reference types="vite-plugin-pwa/react" />
    

    Create src/components/PWAUpdatePrompt.jsx:

    import { useRegisterSW } from 'virtual:pwa-register/react'
    
    function PWAUpdatePrompt() {
      const {
        needRefresh: [needRefresh],
        updateServiceWorker,
      } = useRegisterSW()
    
      if (!needRefresh) {
        return null
      }
    
      return (
        <div className="fixed bottom-4 right-4 rounded-xl
                        bg-white p-4 shadow-lg">
          <p className="mb-3 font-medium">
            A new version is available.
          </p>
    
          <button
            onClick={() => updateServiceWorker(true)}
            className="rounded-lg bg-indigo-600
                       px-4 py-2 text-white"
          >
            Update Now
          </button>
        </div>
      )
    }
    
    export default PWAUpdatePrompt
    

    Render it inside your root component.

    function App() {
      return (
        <>
          <PWAUpdatePrompt />
    
          {/* Application routes */}
        </>
      )
    }
    

    The true argument requests activation of the waiting service worker and reloads the page after the update process.

    Using registerType: 'prompt' gives users an opportunity to finish their current work before refreshing.

    Avoid automatically replacing an active application session when users may have unsaved form data or pending operations.

    Official reference: Vite Plugin PWA — React Integration.

    15. Cache Versioning and Cleanup

    Caching without a cleanup strategy eventually creates problems.

    For example, suppose your application uses the following caches:

    static-assets-v1
    static-images-v1
    api-cache-v1
    

    After deploying a new version, the application may no longer need some of the old cache entries.

    Workbox provides cache management and expiration utilities.

    The expiration configuration used earlier automatically limits the number of entries and their age.

    For custom caches, you can also clean up old cache names during the service worker's activation lifecycle.

    Example of a basic cleanup pattern:

    const CURRENT_CACHES = [
      'static-assets-v2',
      'static-images-v2',
      'public-api-cache-v2',
    ]
    
    self.addEventListener('activate', (event) => {
      event.waitUntil(
        caches.keys().then((cacheNames) => {
          return Promise.all(
            cacheNames
              .filter((name) => {
                return (
                  name.startsWith('my-app-') &&
                  !CURRENT_CACHES.includes(name)
                )
              })
              .map((name) => caches.delete(name))
          )
        })
      )
    })
    

    This is a standalone cleanup pattern for a custom service worker. Do not copy it into a generated Workbox service worker without understanding how its cache names are managed.

    The general principle is to version caches deliberately and remove obsolete application-owned caches without deleting unrelated caches.

    Also remember that browser storage is not guaranteed to be permanent. Users can clear it, and browsers may evict storage under pressure.

    For important user data, synchronization with a server remains necessary.

    16. Handling Different Server and Network Errors

    An offline-first application should distinguish between network failures and backend failures.

    Consider these scenarios:

    SituationMeaningSuggested UI
    No network connectionDevice is offlineOffline indicator
    Request timeoutResponse did not arrive in timeRetry option
    HTTP 401Authentication requiredSign-in prompt
    HTTP 403Permission deniedAccess denied
    HTTP 404Resource not foundNot found page
    HTTP 500Backend server errorServer unavailable
    HTTP 502Gateway errorGateway unavailable
    HTTP 503Service temporarily unavailableTry again later

    A useful application can expose a common error classification function.

    export function classifyApiError(error) {
      if (!error.response) {
        return {
          type: 'NETWORK_ERROR',
          message: 'Unable to reach the server.',
        }
      }
    
      const status = error.response.status
    
      if (status === 401) {
        return {
          type: 'UNAUTHORIZED',
          message: 'Please sign in again.',
        }
      }
    
      if (status === 403) {
        return {
          type: 'FORBIDDEN',
          message: 'You do not have permission.',
        }
      }
    
      if (status === 502 || status === 504) {
        return {
          type: 'GATEWAY_ERROR',
          message: 'The gateway is temporarily unavailable.',
        }
      }
    
      if (status === 503) {
        return {
          type: 'SERVICE_UNAVAILABLE',
          message: 'The service is temporarily unavailable.',
        }
      }
    
      if (status >= 500) {
        return {
          type: 'SERVER_ERROR',
          message: 'Something went wrong on the server.',
        }
      }
    
      return {
        type: 'REQUEST_ERROR',
        message: error.message || 'Unable to complete the request.',
      }
    }
    

    This is an application-level error classifier, not a service worker fallback.

    The service worker cannot infer the meaning of every failed API request. Your frontend and backend should cooperate to provide appropriate error handling.

    17. Push Notifications in a PWA

    Push notifications can help a PWA communicate with users even when the application is not currently open.

    Common use cases include:

    • New messages.
    • Job application updates.
    • Important account notifications.
    • Order status updates.
    • Scheduled reminders.

    Push notifications generally involve three components:

    1. The browser's Push API.
    2. A service worker that receives push events and displays notifications.
    3. A backend that sends push messages through a push service.

    The application needs user permission before displaying notifications.

    A basic permission request looks like this:

    export async function requestNotificationPermission() {
      if (!('Notification' in window)) {
        return 'unsupported'
      }
    
      const permission = await Notification.requestPermission()
    
      return permission
    }
    

    Request permission in response to a meaningful user action, rather than immediately when the application loads.

    A production push implementation also needs:

    • A VAPID key pair.
    • Push subscription management.
    • Backend storage for subscriptions.
    • Subscription expiration handling.
    • Notification payload validation.
    • Notification click handling.
    • Unsubscribe support.

    Do not confuse push notifications with background synchronization. They solve different problems.

    18. Security Considerations for Offline Applications

    Offline storage introduces additional security responsibilities.

    A user may share a device, clear application data, or leave a session active.

    Consider the following practices:

    Avoid Caching Sensitive Responses

    Do not place private account information, authentication responses, or sensitive personal data into shared runtime caches without a carefully designed isolation and invalidation strategy.

    Be Careful with Logout

    When a user logs out:

    • Clear application-specific private caches.
    • Remove or isolate user-specific IndexedDB data.
    • Discard queued operations that should no longer be submitted.
    • Revoke or invalidate the server session as appropriate.

    If multiple accounts can use the same browser profile, separate user data carefully.

    Protect Offline Queues

    A pending queue may contain sensitive information.

    Use a deliberate data-retention policy and avoid storing unnecessary personal data.

    Validate Everything on the Backend

    Offline clients are not trusted sources.

    A user can modify IndexedDB records, alter requests, or replay operations manually.

    Every queued operation must still pass backend authentication, authorization, validation, and business-rule checks.

    Use HTTPS

    Service workers and many other PWA capabilities require a secure context.

    Deploy production PWAs over HTTPS.

    19. Testing an Offline-First PWA

    Testing only while connected to the internet is not enough.

    You should test the application under different network conditions and service worker states.

    Browser DevTools

    Chrome DevTools provides useful tools for inspecting PWA behavior.

    Use:

    • Application → Service Workers.
    • Application → Cache Storage.
    • Application → IndexedDB.
    • Network → Offline.
    • Network throttling.
    • Application → Manifest.

    Essential Test Cases

    TestExpected result
    First visit with internetApplication loads and service worker installs
    Reload with internetApplication loads normally
    Reload offlineCached application shell loads
    Open a cached image offlineImage is displayed
    Open an uncached resource offlineGraceful fallback
    Request a cached public API endpoint offlineCached response is returned
    Request an uncached API endpoint offlineClear offline error
    Perform an eligible operation offlineOperation is saved locally
    Restore connectivityPending operations are synchronized
    Server returns 401Authentication handling is triggered
    Server returns 500Server error is displayed
    Deploy a new frontend versionUpdate prompt appears
    Clear browser storageApplication handles missing local data gracefully

    Also test on real mobile devices.

    Desktop browser simulation is useful, but it cannot fully reproduce mobile browser lifecycle behavior, storage pressure, battery restrictions, or background execution limitations.

    20. Common PWA Implementation Mistakes

    Mistake 1: Caching Every API Request

    Caching every API response can expose private data, serve stale account information, and create unexpected behavior.

    Better approach: Cache only explicitly selected endpoints with known data freshness and privacy requirements.

    Mistake 2: Treating navigator.onLine as Proof of Internet Access

    A connected device does not necessarily have access to your backend.

    Better approach: Treat browser connectivity as a signal and handle actual request failures separately.

    Mistake 3: Using Cache Storage as a Database

    Cache Storage is designed around HTTP requests and responses.

    Better approach: Use IndexedDB for structured application records and pending operations.

    Mistake 4: Automatically Retrying Every Failed POST Request

    A failed response does not mean the server did not process the operation.

    Better approach: Use an explicit queue, idempotency keys, and server-side duplicate protection.

    Mistake 5: Assuming Background Sync Works Everywhere

    Browser support and execution policies vary.

    Better approach: Provide foreground synchronization as a reliable fallback.

    Mistake 6: Updating the Service Worker Without Considering Active Users

    An immediate update may interrupt active work or leave an application in an inconsistent state.

    Better approach: Use a controlled update flow and give users an opportunity to refresh.

    Mistake 7: Testing Only the Production Build While Online

    This misses lifecycle problems, cache failures, offline navigation issues, and update behavior.

    Better approach: Test the built application under offline and degraded network conditions.

    21. Production Readiness Checklist

    Before deploying an offline-first PWA, verify the following:

    Application and manifest

    • Web app manifest is configured.
    • Application icons are available.
    • HTTPS is enabled.
    • Application scope and start URL are correct.

    Service worker

    • Service worker is registered correctly.
    • Lifecycle behavior is understood.
    • Required application assets are precached.
    • Cache names and expiration policies are defined.
    • Old application caches are cleaned up safely.

    API and caching

    • Only appropriate API endpoints are cached.
    • Private and sensitive responses are excluded.
    • API cache expiration is configured.
    • Network failures and HTTP errors are handled separately.

    Offline data

    • IndexedDB schema is defined.
    • Pending operations are stored durably.
    • Retry attempts are limited.
    • Idempotency is implemented on the backend.
    • Conflicts and permanent failures are handled.
    • Local data has a retention and cleanup policy.

    Updates and notifications

    • Service worker updates are handled.
    • Users are not unexpectedly interrupted.
    • Push notifications are permission-based.
    • Notification subscriptions can be managed.

    Testing and deployment

    • Offline navigation is tested.
    • API failure scenarios are tested.
    • Storage-cleared scenarios are tested.
    • Mobile devices are tested.
    • Production build is tested.
    • CDN and server cache headers are configured correctly.

    Conclusion

    Building an offline-first PWA is not simply about adding a service worker and caching a few JavaScript files.

    It requires a coordinated architecture where each technology has a clear responsibility.

    • React manages the user interface and application state.
    • Vite builds and optimizes the frontend.
    • vite-plugin-pwa integrates PWA functionality into the build process.
    • Workbox simplifies service worker caching.
    • Cache Storage keeps reusable HTTP responses.
    • IndexedDB stores structured local data and pending operations.
    • The backend remains the authoritative source of truth.

    The most important principle is to design offline behavior around the actual needs of your application. Static assets, public API data, private account information, and user-generated operations all require different strategies.

    When these pieces work together, a PWA can provide a much more resilient experience—even when the user's connection is unreliable.

    Official References

    1. MDN — Progressive Web Apps
    2. MDN — Service Worker API
    3. MDN — Caching in PWAs
    4. MDN — Background Synchronization API
    5. Vite Plugin PWA Documentation
    6. Vite Plugin PWA — React Integration
    7. Workbox Documentation
    8. MDN — IndexedDB API

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal