hanford / next-offline

make your Next.js application work offline using service workers via Google's workbox
https://github.com/hanford/next-offline
1.59k stars 111 forks source link

Failed when fetching service-worker.js even though it exists #225

Closed renodesper closed 3 years ago

renodesper commented 4 years ago

Issue and steps to reproduce

I have a production-ready site which uses Next and want to implement the service worker to cache the images that we get. Below are the configuration that I use:

next.config.js

const withOffline = require('next-offline');

module.exports = withOffline({
  generateInDevMode: true,
  scope: '/',
  workboxOpts: {
    swDest: 'static/service-worker.js',
    runtimeCaching: [
      {
        urlPattern: /\.(?:gif|ico|jpg|jpeg|png|svg|webp)(?:\?|$)/,
        handler: 'CacheFirst',
        options: {
          cacheName: 'image-cache',
          expiration: {
            maxEntries: 500,
            maxAgeSeconds: 60 * 60 * 24 * 7
          }
        }
      }
    ]
  },
  ...
});

_document.js

<link rel="manifest" href="/static/manifest.json" />

Koa routes

  route.get('/service-worker.js', async ctx => {
    ctx.set('Content-Type', 'application/javascript');
    const cwd = __dirname.replace('/server/Http/routes', '');
    const pathname = await join(cwd, 'client/.next/static', 'service-worker.js');
    ctx.body = await nexApp.serveStatic(ctx.req, ctx.res, pathname);
    ctx.respond = false;
  });

So, the manifest.json can be seen on the application tab on developer tools but it shows me No matching service worker detected. On the console, I see this error:

SW registration failed:  TypeError: Failed to register a ServiceWorker for scope ('https://placeholder-domain.com/') with script ('https://placeholder-domain.com/service-worker.js'): A bad HTTP response code (404) was received when fetching the script.

When I try to access the above URL (https://placeholder-domain.com/service-worker.js), it actually shows me the service worker source code, so I guess it actually exists but something (I don't know what it is) failed to fetch it.

Versions

Browser

Can anyone guide me to fix it? I've been trying to register the service worker manually but it still shows me the same error.