Msw: Cannot set serviceWorker.URL to subdirectory because it limits what requests can be intercepted.

Created on 22 Aug 2020  路  2Comments  路  Source: mswjs/msw

Describe the bug

I receive this error:

[MSW] Failed to register a Service Worker:
mFailed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/static/mockServiceWorker.js'): The path of the provided scope ('/') is not under the max scope allowed ('/static/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.

Environment

  • msw: 0.20.5
  • nodejs: 12.16.1
  • npm: 6.14.7

Please also provide your browser version
Microsoft Edge 84.0.522.52 (Official build) (64-bit)

To Reproduce

  1. Run this code
import { setupWorker, rest } from "msw";

// Define request handlers and response resolvers.
const worker = setupWorker(
  rest.get("/api/v1", (req, res, ctx) => {
    return res(
      ctx.delay(1500),
      ctx.status(202, "Mocked status"),
      ctx.json({
        message: "Mocked response JSON body",
      })
    );
  })
);

// Start the Service Worker.
worker.start({
  onUnhandledRequest: "warn",
  serviceWorker: {
    // Points to the custom location of the Service Worker file.
    url: "/static/mockServiceWorker.js",
    options: {
      scope: "/",
    },
  },
});

// Run a request.
fetch("/api/v1")
  .then((response) => {
    console.log(response);
  })
  .catch((err: XMLHttpRequest) => {
    console.log(err);
  });
  1. Open your browser -> open the console.

Expected behavior

I expect that we can have the mockServiceWorker.js file in any subfolder and then be able to intercept any URL. I was trying to figure out why MSW wasn't intercepting any of my calls to "/api/v1" when mockServiceWorker.js was here: /static/mockServiceWorker.js.

Screenshots

image

bug browser

All 2 comments

I'm submitting this and then closing it to help anyone else that doesn't have a good grasp of service workers like me. This behavior is expected. You can read about scope for service workers here: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Why_is_my_service_worker_failing_to_register. You can't put the mockServiceWorker.js anywhere - it must be in the same directory or in a parent directory of the URLs that you want to intercept.

Thank you for including this, @josephspurrier!

Was this page helpful?
0 / 5 - 0 ratings