Service Worker in ReactJS
- What is the React Service Worker
- Functions of Service Workers
- How to Activate React Service Workers
- Service Worker Configuration
- Conclusion
When our phones are offline, and we can still receive messages on our apps, this is the work of a service worker.
A perfect example is the bible mobile app; once the time allotted is up, the user will get a daily memory verse from the app called push notification
. The Instagram app does the same, we are offline, but we still get notifications from the app.
Happily, React has injected this feature into their framework, and this article will take us through all we need to know about the service worker.
What is the React Service Worker
Service workers are specialized JavaScript assets that enhance existing websites by acting as a link between web browsers and web servers.
Their functions improve the reliability of a website by providing offline access to the website and boosting the web page’s overall performance; this is because some workings on the web page are subjected to the background, making the web page work with vital elements.
When offline and the user can still scroll through the website, that is the handwork of service workers.
Service workers can only run on HTTPS unless it is run in localhost, and also, they are tied to a particular web page; they are constantly reusable as users switch from page to page. One should be mindful of the state of the service worker because once it shuts down, it stops retaining information.
Functions of Service Workers
- Service workers can cache key aspects of a website; this makes it lighter on its feet (it loads faster), resulting in improved website performance.
- They enable notification and push APIs, features that are not usually available with traditional web technologies.
- With the availability of service workers, even when users lose internet functionality, they can still use the application normally. This is because the service workers have helped cached key parts of the website.
- Actions carried out when the app is offline can be synced in the background when the internet is fully restored.
How to Activate React Service Workers
A service worker is generated by default when we use the create-react-app
to create a new React project. We will find the serviceWorker.js
file in the src
folder of the project.
But the service worker is not functional out of the box; we will have to configure it.
We need to register the service worker; we will navigate to the src/index.js
file and look for this line serviceWorker.unregister();
and change it to serviceWorker.register();
.
Registering the service worker also enables it to become functional, and once the production version of the React app is made, the service worker is enabled alongside it.
Service Worker Configuration
When we create React app, the service-worker.js
, by default, caches contents directly associated with the web page; an example is a video embedded in the webpage. We will have to create a new file, custom-service-worker.js
, and then edit the register()
to load the new file we created.
In the serviceWorker.js
file, we will look for the load()
event listener around line 34 and add our custom file to it, like below.
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/custom-service-
worker.js`;
...
}
Once that is done, we will update the package.json
file next.
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
We will now need to install Google’s Workbox plugin; we use npm install --save-dev workbox-build
. The workbox plugin is useful for easily integrating features like background sync into the service worker.
Next, we will create a config file to instruct the Create React App (CRA) to insert the newly created custom service worker, like below.
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
module.exports = function override(config, env) {
config.plugins = config.plugins.map((plugin) => {
if (plugin.constructor.name === 'GenerateSW') {
return new WorkboxWebpackPlugin.InjectManifest({
swSrc: './src/custom-service-worker.js',
swDest: 'service-worker.js'
});
}
return plugin;
});
return config;
};
Lastly, we will create the custom worker to cache a particular directory, as shown below.
workbox.routing.registerRoute(
new RegExp('/path/to/cache/directory/'), workbox.strategies.NetworkFirst());
workbox.precaching.precacheAndRoute(self.__precacheManifest || [])
Once we are done with this part, we can build the application.
Conclusion
The features that service workers offer are ideal for web applications to run smoothly, and with time, they will be used to create some new and exciting features that will make web applications perform even better than they are now.
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn