Course contentsShow
← React
Lesson 2094 of 2,39646. Testing React with RTLFree lesson

MSW in Dev Mode for UI Development

Enable MSW browser worker in development to prototype UIs without backend APIs being ready.

MSW in Dev Mode for UI Development

What you'll learn: How to enable MSW's browser worker during development so you can build and iterate on UI components before the backend API is ready.

The Development Problem

You've been using MSW in tests, but there's a powerful extension: running MSW directly in your browser during development. This means you can prototype entire features, complete with realistic API responses, without touching a real backend or writing manual fetch mocks.

Enabling the Browser Worker

MSW provides a separate setupWorker() function for browser environments. First, generate the service worker file:

npx msw init public/ --save

This creates mockServiceWorker.js in your public folder.

Then create a src/mocks/browser.ts file:

import { setupWorker } from 'msw/browser'
import { http } from 'msw'

export const worker = setupWorker(
  http.get('/api/users', () => {
    return Response.json([
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ])
  })
)

In your src/main.tsx, conditionally start the worker in development:

if (import.meta.env.DEV) {
  const { worker } = await import('./mocks/browser')
  await worker.start()
}

// Then your normal React render...

The Workflow Advantage

Now when you run your dev server, all API calls are intercepted by MSW. You can:

  • Build complex UIs without waiting for backend implementation
  • Test edge cases (errors, empty states) by tweaking handlers
  • Share prototypes with designers without backend deployment

Key Takeaway: MSW in dev mode transforms your development workflow by letting you control all network behavior locally, making frontend development independent of backend progress.