Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise mock service worker (msw) with reactjs project

I tried using msw for local dev and testing using official guide

but faced following issue:

[MSW] Failed to register a Service Worker for scope ('http://localhost:8080/') with script ('http://localhost:8080/mockServiceWorker.js'): Service Worker script does not exist at the given path.

Did you forget to run "npx msw init <PUBLIC_DIR>"?

Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init


  [1]: https://mswjs.io/docs/getting-started/integrate/browser

My folder structure:

enter image description here

like image 493
Sunil Kumar Singh Avatar asked Jan 26 '26 01:01

Sunil Kumar Singh


1 Answers

As the error message suggests, you haven't placed the Service Worker (mockServiceWorker.js) script in your public directory. Based on your screenshot, your public directory is most likely ./build.

Execute this command to place the worker script in your public directory:

$ npx msw init ./build

You should be able to access the worker script in your running application by this URL: http://localhost:8080/mockServiceWorker.js. That should return the contents of the mockServiceWorker.js file to be registered in your app.

like image 58
kettanaito Avatar answered Jan 28 '26 16:01

kettanaito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!