Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

register service worker with nextjs application

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

like image 424
Nikhil Avatar asked Sep 18 '18 19:09

Nikhil


2 Answers

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.

like image 75
Darryl RN Avatar answered Sep 24 '22 03:09

Darryl RN


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.

like image 44
Nikhil Avatar answered Sep 24 '22 03:09

Nikhil