The HttpRequestInterceptor intercepts all HTTP requests in Node.js. It exposes requests as Fetch API Request instances.
Observing Requests
Use the request event to inspect requests. To read the body, you must use request.clone().json() (or similar) to avoid consuming the stream.
Request Initiator
The initiator property tells you which client issued the request. To accurately identify the client (e.g., distinguishing fetch from http.ClientRequest), you should apply the corresponding client-level interceptor (like FetchInterceptor) alongside the HttpRequestInterceptor.
Modifying Requests
You can mutate headers on the request object within the listener. Note that the request representation is read-only for other properties; it is not intended as a full-scale proxy.
Mocking Responses
Use controller.respondWith(new Response(...)) to mock a response. This must be done within the same tick as the listener. For asynchronous side-effects, make the listener an async function and await them.
Mocking Errors
- Generic Network Error: Use
controller.respondWith(Response.error()). - Specific Error: Use
controller.errorWith(new Error('reason')) to provide a custom error reason.
import { HttpRequestInterceptor } from '@mswjs/interceptors/http'
const interceptor = new HttpRequestInterceptor()
interceptor.apply()
// Observing and Mocking
interceptor.on('request', async ({ request, controller }) => {
// 1. Observe
console.log(request.method, request.url)
// 2. Modify headers
request.headers.set('x-my-header', 'true')
// 3. Mock a response (async example)
await new Promise(resolve => setTimeout(resolve, 100))
controller.respondWith(new Response(JSON.stringify({ hello: 'world' }), { status: 200 }))
})
// Observing responses
interceptor.on('response', ({ response, responseType }) => {
// responseType is 'mock' if responded via controller, 'original' otherwise
console.log(responseType)
})