The fetch API is widely used in modern web applications to make HTTP requests. Intercepting these requests can be invaluable for debugging, monitoring network activity, or testing API behavior. This article provides a JavaScript snippet to override the fetch method and log all request and response details to the console.
The Code
Here’s a snippet to intercept and log fetch requests and responses:
(function () {
const originalFetch = window.fetch;
window.fetch = async function (input, init) {
const method = (init && init.method) || 'GET';
const url = input instanceof Request ? input.url : input;
console.log(`[Fetch Intercepted] Request: ${method} ${url}`);
if (init && init.body) {
console.log(`[Fetch Intercepted] Request Body:`, init.body);
}
try {
const response = await originalFetch(input, init);
// Clone the response to read it without affecting the original stream
const clonedResponse = response.clone();
clonedResponse.text().then((text) => {
console.log(`[Fetch Intercepted] Response for ${method} ${url}:`, text);
});
return response; // Return the original response to maintain functionality
} catch (error) {
console.error(`[Fetch Intercepted] Error for ${method} ${url}:`, error);
throw error; // Re-throw the error to maintain original behavior
}
};
})();
How It Works
- Override fetch:
The native fetch function is wrapped with custom logic to intercept and log details about requests and responses. - Log Request Details:
The HTTP method and URL are logged. If a body is included in the request (e.g., for POST/PUT), it’s also logged. - Log Responses:
The response.clone() method is used to read and log the response body without disrupting the original response. - Handle Errors:
Any errors during the request are logged, and the error is re-thrown to ensure the application behaves as expected.
Use Cases
- Debugging: Understand the data being sent to and received from the server.
- Testing APIs: Validate payloads and responses without needing third-party tools like Postman or browser extensions.
- Learning: A useful technique for developers to explore how modern applications communicate with servers.
Precautions
- Performance Impact: Logging large payloads or high volumes of requests may affect application performance.
- Read-Only: This snippet logs data without modifying it. If you need to modify requests or responses, additional logic is required.
How to Use
- Copy the code and paste it into the browser’s developer console or inject it into a script on the page.
- Make fetch requests as usual. The logs will display details of each request and response in the console.
Leave a Reply
You must be logged in to post a comment.