This is a simple Webpack plugin for Next.js to create Google Workbox based service workers.
I recently had to create a Next.js PWA with support for offline Google Analytics.
The app uses a public
folder (introduced in Next.js 9.1) so i thought it must be relatively easy
to find a Webpack plugin that creates a service worker there.
There is next-offline
but it
doesn't seem to support the public
folder yet (doesn't pick up files for precaching and doesn't
save the service worker there), the Workbox tools don't play well with the Next.js pipeline, and
i haven't found anything else. So i wrote my own plugin.
It is really simple and somewhat hacky, and may fail for your use case. It neither supports dynamic routes nor API routes at this point. It may or may not work when deployed on Now. It's not very well tested. But maybe it's a good starting point for your own solution.
The nice thing about this is that you won't need a custom server because the service worker
is served via the public
folder (which is mapped to your app's root). This wasn't possible
prior to Next.js 9.1.
Add the plugin to your next.config.js
:
const NextWorkboxPlugin = require('./NextWorkboxPlugin');
module.exports = {
webpack: (config, options) => {
config.plugins.push(new NextWorkboxPlugin(options));
return config;
},
);
Now when you build your project, Webpack creates the service worker in ./public/sw.js
.
Register the service worker in your project's _app.js
:
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
}