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


3. Registering for Background Sync in a Service Worker

First, we need to register a sync event inside our service worker (service_worker.js):

self.addEventListener("sync", async (event) => {
  if (event.tag === "sync-form") {
    event.waitUntil(syncFormData());
  }
});

async function syncFormData() {
  const db = await openDatabase();
  const storedRequests = await db.getAll("requests");

  for (const req of storedRequests) {
    try {
      await fetch(req.url, {
        method: req.method,
        headers: req.headers,
        body: req.body
      });
      await db.delete("requests", req.id);
    } catch (error) {
      console.error("Sync failed:", error);
    }
  }
}

4. Storing Requests in IndexedDB

Since service workers do not have direct access to local storage, we use IndexedDB to temporarily store requests.

async function saveRequest(url, method, headers, body) {
  const db = await openDatabase();
  await db.put("requests", { url, method, headers, body, id: Date.now() });
}

Now, when a user is offline, their requests will be stored and automatically sent when the connection is available.