register service worker with nextjs application register service worker with nextjs application express express

register service worker with nextjs application


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.


Service worker registration in Nextjs project

Put the service worker file in the public directory.

enter image description here

Inside your _app.js write below code :

componentDidMount(){    if('serviceWorker' in navigator){            navigator.serviceWorker.register("/firebase-messaging-sw.js");        }}