Gathering detailed insights and metrics for @avivasyuta/request-interceptor
Gathering detailed insights and metrics for @avivasyuta/request-interceptor
Gathering detailed insights and metrics for @avivasyuta/request-interceptor
Gathering detailed insights and metrics for @avivasyuta/request-interceptor
Low-level network interception library.
npm install @avivasyuta/request-interceptor
Typescript
Module System
Min. Node Version
Node Version
NPM Version
73.8
Supply Chain
98.1
Quality
75.4
Maintenance
100
Vulnerability
100
License
TypeScript (98.45%)
JavaScript (1.55%)
Total Downloads
2,897
Last Day
4
Last Week
5
Last Month
20
Last Year
1,657
MIT License
603 Stars
753 Commits
140 Forks
7 Watchers
26 Branches
67 Contributors
Updated on May 02, 2025
Minified
Minified + Gzipped
Latest Version
0.1.3
Package Id
@avivasyuta/request-interceptor@0.1.3
Unpacked Size
543.50 kB
Size
119.45 kB
File Count
129
NPM Version
9.5.1
Node Version
18.16.0
Published on
Aug 16, 2023
Cumulative downloads
Total Downloads
Last Day
300%
4
Compared to previous day
Last Week
66.7%
5
Compared to previous week
Last Month
-73.3%
20
Compared to previous month
Last Year
33.6%
1,657
Compared to previous year
7
37
@mswjs/interceptors
Low-level HTTP/HTTPS/XHR/fetch request interception library.
Intercepts any requests issued by:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
window.fetch
axios
, request
, node-fetch
, supertest
, etc.)While there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, giving you a high-level API that includes request matching, timeouts, retries, and so forth.
This library is a strip-to-bone 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 'http' 2 3function applyMock() { 4 // Store the original request module. 5 const originalHttpRequest = http.request 6 7 // Rewrite the request module entirely. 8 http.request = function (...args) { 9 // Decide whether to handle this request before 10 // the actual request happens. 11 if (shouldMock(args)) { 12 // If so, never create a request, respond to it 13 // using the mocked response from this blackbox. 14 return coerceToResponse.bind(this, mock) 15 } 16 17 // Otherwise, construct the original request 18 // and perform it as-is (receives the original response). 19 return originalHttpRequest(...args) 20 } 21}
This library deviates from such implementation and uses class extensions instead of module rewrites. Such deviation is necessary because, unlike other solutions that include request matching and can determine whether to mock requests before they actually happen, this library is not opinionated about the mocked/bypassed nature of the requests. Instead, it intercepts all requests and delegates the decision of mocking to the end consumer.
1class NodeClientRequest extends ClientRequest { 2 async end(...args) { 3 // Check if there's a mocked response for this request. 4 // You control this in the "resolver" function. 5 const mockedResponse = await resolver(request) 6 7 // If there is a mocked response, use it to respond to this 8 // request, finalizing it afterward as if it received that 9 // response from the actual server it connected to. 10 if (mockedResponse) { 11 this.respondWith(mockedResponse) 12 this.finish() 13 return 14 } 15 16 // Otherwise, perform the original "ClientRequest.prototype.end" call. 17 return super.end(...args) 18 } 19}
By extending the native modules, this library actually constructs requests as soon as they are constructed by the consumer. This enables all the request input validation and transformations done natively by Node.js—something that traditional solutions simply cannot do (they replace http.ClientRequest
entirely). The class extension allows to fully utilize Node.js internals instead of polyfilling them, which results in more resilient mocks.
This library extends (or patches, where applicable) the following native modules:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
fetch
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 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('reqest', ({ request, requestId }) => { 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.
Use the request.respondWith()
method to respond to a request with a mocked response:
1interceptor.on('request', ({ request, requestId }) => { 2 request.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 ({ request, requestId }) => { 4 await sleep(500) 5 request.respondWith(new Response(null, { status: 500 })) 6})
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 therequest.respondWith()
method and providing a mockedResponse
instance.
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})
The following libraries were used as an inspiration to write this low-level API:
No vulnerabilities found.
Reason
16 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 9/30 approved changesets -- score normalized to 3
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
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
10 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-04-28
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