Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Build a progressive web app with offline caching and background sync using Service…

  1. User

    Build a progressive web app with offline caching and background sync using Service Workers.

  2. Gemini Assistant

    Formulating the PWA Guide

    I'm now focusing on defining the guide's scope and the key features of the PWA we'll be building. I've begun outlining the structure, breaking it into sections on offline caching, background sync, and user interface considerations. Thinking about what level of detail to include in each section, aiming for a balance between clarity and conciseness for experts like yourself.

    Mapping Out Implementation Steps

    I'm presently building out the detailed steps needed to showcase offline caching and background sync within the PWA tutorial. It involves frontend UI, a backend component, and clear explanations for Service Worker registration and its corresponding logic. Focusing on the manifest file, frontend code, and Service Worker implementation to create a well-structured guide.

    Developing the Tutorial's Core

    I'm now focusing on creating a "Post Sender" app as a concise example. I'm building a streamlined file structure with index.html, app.js, sw.js, manifest.json, and a basic server.js for testing. I'm working through the manifest, frontend elements, and the crucial sync logic within app.js and sw.js. The goal is to provide a clear, practical, and step-by-step example.

    Refining Background Sync

    I'm currently working to refine the background sync mechanism within the tutorial. After a click, it will go to IndexedDB, register a sync tag. The sw.js listens to sync events, processing data written to IDB. Thinking about the helper functions and how to streamline code to enhance clarity, favoring native IDB. I'm focusing on the manifest, front end, and the Service Worker implementation within a simplified Post Sender app for a hands-on experience.

    Streamlining Sync Operations

    I'm now diving into the finer points of the background sync, specifically, checking the tag name and making the IndexedDB interactions easier to digest. I'm focusing on crafting a very readable implementation, which will guide the reader through IndexedDB reads, server POSTs, and IDB deletions on success. In the spirit of clarity, I'm also looking into native IDB or a utility function to streamline the implementation. Plus, I will include a cache strategy using caches.match and fetch. Lastly, I will make a point to add a note regarding browser support for background sync.

    Improving Guide's Testability

    I'm now focusing on adding thorough, step-by-step "How to Test" instructions to the guide, focusing on background sync, to aid the reader. I'll provide clear steps for starting the server, going offline, sending messages, and then going online to observe the server console. I'm also ensuring the guide covers all relevant constraints like offline caching, background sync, and service workers to keep it complete. I'm building a concise and practical test procedure so that even the most technical user has no problem getting the example to run.

    Enhancing Code Readability

    I've decided to create a small, raw IndexedDB helper for the frontend to simplify the example. While idb-keyval is convenient, a self-contained tutorial should minimize dependencies, and the helper will do the job. I'm focusing on ensuring it's straightforward and easy to understand to assist in implementing IndexedDB reads. This will enhance the overall approachability of the guide.

    This is a comprehensive guide to building a Progressive Web App (PWA) that implements Offline Caching (using the Cache API) and Background Sync (using the Sync API and IndexedDB).

    Prerequisites

    1. Node.js installed (for a simple backend to test the sync).
    2. Chrome/Edge browser (Background Sync is primarily supported in Chromium browsers).

    Project Structure

    Create a folder named pwa-sync-demo and add these files:

    1. index.html (The UI)
    2. style.css (Styling)
    3. app.js (Frontend Logic)
    4. sw.js (Service Worker)
    5. manifest.json (PWA Configuration)
    6. server.js (Simple Backend)

    1. The Backend (server.js)

    We need a server to receive data. When the app is offline, data will queue up. When online, the Service Worker will hit this endpoint.

    const express = require('express');
    const app = express();
    const port = 3000;
    
    // Middleware to parse JSON and serve static files
    app.use(express.json());
    app.use(express.static('./'));
    
    app.post('/api/add-message', (req, res) => {
        console.log('>> SERVER RECEIVED DATA:', req.body);
        res.json({ status: 'success', received: req.body });
    });
    
    app.listen(port, () => console.log(`Server running at http://localhost:${port}`));
    

    Run npm init -y and npm install express in your terminal before starting this.


    2. The PWA Manifest (manifest.json)

    This file tells the browser that your website is an installable app.

    {
      "name": "Offline Sync PWA",
      "short_name": "SyncPWA",
      "start_url": "/index.html",
      "display": "standalone",
      "background_color": "#FFE9D2",
      "theme_color": "#FFE9D2",
      "icons": []
    }
    

    3. The Frontend UI (index.html and style.css)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>PWA Background Sync</title>
        <link rel="stylesheet" href="style.css">
        <link rel="manifest" href="manifest.json">
    </head>
    <body>
        <div class="container">
            <h1>Offline Sync Post</h1>
            <p>Status: <span id="network-status">Check Console</span></p>
            
            <input type="text" id="msg-input" placeholder="Type a message...">
            <button id="send-btn">Send Message</button>
            
            <div id="output"></div>
        </div>
        
        <!-- Utilizing a tiny IDB helper script would be better, 
             but we will write raw IDB logic in app.js for zero dependencies -->
        <script src="app.js"></script>
    </body>
    </html>
    

    style.css

    body { font-family: sans-serif; background-color: #f4f4f4; display: flex; justify-content: center; padding-top: 50px; }
    .container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 300px; }
    input { width: 100%; padding: 10px; margin-bottom: 10px; box-sizing: border-box; }
    button { width: 100%; padding: 10px; background: #007bff; color: white; border: none; cursor: pointer; }
    button:hover { background: #0056b3; }
    

    4. Frontend Logic (app.js)

    Here we register the Service Worker and handle user input. If the user sends a message, we save it to IndexedDB and register a Sync task.

    // 1. Register Service Worker
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('/sw.js')
                .then(reg => console.log('SW Registered!', reg))
                .catch(err => console.log('SW Failed', err));
        });
    }
    
    // 2. IndexedDB Helper (To replicate database logic easily)
    function openDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open('sync-db', 1);
            request.onupgradeneeded = e => {
                let db = e.target.result;
                if (!db.objectStoreNames.contains('outbox')) {
                    db.createObjectStore('outbox', { keyPath: 'id', autoIncrement: true });
                }
            };
            request.onsuccess = e => resolve(e.target.result);
            request.onerror = e => reject(e);
        });
    }
    
    function saveToODB(data) {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const transaction = db.transaction(['outbox'], 'readwrite');
                const store = transaction.objectStore('outbox');
                store.add(data);
                transaction.oncomplete = () => resolve();
                transaction.onerror = (e) => reject(e);
            });
        });
    }
    
    // 3. UI Logic
    const btn = document.getElementById('send-btn');
    const input = document.getElementById('msg-input');
    
    btn.addEventListener('click', () => {
        const msg = input.value;
        if (!msg) return;
    
        const payload = { 
            message: msg, 
            timestamp: Date.now() 
        };
    
        // Registration of Sync
        if ('serviceWorker' in navigator && 'SyncManager' in window) {
            navigator.serviceWorker.ready.then(sw => {
                // A. Save to IndexedDB
                saveToODB(payload).then(() => {
                    // B. Register a Sync Tag
                    return sw.sync.register('sync-new-posts');
                }).then(() => {
                    console.log('[App] Sync registered. If offline, will send later.');
                    alert('Message queued! It will send when online.');
                    input.value = '';
                }).catch(err => console.error(err));
            });
        } else {
            // Fallback for browsers without Background Sync
            console.log('Background sync not supported. Trying normal fetch...');
            fetch('/api/add-message', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
        }
    });
    

    5. The Service Worker (sw.js)

    This is the core. It handles:

    1. Install/Activate: Caching static files (Offline support).
    2. Fetch: Serving files from cache if offline.
    3. Sync: Waking up in the background to process IndexedDB data.
    const CACHE_NAME = 'static-v1';
    const ASSETS = [
        '/',
        '/index.html',
        '/style.css',
        '/app.js',
        '/manifest.json'
    ];
    
    // --- 1. INSTALL EVENT (Caching Assets) ---
    self.addEventListener('install', event => {
        console.log('[SW] Installing...');
        event.waitUntil(
            caches.open(CACHE_NAME).then(cache => {
                return cache.addAll(ASSETS);
            })
        );
    });
    
    // --- 2. ACTIVATE EVENT (Cleanup) ---
    self.addEventListener('activate', event => {
        console.log('[SW] Activating...');
        event.waitUntil(
            caches.keys().then(keys => {
                return Promise.all(keys.map(key => {
                    if (key !== CACHE_NAME) return caches.delete(key);
                }));
            })
        );
        return self.clients.claim();
    });
    
    // --- 3. FETCH EVENT (Offline Strategy: Cache First) ---
    self.addEventListener('fetch', event => {
        // Ignore API calls in the cache strategy (Network Only for API)
        if (event.request.url.includes('/api/')) {
            return; 
        }
    
        event.respondWith(
            caches.match(event.request).then(cachedResponse => {
                return cachedResponse || fetch(event.request);
            })
        );
    });
    
    // --- 4. BACKGROUND SYNC EVENT ---
    
    self.addEventListener('sync', event => {
        if (event.tag === 'sync-new-posts') {
            console.log('[SW] Sync event fired!');
            event.waitUntil(sendQueueToServer());
        }
    });
    
    // -- Helper to Access IndexedDB inside SW --
    function openDB() {
        return new Promise((resolve, reject) => {
            const req = indexedDB.open('sync-db', 1);
            req.onsuccess = e => resolve(e.target.result);
            req.onerror = e => reject(e);
        });
    }
    
    function sendQueueToServer() {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const tx = db.transaction(['outbox'], 'readwrite');
                const store = tx.objectStore('outbox');
                const allReq = store.getAll();
    
                allReq.onsuccess = async () => {
                    const posts = allReq.result;
                    for (const post of posts) {
                        try {
                            console.log('[SW] Sending post:', post);
                            
                            // Perform the actual Fetch
                            await fetch('/api/add-message', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(post)
                            });
    
                            // If successful, delete from IDB
                            const txDel = db.transaction(['outbox'], 'readwrite');
                            txDel.objectStore('outbox').delete(post.id);
                        } catch (err) {
                            console.error('[SW] Send failed, will retry:', err);
                            // If error throws here, promise rejects, 
                            // and Sync API automatically schedules a retry.
                            throw err; 
                        }
                    }
                    resolve();
                };
            });
        });
    }
    

    How to Run and Test

    1. Start the Server: Open your terminal in the folder and run:

      node server.js
      
    2. First Load (Online): Go to http://localhost:3000. Open Chrome DevTools (F12) -> Application Tab -> Service Workers. Ensure it is registered and running.

    3. Test Offline Caching:

      • In DevTools -> Network, change "No throttling" to "Offline".
      • Refresh the page. It should still load perfectly (served from static-v1 cache).
    4. Test Background Sync:

      • Step A: Keep the Network set to "Offline".
      • Step B: Type "Hello Offline World" in the input and click Send.
      • Step C: You will see an alert "Message queued!".
      • Step D: Look at the Console. You should see logs about saving to IndexedDB. The request did not go to the server yet.
      • Step E: Change Network back to "No throttling" (Online).
      • Step F: Watch the Terminal where node server.js is running. Within a few seconds (or immediately), you will see: >> SERVER RECEIVED DATA: { message: 'Hello Offline World', ... }

      Note: If the sync doesn't trigger immediately upon reconnecting, you can force it in Chrome DevTools -> Application -> Service Workers -> check "Update on reload" or click the "Sync" button next to the Sync tag.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.