Table of Contents
How to use MSW with SvelteKit
Mock API requests in development with Mock Service Worker
What is MSW?
Mock Service Worker (MSW) is an API mocking library that uses Service Worker to intercept network requests.
MSW intercepts fetch calls in the browser and returns mocked responses defined in your handlers. This lets you develop against APIs that do not exist yet, or work offline without changing application code.
Setup
Install dependencies
pnpm add msw -D
Generate the service worker
MSW needs a service worker file served from your app's static directory. Generate it with:
pnpx msw init static --save
This creates static/mockServiceWorker.js and adds an msw field to package.json:
package.json
{
"msw": {
"workerDirectory": [
"static"
]
}
}
Do not edit mockServiceWorker.js manually. Re-run msw init when you upgrade MSW.
If you use pnpm, allow MSW to run its postinstall script:
pnpm-workspace.yaml
allowBuilds:
msw: true
Define request handlers
Handlers describe which requests to intercept and what to return.
src/lib/mocks/handlers.ts
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.example.com/user', () => {
return HttpResponse.json({
id: 'abc-123',
firstName: 'Rick',
lastName: 'Astley'
});
})
];
Create the browser worker
src/lib/mocks/browser.ts
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers.js';
export const worker = setupWorker(...handlers);
Start the worker in development
Start MSW only in development so mocked responses never ship to production.
src/routes/+layout.svelte
<script>
import { onMount } from 'svelte';
import { dev } from '$app/environment';
let { children } = $props();
onMount(() => {
if (!dev) return;
let worker: SetupWorker;
(async () => {
const { worker: w } = await import('$lib/mocks/browser');
worker = w;
worker.start();
})();
return () => worker?.stop();
});
</script>
{@render children()}
Usage
Once the worker is running, fetch calls that match your handlers are intercepted automatically.
src/routes/+page.svelte
<script>
function fetchUser() {
fetch('https://api.example.com/user')
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}
</script>
<button onclick={fetchUser}>Fetch User</button>
Clicking the button logs the mocked user object instead of hitting the real API.
Notes
- MSW only runs in the browser. Server-side
fetchcalls inloadfunctions or+server.tsfiles are not intercepted by the browser worker. - For server-side mocking, set up a Node server integration separately.
- After changing handlers, a page refresh is enough; you do not need to restart the dev server.