
Security News
MCP Community Begins Work on Official MCP Metaregistry
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
node-request-interceptor
Advanced tools
Low-level HTTP/HTTPS/XHR request interception library for NodeJS
The node-request-interceptor package allows you to intercept and modify HTTP requests in Node.js. This can be useful for testing, mocking APIs, or modifying requests on the fly.
Intercepting HTTP Requests
This feature allows you to intercept HTTP requests made by the Node.js http module. You can log, modify, or mock these requests.
const { interceptClientRequest } = require('node-request-interceptor');
const interceptor = interceptClientRequest();
interceptor.use((req) => {
console.log('Intercepted request:', req);
return req;
});
// Example HTTP request
const http = require('http');
http.get('http://example.com', (res) => {
res.on('data', (chunk) => {
console.log('Response:', chunk.toString());
});
});
Mocking HTTP Responses
This feature allows you to mock HTTP responses based on the request URL or other criteria. This is useful for testing purposes.
const { interceptClientRequest } = require('node-request-interceptor');
const interceptor = interceptClientRequest();
interceptor.use((req) => {
if (req.url === 'http://example.com') {
return {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Mocked response' })
};
}
return req;
});
// Example HTTP request
const http = require('http');
http.get('http://example.com', (res) => {
res.on('data', (chunk) => {
console.log('Response:', chunk.toString());
});
});
Nock is a popular HTTP mocking and expectations library for Node.js. It allows you to intercept HTTP requests and mock responses, similar to node-request-interceptor. Nock provides a more extensive API for setting up expectations and is widely used in the Node.js community.
Mitm is a library for intercepting and mocking HTTP and HTTPS requests in Node.js. It provides a simple API for intercepting requests and modifying responses. Mitm is similar to node-request-interceptor but focuses more on simplicity and ease of use.
Fetch-mock is a library for mocking HTTP requests made using the Fetch API. While it is primarily designed for use in browser environments, it can also be used in Node.js with the help of a Fetch polyfill. Fetch-mock provides a flexible API for setting up mock responses and is useful for testing code that relies on the Fetch API.
node-request-interceptor
Low-level HTTP/HTTPS/XHR request interception library for NodeJS.
Intercepts any requests issued by:
http.get
/http.request
https.get
/https.request
fetch
XMLHttpRequest
request
, node-fetch
, etc.)While there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, exposing 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 in NodeJS. It's primarily designed as an underlying component for a high-level API mocking solutions.
As interception is often combined with request route matching, some libraries can determine whether a request should be mocked before it actually happens. This approach is not suitable for this library, as it rather intercepts all requests and then let's you decide which ones should be mocked. This affects the level at which interception happens, and also the way mocked/original response is constructed, in comparison to other solutions.
Although NodeJS has no XMLHttpRequest
implementation, this library covers it for the sake of processes that still run in NodeJS, but emulate a browser-like environment (i.e. jsdom
when running tests in Jest).
This library monkey-patches the following native modules:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
Once patched, it provides an interface to execute an arbitrary logic upon any outgoing request using a request middleware function.
jsdom
).npm install node-request-interceptor
RequestInterceptor(interceptors: Interceptor[])
import { RequestInterceptor } from 'node-request-interceptor'
import withDefaultInterceptors from 'node-request-interceptor/presets/default'
const interceptor = new RequestInterceptor(withDefaultInterceptors)
Using the
/presets/default
interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin.
This library utilizes a concept of an interceptor–a module that performs necessary patching, handles a mocked response, and restores patched instances.
The list of interceptors:
/interceptors/ClientRequest
/interceptors/XMLHttpRequest
To use one, or multiple interceptors, import and provide them to the RequestInterceptor
constructor.
import { RequestInterceptors } from 'node-request-interceptor'
import { interceptXMLHttpRequest } from 'node-request-interceptor/interceptors/XMLHttpRequest'
// This `interceptor` instance would handle only XMLHttpRequest,
// ignoring requests issued via `http`/`https` modules.
const interceptor = new RequestInterceptors([interceptXMLHttpRequest])
Interceptors are crucial in leveraging environment-specific module overrides. Certain environments (i.e. React Native) do not have access to native NodeJS modules (like
http
). Importing such modules raises an exception, and must be avoided.
.use(middleware: (req: InterceptedRequest, ref: IncomingMessage | XMLHttpRequest) => MockedResponse): void
Applies a given middleware function to an intercepted request. May return a MockedResponse
object that is going to be used to respond to an intercepted request.
interceptor.use((req) => {
// Will print to stdout any outgoing requests
// without affecting their responses
console.log('%s %s', req.method, req.url.href)
})
When a request middleware returns a MockedResponse
object, it will be returned as the response to the intercepted request. This library automatically creates a proper response instance according to the request issuing module (http
/XMLHttpRequest
).
interceptor.use((req) => {
if (['https://google.com'].includes(req.url.origin)) {
// Will return a mocked response for any request
// that is issued from the "https://google.com" origin.
return {
status: 301,
headers: {
'x-powered-by': 'node-request-interceptor',
},
body: JSON.stringify({
message: 'Hey, I am a mocked response',
}),
}
}
})
.restore(): void
Restores all patched modules and stops the interception of any future requests.
interceptor.restore()
InterceptedRequest
interface InterceptedRequest {
url: URL
method: string
headers?: http.OutgoingHttpHeaders
body?: string
}
MockedResponse
Whenever a MockedResponse
object is returned from the request middleware function, it's being used to constructs a relevant response for the intercepted request.
interface MockedResponse {
status?: number
statusText?: string
headers?: Record<string, string | string[]>
body?: string
}
The following libraries were used as an inspiration to write this low-level API:
FAQs
Low-level HTTP/HTTPS/XHR request interception library for NodeJS
We found that node-request-interceptor demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Research
Security News
Socket uncovers an npm Trojan stealing crypto wallets and BullX credentials via obfuscated code and Telegram exfiltration.
Research
Security News
Malicious npm packages posing as developer tools target macOS Cursor IDE users, stealing credentials and modifying files to gain persistent backdoor access.