Suppose you are building an asset list and want to see how the table looks with one record. A status 200 response containing one asset is enough to keep working on the page. The frontend can construct that Response itself. The next decision is this: when you open the asset list this time, should the real query endpoint still receive a request?
How can the page get an asset before the backend is ready?
Suppose the page normally sends a GET to same-origin /api/assets and reads items from the JSON. During development you can put the check inside the request function your pages share. Check the URL and method before calling fetch. On a match, return a new response directly. You can run the following in the console of a local development page. It constructs a fresh Response each time so the list can read the body even if you refresh twice.1
const assetsURL = new URL("/api/assets", location.origin).href;
function mockAssets() {
return Response.json({ items: [{ id: 1, name: "演示键盘" }] });
}
async function send(request) {
if (request.method === "GET" && request.url === assetsURL) {
return mockAssets();
}
return fetch(request);
}
const response = await send(new Request(assetsURL));
console.log(response.status, (await response.json()).items[0].name);
// 200 演示键盘
The call ends at return mockAssets(). The backend need not be running. To test an empty list, change items to []. To test an error message, have the same rule return Response.json({ message: "暂时不可用" }, { status: 503 }) (“temporarily unavailable”), then see whether the page follows its error branch based on response.ok. The match covers GET for this exact URL. Adding pagination query parameters, switching to POST, or calling fetch directly elsewhere will miss the rule.
Can the real request still go through while the page sees different data?
Yes. The difference is when the replacement happens. For the asset list, the client first sends the GET and receives its response, then replaces what it gives the page with the same mockAssets(). Even if the endpoint returns an empty list, the page shows “演示键盘” (demo keyboard). The server access log contains the GET.
My asset management project used this approach for its operation log list. The frontend configuration defined test data for the full query URL and GET method, along with a switch to enable it. On May 13, 2025, I added mockResponse() to the response chain of Express Http Client. Here is that configuration reduced to the asset example. It reuses the previous assetsURL and mockAssets and belongs in a frontend module that can import npm packages.23
import { httpClient, mockResponse } from "express-http-client";
const setup = httpClient();
setup.addResponseInterceptor(mockResponse(true, {
[assetsURL]: { GET: mockAssets },
}));
const api = setup.create(location.origin);
const result = await api.send("/api/assets");
console.log(result.status, (await result.json()).items[0].name);
// 200 演示键盘
The true enables mocking. In 0.3.6, send() first executes fetch(request), then calls the response interceptors. With the switch enabled, mockResponse() looks up a handler by full URL and method and writes the return value into data.response. This explains an easily missed detail: give this instance an unconfigured URL and the request still goes out, but the middleware replaces the result seen by the page with a 404 by default. To mock data for only one page, you can give it a separate client instance.24
Both pages show the demo keyboard. How do we check where the request went?
Have the local test endpoint increment a counter for every GET /api/assets and return { "items": [] }. Run the two versions separately. Along with the record displayed on the page, look at how far the server counter advances. The table shows the result of pointing the two examples at the same local endpoint.5
| Interception point | Asset seen by the page | GETs received by the server |
|---|---|---|
| Return directly before calling Fetch | 演示键盘 (demo keyboard) | 0 |
| Replace the response after Fetch returns | 演示键盘 (demo keyboard) | 1 |
With a delete button, this difference directly affects the data. To test a “deleted successfully” message while preserving the test asset, match the corresponding DELETE before sending it and return new Response(null, { status: 204 }). Put the same 204 in a response interceptor and the real deletion request has already gone out. The page might show the same message while the server has actually deleted the record.
What if pages make requests through several different paths?
If every page goes through one request function, the check in the first example covers them. If some call Fetch directly and others use third-party libraries, one function cannot cover all entry points. In that case interception can move into a browser Service Worker. The browser runs this script for the site. It can receive request events from controlled pages and provide responses with respondWith(). MSW (Mock Service Worker) takes advantage of this capability in browsers. When a mock rule matches, the page can call its normal client, the request appears in developer tools, and the target API service need not process it.67
Does the same rule still apply when the request comes from a different entry point? Requestly’s React example registers an interceptor on one Axios instance. A component must use that instance to get the authentication header automatically. AppSignal’s Got example similarly uses got.extend() to create a client with reusable settings, but it handles requests from a Node.js process. Browser extensions have their own entry point: MDN shows how to match a URL with webRequest and redirect a request to another resource. A Firefox extension could mock a response by letting the real GET /api/assets go through, then using webRequest.filterResponseData() to replace the response body with JSON containing “演示键盘”, without changing page code. When substituting data for one asset list, first identify the client the page actually uses before deciding whether browser-level interception is necessary.8910
I also looked at @mswjs/interceptors and Nock. The former supplies a lower-level request interception interface that lets you provide a response during the request event. Nock targets Node.js tests. You can define responses for a host, path, and method and then check whether the expected requests happened. To mock browser data, first identify which calls need coverage and whether the real request should go out. That tells you where the rule belongs. My log list used response replacement. The client design article describes the execution order it shares with authentication and logging middleware.1112
References
Footnotes
-
MDN contributors. (n.d.). Response: json() static method. MDN Web Docs. Examples: creating a JSON response and specifying status. ↩
-
Cai, B. [S2thend]. (2025, May 13). Add simple mock response interceptor middleware. GitHub. Implementation commit, Matching conditions and default response for unmatched requests in 0.3.6. Filed under the date of the first implementation. ↩ ↩2
-
CaiBorui. (2025, May 21). Add support for express http handler [Local Git commit
54933d5, retained by the author]. The asset management project’sfrontend/src/utils/ExpressHttpHandler.jsregistered a mock response for the operation log GET. The switch in the commit wasfalse. The asset list in this post is an adapted teaching example. ↩ -
Cai, B. [S2thend]. (2025, May 13). HttpClient.js [0.3.6]. GitHub. send calls Fetch, then executes the response chain. ↩
-
CaiBorui. (2026, November 25). Request counts for returning before send and replacing a response [Local verification]. On Node.js 22.12.0 with a local HTTP service and the built express-http-client 0.3.6 package, I checked the status code, parsed asset name, and server request count. Both examples used the same mock data and ran against a local address. ↩
-
MDN contributors. (n.d.). FetchEvent: respondWith() method. MDN Web Docs. Method description and examples. ↩
-
Mock Service Worker contributors. (n.d.). Mock Service Worker. GitHub. Browser: How does it work?. ↩
-
Thakur, D. (2024, September 3). How to Implement HTTP Interceptors in JavaScript Frameworks. Requestly. React section: creating an Axios instance and using it in a component. ↩
-
Olatunji, D. (2024, September 11). Top 5 HTTP Request Libraries for Node.js. AppSignal Blog. 3. Got. ↩
-
MDN contributors. (n.d.). Intercept HTTP requests. MDN Web Docs. Redirecting requests example in Using the webRequest API. MDN contributors. (n.d.). webRequest.filterResponseData(). MDN Web Docs. Examples: rewriting the response body. ↩
-
Mock Service Worker contributors. (n.d.). Interceptors. GitHub. Mocking responses: request events and the response controller. ↩
-
Nock contributors. (n.d.). Nock. GitHub. Usage: defining expected HTTP requests and supplying responses. ↩