Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec

Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

What you will learn

  • Explain how a service worker can answer a fetch inside the browser
  • Generate MSW handlers and faker data from an OpenAPI spec with Orval's mock option
  • Start the worker before the first render, in development only
  • Switch between mocked and real backends without changing app code

Before you start

  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • Server State With TanStack Query

On real teams the screen is often ready before the API is. Without a backend, the front end has nothing to talk to and waits. But both sides can agree on the spec first, and from that same spec you can generate a fake backend. The screen gets built and tried now, and when the real API is ready you simply switch to it.

This article uses Mock Service Worker (MSW): a small script in the browser catches the request your app sends and answers it with fake data that has exactly the shape the spec describes. The project is the library client from the Orval article.

Normal mode and mocked mode

Who answers the request npm run dev:real browser BookList Book API :8080 12 books GET /api/books (network) npm run dev browser BookList service worker 6 fake books server stopped
Same app, same request. In mocked mode the request never leaves the browser.

Normally, GET /api/books?size=50 leaves the browser, crosses the network, reaches the Book API on port 8080, and 200 with twelve books rides back. If there is no server yet, nothing answers and the screen can't work.

A service worker is a script the browser runs on the side, between your app and the network. Ours lives in public/mockServiceWorker.js. When the app calls fetch, the browser fires a fetch event and the worker catches it. The worker does not know the answer itself: it sends a REQUEST message to the page, where our handlers live. If a handler matched, the page sends back MOCK_RESPONSE and the worker hands that answer to the waiting fetch. If none matched, the worker lets the request pass to the network as if nothing happened. The app cannot tell who answered.

The worker file is copied in by the msw init command, and its own header comment asks you not to modify it.

Orval writes the handlers and the fake data

We don't write handlers by hand. Turning on mock: true in the Orval config is enough (the first part of orval.config.ts; the Zod config below it is unchanged):

import { defineConfig } from 'orval'
import { faker } from '@faker-js/faker'
import { operationName } from './orval.names'

// the API describes itself here
const input = 'http://localhost:8080/v3/api-docs'

// one rule per field: realistic fake values
const fake = {
  id: () => faker.number.int({ min: 1, max: 99 }),
  title: () => faker.book.title(),
  author: () => faker.book.author(),
  pages: () =>
    faker.number.int({ min: 120, max: 600 }),
  totalElements: () => 6,
  totalPages: () => 1,
}

export default defineConfig({
  books: {
    input,
    output: {
      target: 'src/api/books.ts',
      schemas: 'src/api/model',
      client: 'react-query',
      // realistic fake answers for the mock server
      mock: true,
      override: {
        operationName,
        mock: {
          required: true,
          arrayMin: 6,
          arrayMax: 6,
          properties: fake,
        },
        // our own fetch wrapper (fetcher.ts)
        mutator: {
          path: 'src/api/fetcher.ts',
          name: 'customFetch',
        },
        // hooks return the body, not { data, status }
        fetch: {
          includeHttpResponseReturnType: false,
        },
      },
      // short lines, the same style as our own files
      formatter: 'prettier',
    },
  },

Next to books.ts, Orval now writes books.msw.ts with the handlers and books.faker.ts with the fake data. The fake object holds one rule per field: an id from 1 to 99, a title from faker.book.title(), an author from faker.book.author(), pages from 120 to 600, and always six elements on one page. required: true fills every field, and arrayMin and arrayMax of 6 give lists of exactly six. The input is the same spec the client uses, so the mocks always have the real shape.

The faker lines fill one answer

An excerpt of the generated books.msw.ts:

export const getGetBooksResponseMock = (
  overrideResponse: Partial<
    Extract<PagedModelBookResponse, object>
  > = {},
): PagedModelBookResponse => ({
  content: Array.from(
    { length: faker.number.int({ min: 6, max: 6 }) },
    (_, i) => i + 1,
  ).map(() => ({
    id: (() =>
      faker.number.int({ min: 1, max: 99 }))(),
    title: (() => faker.book.title())(),
    author: (() => faker.book.author())(),
    pages: (() =>
      faker.number.int({ min: 120, max: 600 }))(),
  })),
  page: {
    size: faker.number.int(),
    number: faker.number.int(),
    totalElements: (() => 6)(),
    totalPages: (() => 1)(),
  },
  ...overrideResponse,
})

Six empty rows, each filled field by field with our rules. Look at page.size and page.number: we gave them no rule, so faker picks any integer. The value has the right type, but it is a huge number no one would ask for as a page size. Realistic, not real: one of the fake rows in the run was The Hobbit by Laurence Sterne.

A handler: match, then answer

export const getGetBooksMockHandler = (
  overrideResponse?:
    | PagedModelBookResponse
    | ((
        info: Parameters<HttpResponseResolver>[0],
      ) =>
        | Promise<PagedModelBookResponse>
        | PagedModelBookResponse),
  options?: RequestHandlerOptions,
) => {
  return http.get(
    '*/api/books',
    async (
      info: Parameters<HttpResponseResolver>[0],
    ) => {
      return HttpResponse.json(
        overrideResponse !== undefined
          ? typeof overrideResponse === 'function'
            ? await overrideResponse(info)
            : overrideResponse
          : getGetBooksResponseMock(),
        { status: 200 },
      )
    },
    options,
  )
}

A handler is a method, a path and a function that returns the answer. http.get('*/api/books', ...) matches any origin (the star) with the path /api/books; the query string ?size=50 is not part of the match. HttpResponse.json(..., { status: 200 }) answers exactly like a real server would. Pass an overrideResponse when a test needs one exact case. There is one handler per endpoint in the spec.

All handlers into one worker

import { faker } from '@faker-js/faker'
import { setupWorker } from 'msw/browser'
import { getLibraryAPIMock } from '../api/books.msw'

// same fake books on every reload
faker.seed(8)

// the handlers were generated from the spec
export const worker = setupWorker(
  ...getLibraryAPIMock(),
)

// BREAK IT: delete public/mockServiceWorker.js and
// worker.start() throws "[MSW] Failed to register the
// Service Worker" - nothing renders, the page is empty

getLibraryAPIMock() returns all seven generated handlers, and setupWorker turns them into a worker that is not started yet. faker.seed(8) makes faker produce the same sequence every time, so a reload shows the same books. Without the seed, the list would change on every reload.

Start the worker, then render

import { createRoot } from 'react-dom/client'
import {
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query'
import './index.css'
import App from './App'

const queryClient = new QueryClient()

async function start() {
  // dev only: the worker answers /api requests itself
  const mocks = import.meta.env.VITE_MOCKS === 'on'
  if (import.meta.env.DEV && mocks) {
    const { worker } = await import('./mocks/browser')
    await worker.start()
  }
  createRoot(document.getElementById('root')!).render(
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>,
  )
}
start()
# mocks on: a service worker answers /api requests, no backend needed
VITE_MOCKS=on

Line 14 checks two things: import.meta.env.DEV, true in the dev server, and VITE_MOCKS, which .env.development sets to on. Only then does line 15 load msw, faker and the handlers with a dynamic import. Line 16 waits for worker.start(), which registers /mockServiceWorker.js, and only then is the app rendered. If you rendered first, the very first request could go out before the worker was ready.

Six books, no server running

With the Book API stopped (reachable on :8080 ? false) and npm run dev, the run recorded:

PASS A (mocks on, API stopped): GET /api/books requests = 1
console lines with [MSW]: ["%c[MSW] Mocking enabled. color:orangered;font-weight:bold;","[MSW] 17:32:50 GET /api/books (%c200 OK%c) color:#69AB32 color:inherit"]
answered by the service worker? true | status 200
titles on screen: ["Under the Volcano","A Bend in the River","On the Road","The Hobbit","Underworld","Walden"]
after a reload, same titles? true
The library page showing 6 books, all fake: Under the Volcano by T. Smollett, A Bend in the River by J.D. Salinger, On the Road by José Rizal, The Hobbit by Laurence Sterne, Underworld by Gustave Doré and Walden by C.S. Lewis, each with a page count and a Remove button.
Six fake books from the service worker, while the Book API is not running.

dev and dev:real

  "scripts": {
    "api": "orval",
    "dev": "vite",
    "dev:real": "vite --mode real",
    "build": "tsc -b && vite build",
    "preview": "vite preview"
  },
# mocks off: requests go through the dev proxy to the real API
VITE_MOCKS=off

npm run dev loads .env.development: mocks on, six books, fromServiceWorker: true. npm run dev:real runs Vite with --mode real, which loads .env.real: mocks off, no worker at all. The same GET goes through the dev proxy to port 8080:

PASS B (npm run dev:real, API running): GET /api/books requests = 1 | fromServiceWorker: false | status 200
console lines with [MSW]: []
page text: Library | 12 books

Not one line of BookList changed between the two. Only the one who answers changed.

No mock code in the bundle

In a production build DEV is false, so the if on line 14 is always false and the block, with its dynamic import, is left out. The run searched the built bundle for setupWorker, mockServiceWorker and faker:

production bundle contains the mock code? false

mockServiceWorker.js is still copied from public/ as a plain file, but nothing registers it, so it never runs.

Common mistakes

  • The worker file is missing from public/. The dev server sends back an HTML page instead of the script, the console says [MSW] Failed to register the Service Worker, worker.start() throws, and the page stays empty.
  • Rendering before worker.start() finishes. The first request can slip past the mock.
  • No seed. The fake list changes on every reload, which makes screens hard to compare.

Quick recap

PieceJob
Service workerCatches every request inside the browser
mock: true in OrvalWrites the handlers and faker data from the spec
http.get('*/api/books')Matches the request and returns the answer
await worker.start()Dev only, before the first render
dev / dev:realChanges who answers, never the app code
npm run buildNo mock code in the bundle

Keep going in React · 56 of 59

Previous
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Next post
A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Server State With TanStack Query: One Key, One Request, One Cache

Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.

Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache

Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.

Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval

Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.

A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy

Generate a React client from FastAPI's /openapi.json, then hit the CORS wall: the API answers 200 but the browser blocks it. Fix it with CORSMiddleware, or avoid it with the Vite proxy and one VITE_API_URL variable.

On this page

  • Normal mode and mocked mode
  • Orval writes the handlers and the fake data
  • The faker lines fill one answer
  • A handler: match, then answer
  • All handlers into one worker
  • Start the worker, then render
  • Six books, no server running
  • dev and dev:real
  • No mock code in the bundle
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.