I'm a newbie to nextjs
and working on a small application where I want to provide an offline support but I'm not been able to register service worker.
throwing Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script
this error.
following is my code...
and my service-worker.js is at the root of nextjs
application.
componentDidMount = () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register('../service-worker.js')
.catch(err => console.log('err', err))
}
}
do I need to configure server i.e. (server.js) in some way to serve that file..?
const express = require('express');
const next = require('next');
var routes = require('./router');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.use('/edit', routes);
server.get('*', (req, res) => handle(req, res));
server.listen(3000, (err) => {
if (err) throw err;
console.log('http://localhost:3000');
});
})
.catch((ex) => {
console.log(ex.stack);
process.exit(1);
})
if yes then how should I do it..?
the directory structure is shown in following image link. directory structure
You need to serve your service-worker
file as a static file to achieve that.
See the reference here, app.serveStatic(req, res, filePath)
line 19.
You can take a look on the complete example here.
move service-worker.js
file in server
folder and add following line
server.use('/service-worker.js', express.static(__dirname + '/service-worker.js'));
in server.js
file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With