How to integrate Service Workers into Next.js application

Are you interested in offline web applications and want to know how to achieve performance levels close to the native program? Then there is nothing better than service workers.

Are you interested in offline web applications and want to know how to achieve performance levels close to the native program? Then there's nothing better than a service worker .

How to integrate Service Workers into Next.js application Picture 1How to integrate Service Workers into Next.js application Picture 1

Service workers are scripts that run in the background to provide powerful caching capabilities and other features for modern web applications.

These features provide a seamless and user-friendly native app experience for web browsers.

Service workers are a fundamental component in creating Progressive Web Apps (PWAs).

What is a service worker?

A service worker is a type of JavaScript web worker that runs in the background, separate from the main JavaScript thread so it is not blocked. This means it does not cause delays or interruptions in the interface or user interaction with it.

How to integrate Service Workers into Next.js application Picture 2How to integrate Service Workers into Next.js application Picture 2

 Service workers act as proxy servers - located between the web application and the network. They can intercept queries and responses, cache resources, and provide offline support. This helps ensure the web application is more seamless and user-friendly, even when they are not online.

Main applications for service workers

There are several applications for service workers, including:

  1. PWA : Service worker powers Progressive Web App. They implement custom network queries, push notifications, offline support, and fast loading.
  2. Caching : Service workers can store application assets - images, JavaScript code, CSS files - in the browser cache. This allows the browser to retrieve them from its cache, instead of fetching them at a remote server on the network. As a result, content loads faster. This is especially useful for users with slow or unreliable Internet connections.
  3. Background sync : Service workers can synchronize data and run other background tasks, even when the user is not actively interacting with the application or when the application is not open in the browser.

Integrate service worker in Next.js application

Before diving into the code, you need to understand how service workers work. Using a service worker has two main phases: registration and activation .

During the first phase, the browser registers the service worker. Here is an example:

const registerServiceWorker = async () => { if ("serviceWorker" in navigator) { registration = await navigator.serviceWorker.register("/sw.js"); } }; registerServiceWorker();

This code will first check to see if the browser supports service workers, which all modern web browsers do. If supported, it proceeds to register a service worker located at the specified file path.

During the activation phase, you need to install and activate a service worker by listening to the install and activate events via a JavaScript event listener. Here's how you can achieve this:

registration.addEventListener("install", () => { console.log("Service worker installed"); }); registration.addEventListener("activate", () => { console.log("Service worker activated"); });

You can include this code right after the registration process. It will run immediately after the service worker registration process is successful.

Create Next.js project

To get started, run the command below to create a local Next.js project:

npx create-next-app next-project

Adding a service worker to a Next.js application involves the following steps:

  1. Register a service worker in the globally scoped environment.
  2. Create a JavaScript service worker file in the public directory.

Add service workers

First, register a service worker. Update the src/pages/_app.js file as follows: Include code in the file to ensure the service worker registers when the application loads and has access to all of the application's assets.

import { useEffect } from 'react'; export default function App({ Component, pageProps }) { useEffect(() => { if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/service-worker.js', { scope: '/' }) .then((registration) => { console.log( 'Service worker registered successfully. Scope:', registration.scope ); }) .catch((error) => { console.error('Service worker registration failed:', error); }); } }, []); return ; } 

The useEffect hook fires when the component is bound. Like the previous example, the code first checks to see if the user's browser supports service workers.

If so, it registers the service worker script as located at the specific file path, and specifies its scope as '/'. This means the service worker has control over all resources in the application. You can provide a more detailed scope if you wish, for example ' /products '.

If registration is successful, it logs a success message, along with its scope. If an error occurs during registration, this code will catch the error and record an error message.

Install and enable service workers

Add the following code to the new file, public/service-worker.js .

const installEvent = () => { self.addEventListener('install', () => { console.log('service worker installed!!!!'); }); }; installEvent(); const activateEvent = () => { self.addEventListener('activate', () => { console.log('service worker activated!!!'); }); }; activateEvent();

To check whether the service worker has been successfully registered, installed and activated, start the programming server & open the application in the browser.

npm run dev

Open Chrome's Developer Tools window, navigate to the Application tab . In the Service Workers section , you will see registered Service Workers .

How to integrate Service Workers into Next.js application Picture 3How to integrate Service Workers into Next.js application Picture 3

With the service worker successfully registered, installed & activated, you can implement several functions such as caching, background sync or sending push notifications.

Store resources with service workers

Storing app assets on user devices can improve performance by allowing faster access, especially in situations with unreliable Internet connections.

To cache your application's resources, include the following code in the service-worker.js file .

const cacheName = 'test-cache'; self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cachedResponse) => { return cachedResponse || fetch(event.request).then((response) => { return caches.open(cacheName).then((cache) => { cache.put(event.request, response.clone()); return response; }); }); }) ); });

When the user first visits the home page, this code checks to see if there is a response stored for this query in the cache. If a cached response exists, the service returns it to the client.

If no stored response exists, the service worker fetches the source from a server on the network. It responds to the client and stores it for future queries.

To view stored resources, open the Application tab in programming tools. In the Cache Storage section , you will see a list of stored resources. You can also check the Offline option in Service Worker and reload the page for an offline experience.

How to integrate Service Workers into Next.js application Picture 4How to integrate Service Workers into Next.js application Picture 4

Now after reaching the home page, the browser will cache the source instead of trying to make a query over the internet to fetch the data.

Overall, service worker is a powerful tool to enhance the performance of applications created with Next.JS. Hopefully this article will help you know how to use service workers effectively in the Next.js app.

4.5 ★ | 2 Vote