I've configured Vite to work with MSW to intercept my requests, so far no issues with this. The mockServiceWorker.js file in inside public folder. However, i needed to add a property in my vite.config.ts named base:
vite.config.ts
export default defineConfig({
base: '/kiosk',
...other configs...
With this, I also added the necessary property on package.json:
package.json
"homepage": "/kiosk",
...other configs...
This has broken the MSW functionality, and it doesn't intercept any request.
This is what i currently have in my MSW initializer.
import { StartOptions } from 'msw/browser';
export const enableMocking = async () => {
if (!import.meta.env.DEV) return;
const { worker } = await import('./browser');
return worker.start(workerStartOptions);
};
const workerStartOptions: StartOptions = {
serviceWorker: {
url: '/kiosk/mockServiceWorker.js'
},
};
And is not intercepting any request, while getting this message on the console: `[MSW] Cannot intercept requests on this page because it's outside of the worker's scope ("http://localhost:3000/kiosk/"). If you wish to mock API requests on this page, you must resolve this scope issue.
- (Recommended) Register the worker at the root level ("/") of your application.
- Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.`
Any solutions to get MSW to work with base paths? Thanks in advance!
I ran into this issue as well with Vite and MSW, and ran this:
Seemed to fix it for me.
Although I'm not totally happy with the mockServiceWorker.js file being in my root project directory.
There is a possibility of adding the 'Service-Worker-Allowed' header to the handlers might work.
https://mswjs.io/docs/recipes/custom-worker-script-location/#option-2-service-worker-allowed-response-header