DEV Community

Daksh Kulshrestha
Daksh Kulshrestha

Posted on

What is a service worker and why should you use it?

What are service workers?

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. They can do loads of tasks. The specific one we are gonna talk about is offline caching.

I am just a beginner to Service Workers, read them about in depth here.

How do they work?

A service worker usually mimics a caching server (from what I've understood so far). It downloads the assets used to run a webpage and then it automatically sets up a server with the static assets when you're offline. The offline version is automatically downloaded the first time you visit the app.

How do I know if they're enabled on a website?

In most cases, the service workers render a different component than the actual sites. For instance, Twitter mobile version has a service worker set up which shows you're offline, that's pretty cool right?!

How do I set it up in my website?

They are to be found in serviceworker object inside navigator function in VanillaJS. Here, I'll teach you how to set them up in ReactJS. Before setting them up make sure your app runs over an HTTPS connection. Service workers can be used to hijack connections and filter responses. Powerful stuff. While you would use these powers for good, a man-in-the-middle might not. To avoid this, you can only register for service workers on pages served over HTTPS, so we know the service worker the browser receives hasn't been tampered with during its journey through the network.

For setting them up in your React App built using CRA template, you need to open your src folder and make sure you don't touch the serviceWorker.js. When your service worker's integrity is made sure of, open up index.js and change the following line.

serviceworker.unregister()
Enter fullscreen mode Exit fullscreen mode

to

servieworker.register()
Enter fullscreen mode Exit fullscreen mode

Yes, it's THAT easy. I was shocked too. But if you're in the development server mode, offline caching won't work, since you're running the app locally.

After when your app is in production, you can just visit the app once and forget to turn on your network connection next time you visit it. If your app has some sort of CRUD functionality with any database, you can also set it up to take the instructions and do them once you're online.

This is one of the best practices of PWA. After a lighthouse report I got a PWA badge.

If you stuck till here, thanks! This is my first blog post ever! It feels really great to write. Might do this more often.

Top comments (0)