Skip to main content

APIs · Intermediate · 22 min

Mock an API during frontend development with Mock Service Worker

By Padding · Updated 18 Nov 2026
Node.js 26.13 · MSW 3.0.7 · Vite 8.3.8 · Vitest 5.1.1 · checked in the node:26 image

You will build a Vite page against a mocked API with Mock Service Worker 3, drive its loading, error and empty states on demand, reuse the same mocks in Vitest, and switch to the real API with one environment variable.

On this page

Front-end work often stalls on the back end. The endpoint is not finished, the staging server is down, or nobody can make it return an error on purpose. Mock Service Worker (MSW) removes that wait. You describe the API in small functions called request handlers, and MSW answers your app's real fetch calls with them. In the browser it does this from a service worker, so the Network tab shows the requests. In Node.js it hooks into the HTTP modules, so tests use the same handlers. Your application code never knows it is talking to a mock.

In this tutorial you build a small page that lists upcoming workshops from GET /api/workshops, before any server exists. You write handlers with realistic data, start the mock only in development, force a slow response, a 500 error and an empty list to build each state, test the same handlers in Vitest, and then point the page at a real API by changing one variable.

MSW 3 moved a few imports since version 2. http and HttpResponse now come from msw/http, delay from msw/utils/delay, and the onUnhandledRequest option is called onUnhandledFrame. Code from older blog posts that imports everything from msw will not work, so follow the imports shown here.

Step 1 · Create the project and install MSW

Create a plain JavaScript project from Vite's template in a new folder, then add MSW and Vitest as development dependencies. Both are pinned to the versions this tutorial was written with:

Bash
cd ~
npm create vite@9 msw-demo -- --template vanilla --no-interactive
cd msw-demo
npm install
npm install --save-dev msw@3.0.7 vitest@5.1.1

MSW 3 needs Node.js 22.12 or later, so Node.js 26 is fine. Remove the template's demo files. You replace src/main.js and src/style.css later:

Bash
rm -rf src/counter.js src/assets
mkdir -p src/mocks server

Check it worked

Bash
npm ls msw vitest vite

The tree lists msw@3.0.7, vitest@5.1.1 and vite@8. with a patch number. If npm prints ERESOLVE, check node --version reports v26.

Step 2 · Describe the API with request handlers

Agree the shape of the response with whoever builds the back end, even if it is you next month. Here the endpoint returns an array of workshops, each with an id, title, city, ISO date and seatsLeft.

The page reads the API address from an environment variable, so the same code works against the mock and the real server. Vite exposes variables that start with VITE_ to your code as import.meta.env.VITE_.... A .env file applies in every mode, including tests:

Bash
cat > .env <<'ENV'
VITE_API_URL=http://localhost:4000
ENV

Write the API module. getWorkshops does the request and throws on a bad status. loadWorkshops turns any outcome into one of three states the page can draw: ready, empty or error:

Bash
cat > src/api.js <<'JS'
const API_URL = import.meta.env.VITE_API_URL

export async function getWorkshops() {
  const response = await fetch(`${API_URL}/api/workshops`)
  if (!response.ok) {
    throw new Error(`The API answered ${response.status}`)
  }
  return response.json()
}

export async function loadWorkshops() {
  try {
    const workshops = await getWorkshops()
    return { state: workshops.length === 0 ? 'empty' : 'ready', workshops }
  } catch (error) {
    return { state: 'error', message: error.message }
  }
}
JS

Now the handlers. Each one matches a method and URL and returns a response. handlers holds the normal behaviour. scenarios holds overrides for the states that are hard to produce from a real server:

Bash
cat > src/mocks/handlers.js <<'JS'
import { http, HttpResponse } from 'msw/http'
import { delay } from 'msw/utils/delay'

const workshopsUrl = `${import.meta.env.VITE_API_URL}/api/workshops`

export const workshops = [
  { id: 1, title: 'Accessible forms in an afternoon', city: 'Lagos', date: '2026-12-03', seatsLeft: 12 },
  { id: 2, title: 'Offline-first web apps', city: 'Nairobi', date: '2026-12-10', seatsLeft: 3 },
  { id: 3, title: 'Testing with Playwright', city: 'Kigali', date: '2026-12-17', seatsLeft: 0 },
]

export const handlers = [
  http.get(workshopsUrl, async () => {
    await delay()
    return HttpResponse.json(workshops)
  }),
]

export const scenarios = {
  slow: http.get(workshopsUrl, async () => {
    await delay(3000)
    return HttpResponse.json(workshops)
  }),
  error: http.get(workshopsUrl, () =>
    HttpResponse.json({ message: 'Database unavailable' }, { status: 500 }),
  ),
  empty: http.get(workshopsUrl, () => HttpResponse.json([])),
}
JS

delay() with no argument waits a random 100 to 400 milliseconds in the browser, so your page never gets used to instant answers. delay(3000) waits exactly three seconds. Keep mock data realistic: a full workshop, a long title, a non-English city name. Mocks that only return "foo" hide layout bugs until launch day.

Check it worked

Bash
node --check src/api.js
node --check src/mocks/handlers.js
ls src src/mocks

node --check prints nothing when the syntax is valid, and a SyntaxError with the line number when it is not. The listing shows api.js in src and handlers.js in src/mocks.

Step 3 · Run the handlers in Vitest

You can prove the handlers work before opening a browser. MSW's Node integration, setupServer from msw/node, intercepts fetch inside Node.js with the same handler list. Create the server:

Bash
cat > src/mocks/node.js <<'JS'
import { setupServer } from 'msw/node'
import { handlers } from './handlers.js'

export const server = setupServer(...handlers)
JS

Start it before the tests, reset any per-test overrides after each one, and close it at the end. onUnhandledFrame: 'error' makes a test fail if the code calls a URL you have not mocked, which catches typos in addresses:

Bash
cat > vitest.setup.js <<'JS'
import { afterAll, afterEach, beforeAll } from 'vitest'
import { server } from './src/mocks/node.js'

beforeAll(() => server.listen({ onUnhandledFrame: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
JS
cat > vite.config.js <<'JS'
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    setupFiles: ['./vitest.setup.js'],
  },
})
JS

Write three tests. The first uses the default handler. The other two prepend a scenario with server.use, which wins over the defaults until resetHandlers runs:

Bash
cat > src/api.test.js <<'JS'
import { describe, expect, it } from 'vitest'
import { loadWorkshops } from './api.js'
import { scenarios, workshops } from './mocks/handlers.js'
import { server } from './mocks/node.js'

describe('loadWorkshops', () => {
  it('returns the list when the API answers', async () => {
    expect(await loadWorkshops()).toEqual({ state: 'ready', workshops })
  })

  it('reports an empty list', async () => {
    server.use(scenarios.empty)
    expect(await loadWorkshops()).toEqual({ state: 'empty', workshops: [] })
  })

  it('turns a 500 into an error state', async () => {
    server.use(scenarios.error)
    expect(await loadWorkshops()).toEqual({ state: 'error', message: 'The API answered 500' })
  })
})
JS
npx vitest run

Check it worked

Vitest reports Test Files 1 passed (1) and Tests 3 passed (3). Change 'The API answered 500' in the test to 'The API answered 404' and run npx vitest run again: the third test fails and shows both messages. Change it back before you continue.

Step 4 · Start the service worker in development only

In the browser, MSW needs its worker script served from your site's root. Copy it into public/. --save records the folder in package.json, so after a future MSW upgrade you only run npx msw init to refresh the file:

Bash
npx msw init public --save

Switch mocking on for the development server with a mode-specific env file. Vite reads .env.development only when it runs npm run dev, never for a build:

Bash
cat > .env.development <<'ENV'
VITE_API_MOCKING=on
ENV
cat > src/mocks/browser.js <<'JS'
import { setupWorker } from 'msw/browser'
import { handlers } from './handlers.js'

export const worker = setupWorker(...handlers)
JS

Now the page. enableMocking returns at once unless this is the dev server with mocking on. The dynamic import() calls mean MSW is only downloaded when it is needed. The page waits for the worker before its first request, otherwise that request could reach the network before the mock is ready. A ?scenario= query parameter picks one of the overrides:

Bash
cat > src/main.js <<'JS'
import './style.css'
import { loadWorkshops } from './api.js'

async function enableMocking() {
  if (!import.meta.env.DEV || import.meta.env.VITE_API_MOCKING !== 'on') {
    return
  }
  const { worker } = await import('./mocks/browser.js')
  const { scenarios } = await import('./mocks/handlers.js')
  await worker.start({ onUnhandledFrame: 'bypass' })

  const scenario = new URLSearchParams(location.search).get('scenario')
  if (scenario && Object.hasOwn(scenarios, scenario)) {
    worker.use(scenarios[scenario])
  }
}

const app = document.querySelector('#app')
app.innerHTML = `
  <h1>Upcoming workshops</h1>
  <p id="status" role="status"></p>
  <ul id="list"></ul>
  <button id="retry" type="button" hidden>Try again</button>
`
const status = app.querySelector('#status')
const list = app.querySelector('#list')
const retry = app.querySelector('#retry')
const dateFormat = new Intl.DateTimeFormat(undefined, { day: 'numeric', month: 'long' })

async function render() {
  status.textContent = 'Loading workshops…'
  list.replaceChildren()
  retry.hidden = true

  const result = await loadWorkshops()

  if (result.state === 'error') {
    status.textContent = 'Workshops could not be loaded. Check your connection and try again.'
    retry.hidden = false
    return
  }
  if (result.state === 'empty') {
    status.textContent = 'No workshops are scheduled yet. Check back next month.'
    return
  }

  status.textContent = `${result.workshops.length} workshops`
  for (const workshop of result.workshops) {
    const item = document.createElement('li')
    const seats = workshop.seatsLeft === 0 ? 'Full' : `${workshop.seatsLeft} seats left`
    item.textContent = `${workshop.title}, ${workshop.city}, ${dateFormat.format(new Date(workshop.date))}: ${seats}`
    list.append(item)
  }
}

retry.addEventListener('click', render)

await enableMocking()
render()
JS
cat > src/style.css <<'CSS'
body {
  font-family: system-ui, sans-serif;
  margin: 0 auto;
  max-width: 40rem;
  padding: 1rem;
  line-height: 1.5;
}
li {
  padding: 0.5rem 0;
  border-bottom: 1px solid #d9dce1;
}
CSS

onUnhandledFrame: 'bypass' lets requests with no handler, such as Vite's own module requests, go to the network without a warning. The status paragraph has role="status", so screen readers announce each change of state.

Start the dev server and leave it running. Use a second terminal in ~/msw-demo for the commands that follow:

Bash
npm run dev
Bash
curl -s http://localhost:5173/mockServiceWorker.js | head -n 12

Check it worked

curl prints the top of the worker script, a comment block naming Mock Service Worker. Open http://localhost:5173/ in your browser. The page shows 3 workshops and three rows, the last ending in Full. The developer console shows [MSW] Mocking enabled. and one collapsed entry for GET http://localhost:4000/api/workshops. Nothing listens on port 4000: the answer came from your handler. Service workers only run on https or localhost, so open the page by that name and not by your machine's IP address.

Step 5 · Build every state with scenarios

Open each scenario in the browser and watch the page:

  • http://localhost:5173/?scenario=slow shows Loading workshops… for three seconds, then the list.
  • http://localhost:5173/?scenario=error shows the error message and a Try again button.
  • http://localhost:5173/?scenario=empty shows No workshops are scheduled yet.

The slow scenario is worth more time than it seems. Many readers of your site will be on prepaid mobile data or a busy network, where three seconds is an ordinary wait. A page that looks broken while it loads loses them.

Clicking around proves it once. A browser test proves it on every change. Install Playwright and Chromium; on Linux, --with-deps also installs the system libraries Chromium needs and may ask for your password:

Bash
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

Write a script that visits the page in each scenario, in a fresh browser context each time so no worker state carries over:

Bash
cat > check-mocks.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'

const site = 'http://localhost:5173/'
const browser = await chromium.launch()

async function open(query = '') {
  const context = await browser.newContext()
  const page = await context.newPage()
  const logs = []
  page.on('console', (message) => logs.push(message.text()))
  await page.goto(site + query)
  return { page, logs }
}

// Default handlers: three workshops, the last one full.
const normal = await open()
await normal.page.getByText('3 workshops').waitFor()
const rows = normal.page.getByRole('listitem')
assert.equal(await rows.count(), 3)
assert.match(await rows.nth(2).textContent(), /Kigali.*Full$/)
assert.ok(normal.logs.some((line) => line.includes('[MSW] Mocking enabled.')), 'worker started')

// Slow: the loading text is visible before the list arrives.
const slow = await open('?scenario=slow')
await slow.page.getByText('Loading workshops…').waitFor()
await slow.page.getByText('3 workshops').waitFor({ timeout: 10000 })

// Error: the message and the retry button appear.
const failing = await open('?scenario=error')
await failing.page.getByText('Workshops could not be loaded.').waitFor()
assert.ok(await failing.page.getByRole('button', { name: 'Try again' }).isVisible())

// Empty: a friendly message and no rows.
const empty = await open('?scenario=empty')
await empty.page.getByText('No workshops are scheduled yet.').waitFor()
assert.equal(await empty.page.getByRole('listitem').count(), 0)

await browser.close()
console.log('PASS: every state renders from the mocks')
JS
node check-mocks.mjs

Check it worked

The last line of output is PASS: every state renders from the mocks. To add a state, such as a 401 for a signed-out user, add one entry to scenarios and visit ?scenario= with its name.

Step 6 · Keep the mocks out of the production build

In a build, import.meta.env.DEV is false, so enableMocking returns at its first line and the bundler drops the code behind it, including both import() calls. Build and look:

Bash
npm run build
ls dist dist/assets
if grep -l 'mockServiceWorker' dist/assets/*.js; then echo 'mocking code found in the bundle'; false; else echo 'no mocking code in the bundle'; fi

Check it worked

Vite's build summary shows one small JavaScript file (something like 2 kB) and one CSS file, and ls lists the same two files under dist/assets/, with no separate chunk for browser.js or handlers.js. The last line is no mocking code in the bundle; if MSW had leaked into the bundle, the command would print the file name and mocking code found in the bundle, then fail. dist/ still contains mockServiceWorker.js, because Vite copies everything in public/. Nothing in the built page registers it, so it is inert. If you would rather not ship it, delete it from dist/ in your deploy script.

For production, set the real address in a .env.production file, for example VITE_API_URL=https://api.example.com (replace this with your API's address). Everything in a VITE_ variable ends up in the JavaScript every visitor downloads, so never put a secret key there.

Step 7 · Switch to the real API with one variable

When the back end exists, the page should use it with no code change. To try this here, write a tiny stand-in for the real API. It returns a different workshop, so you can tell which source answered, and allows requests from the dev server's origin:

Bash
cat > server/real-api.mjs <<'JS'
import { createServer } from 'node:http'

const workshops = [
  { id: 7, title: 'Design tokens in practice', city: 'Accra', date: '2027-01-14', seatsLeft: 20 },
]

createServer((request, response) => {
  response.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173')
  if (request.method === 'GET' && request.url === '/api/workshops') {
    response.writeHead(200, { 'Content-Type': 'application/json' })
    response.end(JSON.stringify(workshops))
    return
  }
  response.writeHead(404, { 'Content-Type': 'application/json' })
  response.end(JSON.stringify({ message: 'Not found' }))
}).listen(4000, () => console.log('API listening on http://localhost:4000'))
JS

Start it in a third terminal and leave it running:

Bash
node server/real-api.mjs

Stop the dev server with Ctrl+C in its terminal, then start it again with mocking off. A variable already set in the shell takes priority over the .env files:

Bash
VITE_API_MOCKING=off npm run dev

In Windows PowerShell, run $env:VITE_API_MOCKING='off'; npm run dev instead. To keep the setting without typing it each time, put VITE_API_MOCKING=off in .env.development.local. The Vite template's .gitignore already excludes *.local files, so the choice stays on your machine.

Check the page now reads from the server, and that no service worker is registered:

Bash
cat > check-real.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'

const browser = await chromium.launch()
const page = await (await browser.newContext()).newPage()
await page.goto('http://localhost:5173/')
await page.getByText('1 workshops').waitFor()
assert.match(await page.getByRole('listitem').first().textContent(), /Design tokens in practice, Accra/)
const workers = await page.evaluate(async () => (await navigator.serviceWorker.getRegistrations()).length)
assert.equal(workers, 0, 'no mock worker registered')
await browser.close()
console.log('PASS: the page reads from the real API')
JS
node check-real.mjs

Check it worked

The output ends with PASS: the page reads from the real API, and the browser shows one workshop in Accra. The 1 workshops wording is the kind of small bug a mock with three items never shows. Fix it with Intl.PluralRules once you have more than one language to support. Your browser may still have the worker from earlier registered on this origin; it stays idle because the page no longer starts it, and you can remove it under Application, Service workers in the developer tools.

Step 8 · Clean up

Stop the dev server and the stand-in API with Ctrl+C in their terminals. Then delete the project, which also removes the local Playwright and MSW packages. The Chromium browser Playwright downloaded stays in a shared cache; run npx playwright uninstall from the project folder first if you want it gone too.

Bash
cd ~
rm -rf ~/msw-demo

Check it worked

ls ~/msw-demo reports that there is no such file or directory, and neither http://localhost:5173/ nor http://localhost:4000/api/workshops loads.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.