How to Mock a REST API with a Service Worker for Front-End Work
Build mock REST endpoints with templated JSON, delays, error codes and CRUD collections, test them in the browser and export a service worker for your app.

How to Mock a REST API with a Service Worker for Front-End Work
Front-end work often waits on a back end that is not ready, unstable, or hard to push into the exact state you need. A mocked API removes that dependency: your app calls the same URLs, but responses come from definitions you control. Mocking in a service worker is especially convenient, because the app's code does not change at all. This guide explains how service-worker mocking works, what to mock, and how to build and export mocks with a free browser tool.
Why mock at the network level
You can fake data in many places: hard-coded objects in components, a stub module, or a local JSON server. Each has trade-offs. Hard-coded data skips your real fetch code, so bugs in request building and error handling go unnoticed. A separate server needs to be started and kept in sync.
A service worker sits between the page and the network. Once registered, it receives every fetch event within its scope and can answer with a synthetic Response. Your components, data hooks and retry logic run exactly as in production, but the reply comes from the mock. That makes it a good fit for building screens before the API exists, reproducing rare errors on demand, and running demos offline.
Two browser rules shape how this works. A service worker must be served from the same origin as the page it controls, and it only runs on HTTPS or localhost.
What a useful mock includes
Realistic mocks go beyond a happy-path JSON blob:
- Path parameters, so
/users/7and/users/8return different ids. - Status codes, including 201 for creation, 204 with no body, 404 and 5xx errors.
- Delays, to see loading states and test timeouts.
- Dynamic values such as timestamps and random ids.
- Stateful collections, so creating an item and then listing shows it.
Building mocks with the tool
Open the Mock REST API with Service Worker and go to Endpoints. For each endpoint set the method (or ANY), a path pattern, the status, an optional delay in milliseconds, response headers and a body. In patterns, :id captures a single segment and * matches the rest. The first enabled match wins, so move specific routes above general ones with the arrow buttons.
Bodies and header values accept templates: {{params.id}}, {{query.page}}, {{body.name}} and {{headers.authorization}} echo parts of the request, while {{now}}, {{timestamp}}, {{uuid}} and {{int 1 100}} generate values.
For resources, add a collection with a base path and a seed JSON array. Listing supports ?q= search, field filters like ?done=true, and paging with _start and _limit. GET, PUT, PATCH and DELETE on /:id act on one item, and POST adds an item with the next numeric id. Changes are held in memory, so a full create, edit and delete flow behaves sensibly.
While the page is open it answers requests to the host mock.local. The Try it tab sends a request and shows status, headers, body and timing, and the log records which route matched each call.
When the mocks are ready, set a path prefix and download mock-sw.js with the registration snippet. Because a site can only register workers from its own origin, the file goes into your app's public folder; register it only in development, reload once, and matching requests under the prefix are answered locally.
Worked example
Define GET /api/users/:id with the body { "id": {{params.id}}, "name": "User {{params.id}}", "at": "{{now}}" }. A request to /api/users/7 returns 200 with id 7 and the current time. Add a todos collection seeded with two items; POST /api/todos with a title returns 201 and id 3. Finally add GET /api/flaky with status 503 and an 800 ms delay, and use it to check that your app shows a spinner and then a sensible retry message.
Tips and common mistakes
- Keep the registration behind a development flag so the worker never ships to users.
- If requests are not intercepted, check the scope and the path prefix first.
- Remember that the very first page load happens before the worker activates; reload once.
- Unregister old workers in the browser's application panel when switching projects.
- Mirror real error formats, not just status codes, so your error UI is tested properly.
Limits
This is a development aid, not a server. Mocks are not reachable from other devices, and collection data resets whenever the page or worker restarts. Service workers require HTTPS or localhost and do not intercept requests made before activation. Responses are not validated against an OpenAPI or other schema, so keeping mocks in step with the real API is up to you.



