Fixing the Service Worker issue when you rewrite a React app using the Next.js framework
Do you have a React app already deployed on a web server and realized that your app is not ranking at all in any web search engine? Are you thinking about rewriting your app to improve its SEO (search engine optimization)? If you are, you might be thinking about using the Next.js framework, but before you dive into it, we’d like to walk you through the Service Worker issue, which can be a pain in the neck!
Let’s start with the basics
When we create a React app, a Service Worker is invoked by default, so even if we unregister the Service Worker before deploying the React app using Next.js, we must make sure that every browser removed the Service Worker. Otherwise, we will have to fix an unexpected issue because Next.js does not use Service Workers — remember that Next.js runs on the server side — and it also stores static files in a different location so, if we don’t update it, the browser will continue using it in order to access to wrong static file paths — e.g. images. The only way to avoid this issue is unregistering the Service Worker before deploying the React app. However, this makes no sense because if we create a React app, we will want to have a good performance and, in order to achieve that, we need a Service Worker.
To solve this, the idea is to unregister the Service Worker of our React app so the browser can remove it. To do that, we have to create a Service Worker on the root of the Next.js project and add an EventListener — on any load page — to remove this file from the browser. Once we do this, we can be sure that next time a browser makes a request, it will be updated. Another important thing to note is that browsers need to close all the Service Worker’s instances associated with our app to apply the changes.
A final note
We hope this workaround were useful and saves time for other React developers. But before you decide to rewrite a React app using Next.js, keep in mind that it may not be the best option, especially if you are using Redux/Sagas to manage the app stored. Next.js was optimized for Apollo — one of the best GraphQL clients — to create HTTP requests and manage the app stored. It also has one more restriction: the environment variables can not be accessed in the client side with all that this implies.