Registering a Service Worker gives 404 in webpack project

Viewed 398

I have a basic webpack starter project with just html, css and javascript. I am trying to register a service worker with the application but it is constantly giving 404 error in the console saying service worker not found.

A bad HTTP response code (404) was received when fetching the script.
index.js?15bb:21 Service Worker failed to install TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/sw.js'): A bad HTTP response code (404) was received when fetching the script.

enter image description here

Can anyone help me with the issue?

I have updated my git repo which is public. https://github.com/ankitbtanna/service-workers

1 Answers

Your src/sw.js is never ingested into the webpack asset pipeline, so the webpack development server doesn't know how to respond to requests for it.

If your src/sw.js is just a static file (like it is right now), then you should put it in the public/ directory, and your webpack configuration will automatically expose it to the development server.

The one wrinkle here is that you'd want to make sure that everything in public/ is served from your web root /, not from /public/, because you need the URL for your service worker to be /sw.js, not /public/sw.js.

You can change your CopyWebpackPlugin config to do this:

new CopyWebpackPlugin({
  patterns: [{
    from: Path.resolve(__dirname, '../public'),
    to: '.', // changed from 'public'
  }],
}),
Related