Most frontend apps get data from a backend through HTTP requests. This includes API responses in JSON or static assets like stylesheets and scripts. During development or testing, developers often need to check how the UI reacts to different responses, such as errors, empty lists, or large datasets.
Instead of changing the backend or setting up mock servers, it’s easier to override API responses in the browser or local environment. This lets you test frontend behavior without making changes to the backend.
This article covers what it means to load a different API response in frontend code, why it’s useful, and how to do it.
What Does It Mean to Load a Different API Response?
Loading a different API response means replacing the real response from a backend API with a version you control. This change only happens in your local browser or environment. The backend doesn’t know anything was altered.
In other words, you’re not rewriting backend code or making permanent frontend changes. Instead, you intercept the HTTP response and substitute it in real time. This helps test how the UI handles specific scenarios without touching the actual server.
Also Read: UI Testing: A Detailed Guide
Why Load a Different API Response in Frontend Code?
Overriding API responses helps both developers and testers simulate real-world scenarios that are otherwise hard to reproduce. This is useful when the backend isn’t fully ready, or when testing very specific edge cases.
Here are some real-world scenarios where overriding the API response becomes useful:
- Simulate a broken or down API: Replace a 200 OK response with a 500 Internal Server Error and observe whether the UI shows a fallback message.
- Change a user’s role in the response: If the API returns user roles and permissions, change the role to ‘admin’ and check how the dashboard renders.
- Empty states testing: Return an empty array from a list API to test how the app handles zero results.
- Response delay simulation: Add a delay to check for loading spinners or timeout handling.
- Security testing: Inject malicious-looking strings to test how the frontend handles them (like script tags or long inputs).
Read More: What is Mobile App Security Testing?
Methods to Override API Responses in Frontend Code
There are several ways to modify API responses without editing backend code:
1. Modify Fetch/XHR in Frontend Code
You can intercept HTTP requests during development by modifying how fetch or XMLHttpRequest works in the browser. This technique is called monkey-patching.
For example, this code overrides the native fetch function to return a custom mock response when the request URL includes /api/user.
const originalFetch = window.fetch; window.fetch = async (...args) => { const response = await originalFetch(...args); if (args[0].includes('/api/user')) { return new Response(JSON.stringify({ name: 'Mocked User', role: 'admin' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } return response; };
However, this method has its own limitations, such as:
- It only works in dev environments
- It doesn’t affect assets or non-JS frameworks
- It needs you to inject the override logic each time
Also Read: Front-End Testing Strategy: A Detailed Guide
2. Use Browser DevTools for Simple Overrides
Browsers like Chrome allow local overrides:
- Open DevTools > Network tab
- Right-click a request > Save for override
- Go to Sources > Enable Local Overrides
- Edit the response body
Chrome will now serve the edited version instead of the actual network response. This is handy for static files or basic JSON APIs.
However, it has limitations too, such as:
- No support for dynamic or encrypted payloads
- Overrides are local and can be reset when DevTools settings change
3. Use a Dedicated Tool Like Requestly
Requestly is a tool from BrowserStack that lets you intercept and modify HTTP requests and responses without touching your backend code. It works as both a browser extension and a desktop application.
Requestly supports features like:
- Modifying and mocking API responses: Change the body of API responses to test different frontend states.
- Blocking network requests: Stop or reroute specific requests to a different endpoint.
- Modifying HTTP headers: Inject custom headers or remove unnecessary ones for testing.
- Injecting custom scripts: Add JavaScript to a page without editing the source code.
How to Use Requestly to Modify API Responses
Use the Requestly desktop app to create response override rules that work with any browser and support HTTPS traffic. Follow these steps to apply a rule:
Step 1: Launch Requestly and Connect Your Browser
To begin, open the Requestly desktop app.
- In the sidebar, click Connect Apps
- Select the browser you want to use (Chrome, Edge, Firefox, etc.)
- The browser will open in a connected state, allowing Requestly to capture all network traffic
This connection enables real-time interception and modification of requests and responses.
Step 2: Trigger the API You Want to Modify
Now, visit the page or application where the target API call is made. For example, you might want to override a call to fetch user details or a preview snippet.
To capture the API request:
- Use the app as usual in the connected browser
- Let Requestly auto-log all network activity
- Look for the specific API endpoint (example: https://api.example.com/user/info)
Once you see the request in the Requestly interface, you’re ready to override it.
Step 3: Open the Modify Response Panel
Requestly allows you to override either with a fixed response or dynamic logic. Here’s how to open the modify response panel.
- Right-click the captured request
- Select Modify Response Body
You’ll be prompted to choose between Static Override and Programmatic Override
Step 4: Use Static Override for Simple Mock Data
If you want to replace the entire response with a custom payload, use static override. This is helpful when you need to simulate a blank response, return a successful payload with fixed values, or test how the UI handles a response with certain fields missing.
To apply a static override:
- Choose Static Override
- Paste a mock JSON body such as:
{ "id": "mock-456", "name": "Test User", "status": "inactive", "roles": [] }
- Click Create Rule to save it.
Anytime this API is called, the frontend will receive this mocked response.
Step 5: Use Programmatic Override for Dynamic Changes
If the response needs to vary based on logic or partial edits, choose programmatic override. This method lets you inspect or transform the original response before the browser sees it. It’s ideal when you want to inject new fields into the payload, replace existing values conditionally, or filter out parts of the data based on specific rules.
To apply a programmatic override:
- Select Programmatic Override
- Write a JavaScript function like this:
module.exports = function overrideResponseBody(body) { const json = JSON.parse(body); json.status = 'admin-override'; json.features = ['mocked-feature']; return JSON.stringify(json); };
- Save the rule to apply it.
You now have complete control over the structure and content of the modified response.
Challenges When Overriding Frontend API Responses
Overriding API responses is useful but comes with a few common challenges. Here’s what to watch out for and how to deal with them:
- URL matching must be exact: Overrides won’t apply if the request URL has dynamic paths or query parameters. Where supported, you can use wildcards or regex patterns to match variable parts of the URL.
- CORS errors are common: Modifying headers or responses can cause cross-origin issues in the browser. You can avoid this by not altering CORS headers directly or using a tool like the Requestly desktop app, which handles it correctly.
Read More: What is CORS, and How to Bypass It?
- HTTPS traffic needs special handling: Browsers block unauthorized interception of secure responses. You can resolve this by installing a trusted certificate through the Requestly desktop app, which allows safe HTTPS interception.
- Signed or encrypted responses break easily: JWTs or other signed payloads fail if modified. You can avoid breaking these by excluding sensitive tokens from overrides or mocking only parts of the payload that don’t affect validation.
- Hard to maintain mock rules: As backend APIs change, old override rules may cause mismatches or errors. You can manage this by versioning and updating your override rules alongside your API contract.
Conclusion
Overriding API responses in the frontend is a practical technique for testing UI behavior, handling edge cases, and working independently of backend dependencies. It helps simulate various states like errors, delays, or incomplete data without needing backend changes.
Requestly provides a structured and reliable way to override these responses. With both a browser extension and a powerful desktop app, it supports modifying request and response bodies, even for HTTPS traffic. It removes the need for complex setups or patching code, letting teams test and debug faster, with full control over the data returned to the frontend.