API Engineering

Mocking APIs for Frontend Development: MSW and Local Contract Testing

Accelerate frontend development with Mock Service Worker (MSW) and realistic JSON fixtures. Develop and test UI components before backend endpoints exist.

By Cometflow API Engineering Team • Updated 2026-10-06

Mock Service Worker (MSW) intercepts outgoing network requests at the Service Worker level in browsers (and at the socket layer in Node.js tests), allowing your frontend components to make real fetch() calls while receiving deterministic mock responses.

1. Defining an MSW 2.0 Request Handler

import { http, HttpResponse, delay } from 'msw';

export const handlers = [
  http.get('/api/v1/user', async () => {
    await delay(150);
    return HttpResponse.json({
      id: 'usr_101',
      name: 'Ada Lovelace',
      role: 'admin'
    });
  })
];

2. Simulating Error States & Network Latency

Beyond happy-path 200 OK fixtures, MSW lets you override handlers inside individual Vitest or Playwright tests to simulate 429 Too Many Requests, 503 Service Unavailable, or slow 2-second mobile network delays—verifying that your UI loading skeletons, retry boundaries, and error banners behave properly before production deployment.

Frequently Asked Questions (FAQ)

Why is MSW better than stubbing window.fetch in unit tests?

Stubbing window.fetch bypasses your application's actual request serialization, headers, and URL construction logic. MSW tests the full network stack right up to the HTTP boundary.