Gathering detailed insights and metrics for @mswjs/interceptors
Gathering detailed insights and metrics for @mswjs/interceptors
Gathering detailed insights and metrics for @mswjs/interceptors
Gathering detailed insights and metrics for @mswjs/interceptors
onfetch
Mock fetch() with native Request / Response API. Works with globalThis, service worker, @mswjs/interceptors, and custom contexts
msw
Seamless REST/GraphQL API mocking library for browser and Node.js.
@mswjs/cookies
Manage request/response cookies in the environments where those are not supported.
@avivasyuta/request-interceptor
Low-level HTTP/HTTPS/XHR/fetch request interception library. Fork of @mswjs/interceptors.
Low-level network interception library.
npm install @mswjs/interceptors
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
569 Stars
723 Commits
127 Forks
8 Watching
22 Branches
64 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (98.39%)
JavaScript (1.61%)
Cumulative downloads
Total Downloads
Last day
-6.6%
729,806
Compared to previous day
Last week
3.5%
4,057,389
Compared to previous week
Last month
10.4%
16,948,947
Compared to previous month
Last year
50.5%
151,700,327
Compared to previous year
6
48
@mswjs/interceptors
Low-level network interception library.
This library supports intercepting the following protocols:
http
module, XMLHttpRequest
, or globalThis.fetch
);WebSocket
class in Undici and in the browser).While there are a lot of network mocking libraries, they tend to use request interception as an implementation detail, giving you a high-level API that includes request matching, timeouts, recording, and so forth.
This library is a barebones implementation that provides as little abstraction as possible to execute arbitrary logic upon any request. It's primarily designed as an underlying component for high-level API mocking solutions such as Mock Service Worker.
A traditional API mocking implementation in Node.js looks roughly like this:
1import http from 'node:http' 2 3// Store the original request function. 4const originalHttpRequest = http.request 5 6// Override the request function entirely. 7http.request = function (...args) { 8 // Decide if the outgoing request matches a predicate. 9 if (predicate(args)) { 10 // If it does, never create a request, respond to it 11 // using the mocked response from this blackbox. 12 return coerceToResponse.bind(this, mock) 13 } 14 15 // Otherwise, construct the original request 16 // and perform it as-is. 17 return originalHttpRequest(...args) 18}
The core philosophy of Interceptors is to run as much of the underlying network code as possible. Strange for a network mocking library, isn't it? Turns out, respecting the system's integrity and executing more of the network code leads to more resilient tests and also helps to uncover bugs in the code that would otherwise go unnoticed.
Interceptors heavily rely on class extension instead of function and module overrides. By extending the native network code, it can surgically insert the interception and mocking pieces only where necessary, leaving the rest of the system intact.
1class XMLHttpRequestProxy extends XMLHttpRequest { 2 async send() { 3 // Call the request listeners and see if any of them 4 // returns a mocked response for this request. 5 const mockedResponse = await waitForRequestListeners({ request }) 6 7 // If there is a mocked response, use it. This actually 8 // transitions the XMLHttpRequest instance into the correct 9 // response state (below is a simplified illustration). 10 if (mockedResponse) { 11 // Handle the response headers. 12 this.request.status = mockedResponse.status 13 this.request.statusText = mockedResponse.statusText 14 this.request.responseUrl = mockedResponse.url 15 this.readyState = 2 16 this.trigger('readystatechange') 17 18 // Start streaming the response body. 19 this.trigger('loadstart') 20 this.readyState = 3 21 this.trigger('readystatechange') 22 await streamResponseBody(mockedResponse) 23 24 // Finish the response. 25 this.trigger('load') 26 this.trigger('loadend') 27 this.readyState = 4 28 return 29 } 30 31 // Otherwise, perform the original "XMLHttpRequest.prototype.send" call. 32 return super.send(...args) 33 } 34}
The request interception algorithms differ dramatically based on the request API. Interceptors acommodate for them all, bringing the intercepted requests to a common ground—the Fetch API
Request
instance. The same applies for responses, where a Fetch APIResponse
instance is translated to the appropriate response format.
This library aims to provide full specification compliance with the APIs and protocols it extends.
This library extends the following native modules:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
fetch
WebSocket
Once extended, it intercepts and normalizes all requests to the Fetch API Request
instances. This way, no matter the request source (http.ClientRequest
, XMLHttpRequest
, window.Request
, etc), you always get a specification-compliant request instance to work with.
You can respond to the intercepted HTTP request by constructing a Fetch API Response instance. Instead of designing custom abstractions, this library respects the Fetch API specification and takes the responsibility to coerce a single response declaration to the appropriate response formats based on the request-issuing modules (like http.OutgoingMessage
to respond to http.ClientRequest
, or updating XMLHttpRequest
response-related properties).
1npm install @mswjs/interceptors
To use this library you need to choose one or multiple interceptors to apply. There are different interceptors exported by this library to spy on respective request-issuing modules:
ClientRequestInterceptor
to spy on http.ClientRequest
(http.get
/http.request
);XMLHttpRequestInterceptor
to spy on XMLHttpRequest
;FetchInterceptor
to spy on fetch
.Use an interceptor by constructing it and attaching request/response listeners:
1import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' 2 3const interceptor = new ClientRequestInterceptor() 4 5// Enable the interception of requests. 6interceptor.apply() 7 8// Listen to any "http.ClientRequest" being dispatched, 9// and log its method and full URL. 10interceptor.on('request', ({ request, requestId }) => { 11 console.log(request.method, request.url) 12}) 13 14// Listen to any responses sent to "http.ClientRequest". 15// Note that this listener is read-only and cannot affect responses. 16interceptor.on( 17 'response', 18 ({ response, isMockedResponse, request, requestId }) => { 19 console.log('response to %s %s was:', request.method, request.url, response) 20 } 21)
All HTTP request interceptors implement the same events:
request
, emitted whenever a request has been dispatched;response
, emitted whenever any request receives a response.You can combine multiple interceptors to capture requests from different request-issuing modules at once.
1import { BatchInterceptor } from '@mswjs/interceptors' 2import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' 3import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest' 4 5const interceptor = new BatchInterceptor({ 6 name: 'my-interceptor', 7 interceptors: [ 8 new ClientRequestInterceptor(), 9 new XMLHttpRequestInterceptor(), 10 ], 11}) 12 13interceptor.apply() 14 15// This "request" listener will be called on both 16// "http.ClientRequest" and "XMLHttpRequest" being dispatched. 17interceptor.on('request', listener)
Note that you can use pre-defined presets that cover all the request sources for a given environment type.
When using BatchInterceptor
, you can provide a pre-defined preset to its "interceptors" option to capture all request for that environment.
This preset combines ClientRequestInterceptor
, XMLHttpRequestInterceptor
and is meant to be used in Node.js.
1import { BatchInterceptor } from '@mswjs/interceptors' 2import nodeInterceptors from '@mswjs/interceptors/presets/node' 3 4const interceptor = new BatchInterceptor({ 5 name: 'my-interceptor', 6 interceptors: nodeInterceptors, 7}) 8 9interceptor.apply() 10 11interceptor.on('request', listener)
This preset combines XMLHttpRequestInterceptor
and FetchInterceptor
and is meant to be used in a browser.
1import { BatchInterceptor } from '@mswjs/interceptors' 2import browserInterceptors from '@mswjs/interceptors/presets/browser' 3 4const interceptor = new BatchInterceptor({ 5 name: 'my-interceptor', 6 interceptors: browserInterceptors, 7}) 8 9interceptor.on('request', listener)
All HTTP request interceptors emit a "request" event. In the listener to this event, they expose a request
reference, which is a Fetch API Request instance.
There are many ways to describe a request in Node.js but this library coerces different request definitions to a single specification-compliant
Request
instance to make the handling consistent.
1interceptor.on('request', ({ request, requestId, controller }) => { 2 console.log(request.method, request.url) 3})
Since the exposed request
instance implements the Fetch API specification, you can operate with it just as you do with the regular browser request. For example, this is how you would read the request body as JSON:
1interceptor.on('request', async ({ request, requestId }) => { 2 const json = await request.clone().json() 3})
Do not forget to clone the request before reading its body!
Request representations are readonly. You can, however, mutate the intercepted request's headers in the "request" listener:
1interceptor.on('request', ({ request }) => { 2 request.headers.set('X-My-Header', 'true') 3})
This restriction is done so that the library wouldn't have to unnecessarily synchronize the actual request instance and its Fetch API request representation. As of now, this library is not meant to be used as a full-scale proxy.
Although this library can be used purely for request introspection purposes, you can also affect request resolution by responding to any intercepted request within the "request" event.
Access the controller
object from the request event listener arguments and call its controller.respondWith()
method, providing it with a mocked Response
instance:
1interceptor.on('request', ({ request, controller }) => { 2 controller.respondWith( 3 new Response( 4 JSON.stringify({ 5 firstName: 'John', 6 lastName: 'Maverick', 7 }), 8 { 9 status: 201, 10 statusText: 'Created', 11 headers: { 12 'Content-Type': 'application/json', 13 }, 14 } 15 ) 16 ) 17})
We use Fetch API
Response
class as the middle-ground for mocked response definition. This library then coerces the response instance to the appropriate response format (e.g. tohttp.OutgoingMessage
in the case ofhttp.ClientRequest
).
The Response
class is built-in in since Node.js 18. Use a Fetch API-compatible polyfill, like node-fetch
, for older versions of Node.js.`
Note that a single request can only be handled once. You may want to introduce conditional logic, like routing, in your request listener but it's generally advised to use a higher-level library like Mock Service Worker that does request matching for you.
Requests must be responded to within the same tick as the request listener. This means you cannot respond to a request using setTimeout
, as this will delegate the callback to the next tick. If you wish to introduce asynchronous side-effects in the listener, consider making it an async
function, awaiting any side-effects you need.
1// Respond to all requests with a 500 response 2// delayed by 500ms. 3interceptor.on('request', async ({ controller }) => { 4 await sleep(500) 5 controller.respondWith(new Response(null, { status: 500 })) 6})
You can provide an instance of Response.error()
to error the pending request.
1interceptor.on('request', ({ request, controller }) => { 2 controller.respondWith(Response.error()) 3})
This will automatically translate to the appropriate request error based on the request client that issued the request. Use this method to produce a generic network error.
Note that the standard
Response.error()
API does not accept an error message.
Use the controller.errorWith()
method to error the request.
1interceptor.on('request', ({ request, controller }) => { 2 controller.errorWith(new Error('reason')) 3})
Unlike responding with Response.error()
, you can provide an exact error reason to use to .errorWith()
. Use this method to error the request.
Note that it is up to the request client to respect your custom error. Some clients, like
ClientRequest
will use the provided error message, while others, likefetch
, will produce a genericTypeError: failed to fetch
responses. Interceptors will try to preserve the original error in thecause
property of such generic errors.
You can use the "response" event to transparently observe any incoming responses in your Node.js process.
1interceptor.on( 2 'response', 3 ({ response, isMockedResponse, request, requestId }) => { 4 // react to the incoming response... 5 } 6)
Note that the
isMockedResponse
property will only be set totrue
if you resolved this request in the "request" event listener using thecontroller.respondWith()
method and providing a mockedResponse
instance.
By default, all unhandled exceptions thrown within the request
listener are coerced to 500 error responses, emulating those exceptions occurring on the actual server. You can listen to the exceptions by adding the unhandledException
listener to the interceptor:
1interceptor.on( 2 'unhandledException', 3 ({ error, request, requestId, controller }) => { 4 console.log(error) 5 } 6)
To opt out from the default coercion of unhandled exceptions to server responses, you need to either:
unhandledException
listener.Here's an example of propagating the unhandled exception up:
1interceptor.on('unhandledException', ({ error }) => { 2 // Now, any unhandled exception will NOT be coerced to a 500 error response, 3 // and instead will be thrown during the process execution as-is. 4 throw error 5})
You can intercept a WebSocket communication using the WebSocketInterceptor
class.
[!IMPORTANT] This library only supports intercepting WebSocket connections created using the global WHATWG
WebSocket
class. Third-party transports, such as HTTP/XHR polling, are not supported by design due to their contrived nature.
1import { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket' 2 3const interceptor = new WebSocketInterceptor()
Unlike the HTTP-based interceptors that share the same request
/response
events, the WebSocket interceptor only emits the connection
event and let's you handle the incoming/outgoing events in its listener.
server.connect()
in the interceptor.event.preventDefault()
for that client message event.event.preventDefault()
for the server message event.close
event received from that server is forwarded to the client by default. If you wish to prevent that, call event.preventDefault()
for that close event of the server.Whenever a WebSocket instance is constructed, the connection
event is emitted on the WebSocket interceptor.
1intereceptor.on('connection', ({ client }) => { 2 console.log(client.url) 3})
The connection
event exposes the following arguments:
Name | Type | Description |
---|---|---|
client | WebSocketClientConnection | An object representing a connected WebSocket client instance. |
server | WebSocketServerConnection | An object representing the original WebSocket server connection. |
info | object | Additional WebSocket connection information (like the original client protocols ). |
WebSocketClientConnection
.addEventListener(type, listener)
type
, string
listener
, EventListener
Adds an event listener to the given event type of the WebSocket client.
1interface WebSocketServerConnectionEventMap { 2 // Dispatched when the WebSocket client sends data. 3 message: (this: WebSocket, event: MessageEvent<WebSocketData>) => void 4 5 // Dispatched when the WebSocket client is closed. 6 close: (this: WebSocket, event: CloseEvent) => void 7}
1client.addEventListener('message', (event) => { 2 console.log('outgoing:', event.data) 3})
.removeEventListener(type, listener)
type
, string
listener
, EventListener
Removes the listener for the given event type.
.send(data)
data
, string | Blob | ArrayBuffer
Sends the data to the intercepted WebSocket client.
1client.send('text') 2client.send(new Blob(['blob'])) 3client.send(new TextEncoder().encode('array buffer'))
.close(code, reason)
code
, close status code.reason
, close reason.Closes the client connection. Unlike the regular WebSocket.prototype.close()
, the client.close()
method can accept a non-configurable status codes, such as 1001, 1003, etc.
1// Gracefully close the connection with the 2// intercepted WebSocket client. 3client.close()
1// Terminate the connection by emulating 2// the server unable to process the received data. 3client.close(1003)
WebSocketServerConnection
.connect()
Establishes the connection to the original WebSocket server. Connection cannot be awaited. Any data sent via server.send()
while connecting is buffered and flushed once the connection is open.
.addEventListener(type, listener)
type
, string
listener
, EventListener
Adds an event listener to the given event type of the WebSocket server.
1interface WebSocketServerConnectionEventMap { 2 // Dispatched when the server connection is open. 3 open: (this: WebSocket, event: Event) => void 4 5 // Dispatched when the server sends data to the client. 6 message: (this: WebSocket, event: MessageEvent<WebSocketData>) => void 7 8 // Dispatched when the server connection closes. 9 close: (this: WebSocket, event: CloseEvent) => void 10}
1server.addEventListener('message', (event) => { 2 console.log('incoming:', event.data) 3})
.removeEventListener(type, listener)
type
, string
listener
, EventListener
Removes the listener for the given event type.
.send(data)
data
, string | Blob | ArrayBuffer
Sends the data to the original WebSocket server. Useful in a combination with the client-sent events forwarding:
1client.addEventListener('message', (event) => { 2 server.send(event.data) 3})
.close()
Closes the connection with the original WebSocket server. Unlike client.close()
, closing the server connection does not accept any arguments and always asumes a graceful closure. Sending data via server.send()
after the connection has been closed will have no effect.
Interceptor
A generic class implemented by all interceptors. You do not interact with this class directly.
1class Interceptor { 2 // Applies the interceptor, enabling the interception of requests 3 // in the current process. 4 apply(): void 5 6 // Listens to the public interceptor events. 7 // For HTTP requests, these are "request' and "response" events. 8 on(event, listener): void 9 10 // Cleans up any side-effects introduced by the interceptor 11 // and disables the interception of requests. 12 dispose(): void 13}
For public consumption, use interceptors instead.
BatchInterceptor
Applies multiple request interceptors at the same time.
1import { BatchInterceptor } from '@mswjs/interceptors' 2import nodeInterceptors from '@mswjs/interceptors/presets/node' 3 4const interceptor = new BatchInterceptor({ 5 name: 'my-interceptor', 6 interceptors: nodeInterceptors, 7}) 8 9interceptor.apply() 10 11interceptor.on('request', ({ request, requestId }) => { 12 // Inspect the intercepted "request". 13 // Optionally, return a mocked response. 14})
Using the
/presets/node
interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin.
RemoteHttpInterceptor
Enables request interception in the current process while delegating the response resolution logic to the parent process. Requires the current process to be a child process. Requires the parent process to establish a resolver by calling the createRemoteResolver
function.
1// child.js 2import { RemoteHttpInterceptor } from '@mswjs/interceptors/RemoteHttpInterceptor' 3import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' 4 5const interceptor = new RemoteHttpInterceptor({ 6 // Alternatively, you can use presets. 7 interceptors: [new ClientRequestInterceptor()], 8}) 9 10interceptor.apply() 11 12process.on('disconnect', () => { 13 interceptor.dispose() 14})
You can still listen to and handle any requests in the child process via the request
event listener. Keep in mind that a single request can only be responded to once.
RemoteHttpResolver
Resolves an intercepted request in the given child process
. Requires for that child process to enable request interception by calling the createRemoteInterceptor
function.
1// parent.js 2import { spawn } from 'child_process' 3import { RemoteHttpResolver } from '@mswjs/interceptors/RemoteHttpInterceptor' 4 5const appProcess = spawn('node', ['app.js'], { 6 stdio: ['inherit', 'inherit', 'inherit', 'ipc'], 7}) 8 9const resolver = new RemoteHttpResolver({ 10 process: appProcess, 11}) 12 13resolver.on('request', ({ request, requestId }) => { 14 // Optionally, return a mocked response 15 // for a request that occurred in the "appProcess". 16}) 17 18resolver.apply()
The following libraries were used as an inspiration to write this low-level API:
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 26 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 4/30 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
22 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More