Custom worker
next-pwa
allows you to inject some custom code into the generated service worker. By default, this code should be located at worker/index.{js,ts}
.
The plugin will check if the file exists and bundle the file to dest/worker-*.js
if it does.
Do not use this feature to write critical worker code that your application depends on to function. Again, the service worker should function as an enhancement, not something critical to your application.
You can change the directory in which next-pwa
looks for a custom worker implementation and change the directory in which next-pwa
outputs the bundled
worker:
const withPWA = require("@ducanh2912/next-pwa").default({
customWorkerSrc: "service-worker",
customWorkerDest: "somewhere-else", // defaults to `dest`
customWorkerPrefix: "not/a-worker",
// ...
});
module.exports = withPWA({
// Your Next.js config
});
In this example, next-pwa
will look for service-worker/index.{js,ts}
, bundle it if it is available, and then emit the result
to somewhere-else/not/a-worker-*.js
.
The difference between customWorkerDest
and customWorkerPrefix
is that the
former only changes the output directory of the custom worker, whereas the
latter also changes the URL the service worker uses to look for the custom
worker. In the example above, the service worker will try to look for
/not/a-worker-*.js
, and it is your responsibility to serve it if you change
customWorkerDest
to something different from public
.