---
title: "How can a service worker be used to implement background sync or push notifications?"  
description: "How can a service worker be used to implement background sync or push notifications?"  
author: "ICSM Computer"  
published: 2025-08-17  
updated: 2025-08-19  
canonical: https://www.mindstick.com/interview/34354/how-can-a-service-worker-be-used-to-implement-background-sync-or-push-notifications  
category: "services"  
tags: ["javascript", "service"]  
reading_time: 4 minutes  

---

# How can a service worker be used to implement background sync or push notifications?

## 1. Background Sync with [Service Worker](https://www.mindstick.com/interview/34348/what-is-a-service-worker-and-how-does-it-differ-from-a-traditional-javascript-script)

Background sync lets your app retry failed network requests when the user has a stable connection again — even if the app is closed.

**Use case:** Offline-first apps (e.g., Twitter, Gmail, Todo apps) where you create content offline and it syncs later.

### Steps:

- **Register the sync in your page script**

```javascript
navigator.serviceWorker.ready.then(event => {
    return event.sync.register('sync-posts'); // Tag your sync event
});
```

- **Listen for the sync event in the** [**Service Worker**](https://www.mindstick.com/interview/34349/what-are-the-three-main-phases-in-a-service-worker-s-lifecycle)

```javascript
self.addEventListener('sync', event => {
    if (event.tag === 'sync-posts') {
        event.waitUntil(syncPendingPosts());
    }
});

async function syncPendingPosts() {
    const posts = await getPendingPostsFromIndexedDB();
    for (const post of posts) {
        try {
            await fetch('/api/posts', {
                method: 'POST',
                body: JSON.stringify(post),
                headers: { 'Content-Type': 'application/json' }
            });
            await markPostAsSynced(post.id);
        } catch (err) {
            console.error('Sync failed, will retry later:', err);
            throw err; // ensures retry on next connection
        }
    }
}
```

## 2. Push Notifications with Service Worker

Push notifications allow your server to send messages to users using the **Push API +** [**Service Workers**](https://www.mindstick.com/interview/34350/how-do-you-register-a-service-worker-in-a-web-application), even if the site isn’t open.

**Use case:** Messaging apps, news apps, reminders or marketing notifications.

### Steps:

- **Subscribe to push on the client**

```javascript
navigator.serviceWorker.ready.then(async event => {
    const subscription = await event.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('<Your-VAPID-Public-Key>')
    });

    // Send subscription details to your server
    await fetch('/save-subscription', {
        method: 'POST',
        body: JSON.stringify(subscription),
        headers: { 'Content-Type': 'application/json' }
    });
});
```

- **Handle push events in the Service Worker**

```javascript
self.addEventListener('push', event => {
    let data = {};
    if (event.data) {
        data = event.data.json();
    }
    const options = {
        body: data.body,
        icon: '/icons/icon-192x192.png',
        badge: '/icons/badge-72x72.png',
        actions: [
            { action: 'open', title: 'Open App' },
            { action: 'dismiss', title: 'Dismiss' }
        ]
    };

    event.waitUntil(
        self.registration.showNotification(data.title, options)
    );
});
```

- **Handle notification clicks**

```javascript
self.addEventListener('notificationclick', event => {
    event.notification.close();

    if (event.action === 'open') {
        event.waitUntil(clients.openWindow('/dashboard'));
    }
});
```

## Key Difference

- **Background Sync** → triggered when connectivity is restored, ensures reliable delivery of user actions.
- [**Push Notifications**](https://www.mindstick.com/blog/94381/how-web-push-notifications-help-in-e-commerce-business) → This server-triggered feature lets you re-engage users even if the app is closed.

## Answers

### Answer by ICSM Computer

## 1. Background Sync with [Service Worker](https://www.mindstick.com/interview/34348/what-is-a-service-worker-and-how-does-it-differ-from-a-traditional-javascript-script)

Background sync lets your app retry failed network requests when the user has a stable connection again — even if the app is closed.

**Use case:** Offline-first apps (e.g., Twitter, Gmail, Todo apps) where you create content offline and it syncs later.

### Steps:

- **Register the sync in your page script**

```javascript
navigator.serviceWorker.ready.then(event => {
    return event.sync.register('sync-posts'); // Tag your sync event
});
```

- **Listen for the sync event in the** [**Service Worker**](https://www.mindstick.com/interview/34349/what-are-the-three-main-phases-in-a-service-worker-s-lifecycle)

```javascript
self.addEventListener('sync', event => {
    if (event.tag === 'sync-posts') {
        event.waitUntil(syncPendingPosts());
    }
});

async function syncPendingPosts() {
    const posts = await getPendingPostsFromIndexedDB();
    for (const post of posts) {
        try {
            await fetch('/api/posts', {
                method: 'POST',
                body: JSON.stringify(post),
                headers: { 'Content-Type': 'application/json' }
            });
            await markPostAsSynced(post.id);
        } catch (err) {
            console.error('Sync failed, will retry later:', err);
            throw err; // ensures retry on next connection
        }
    }
}
```

## 2. Push Notifications with Service Worker

Push notifications allow your server to send messages to users using the **Push API +** [**Service Workers**](https://www.mindstick.com/interview/34350/how-do-you-register-a-service-worker-in-a-web-application), even if the site isn’t open.

**Use case:** Messaging apps, news apps, reminders or marketing notifications.

### Steps:

- **Subscribe to push on the client**

```javascript
navigator.serviceWorker.ready.then(async event => {
    const subscription = await event.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('<Your-VAPID-Public-Key>')
    });

    // Send subscription details to your server
    await fetch('/save-subscription', {
        method: 'POST',
        body: JSON.stringify(subscription),
        headers: { 'Content-Type': 'application/json' }
    });
});
```

- **Handle push events in the Service Worker**

```javascript
self.addEventListener('push', event => {
    let data = {};
    if (event.data) {
        data = event.data.json();
    }
    const options = {
        body: data.body,
        icon: '/icons/icon-192x192.png',
        badge: '/icons/badge-72x72.png',
        actions: [
            { action: 'open', title: 'Open App' },
            { action: 'dismiss', title: 'Dismiss' }
        ]
    };

    event.waitUntil(
        self.registration.showNotification(data.title, options)
    );
});
```

- **Handle notification clicks**

```javascript
self.addEventListener('notificationclick', event => {
    event.notification.close();

    if (event.action === 'open') {
        event.waitUntil(clients.openWindow('/dashboard'));
    }
});
```

## Key Difference

- **Background Sync** → triggered when connectivity is restored, ensures reliable delivery of user actions.
- [**Push Notifications**](https://www.mindstick.com/blog/94381/how-web-push-notifications-help-in-e-commerce-business) → This server-triggered feature lets you re-engage users even if the app is closed.


---

Original Source: https://www.mindstick.com/interview/34354/how-can-a-service-worker-be-used-to-implement-background-sync-or-push-notifications

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
