react-mirage-msw
v0.0.1
Published
A utility package for using [Mirage JS](https://miragejs.com/) with [MSW](https://mswjs.io/) in React/Vite apps, providing a consistent setup for both browser and test environments.
Readme
React Mirage MSW
A utility package for using Mirage JS with MSW in React/Vite apps, providing a consistent setup for both browser and test environments.
Installation
pnpm i react-mirage-msw
Browser integration for MSW
MSW intercepts requests in the browser via a service worker. For this to work, a mockServiceWorker.js file must be served from the root of your app — i.e. it must be accessible at /mockServiceWorker.js.
In a Vite project, place the file in the public/ directory. You can generate it by running:
npx msw init public/This only needs to be done once. The file should be committed to source control. It does not need to be modified.
For more details see the MSW browser integration docs.
Defining Mirage config
The config file is a plain exported object that is shared between the browser bootstrap and your tests. It uses createConfig to asynchronously load Mirage's models, fixtures, factories, serializers and identity managers via Vite's import.meta.glob.
Use the routes() function for standard JSON responses handled by Mirage's serializer layer. For responses that Mirage cannot serialize correctly — such as binary data or streaming responses — use rawRoutes. These are MSW handlers that bypass Mirage entirely and return HttpResponse objects directly.
// src/mirage/config.js
import { baseURL } from '../api/client';
import { createConfig } from 'react-mirage-msw/create-config';
import { http, HttpResponse } from 'msw';
const config = await createConfig({
factories: import.meta.glob('./factories/*'),
fixtures: import.meta.glob('./fixtures/*'),
models: import.meta.glob('./models/*'),
serializers: import.meta.glob('./serializers/*'),
identityManagers: import.meta.glob('./identity-managers/*'),
});
export default {
...config,
logging: true,
timing: 0,
routes() {
this.urlPrefix = baseURL;
this.namespace = '';
this.get('/users', (schema) => {
return schema.users.all();
});
this.passthrough();
},
rawRoutes: [
http.get(`${baseURL}/stream`, () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('hello'));
controller.enqueue(new TextEncoder().encode('world'));
controller.close();
},
});
return new HttpResponse(stream, {
headers: { 'content-type': 'text/plain' },
});
}),
http.get(`${baseURL}/image-buffer`, () => {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><text y="28" font-size="28">😎</text></svg>';
const buffer = new TextEncoder().encode(svg).buffer;
return HttpResponse.arrayBuffer(buffer, {
headers: { 'content-type': 'image/svg+xml' },
});
}),
],
};Starting Mirage in the browser
Create a start-mirage.js bootstrap file that wires the shared config together with the MSW browser interceptor. This is called before React renders so that all requests are intercepted from the very first render.
// src/mirage/start-mirage.js
import MSWInterceptor from 'mirage-msw';
import config from './config.js';
import startServer from 'react-mirage-msw/start-server';
export default async function () {
const server = await startServer({
...config,
interceptor: new MSWInterceptor(),
});
return server;
}Bootstrapping in main.jsx
Call startMirage() and wait for it to resolve before mounting the React app. This ensures the MSW service worker is registered and all route handlers are active before any component tries to make a request.
// main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.jsx';
import startMirage from './mirage/start-mirage.js';
startMirage().then(() => {
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
});Using Mirage in tests
setupMirage is a Vitest helper that wires up a Mirage server with a Node-compatible MSW interceptor around each test. It handles beforeEach / afterEach internally — just call it at the top of your describe block and pass in your shared config.
import setupMirage from 'react-mirage-msw/test-support/setup-mirage';
import mirageConfig from '../mirage/config';
describe('UsersFetcher', () => {
setupMirage(mirageConfig);
...
});Demo app
To run a demo app with the configuration outlined above:
git clone [email protected]:andrew-paterson/react-mirage-msw.git
pnpm install
cd demo app
To run the app in dev mode:
pnpm run dev
To run the tests with Vitest:
pnpm run test
