Registry / web-framework / express-intercept

express-intercept

JSON →
library1.1.1jsnpmunverified

express-intercept is a lightweight Express.js middleware library providing a fluent API for intercepting, inspecting, replacing, and transforming HTTP responses and requests. It simplifies complex tasks like modifying response bodies, logging sensitive request/response data, or dynamically altering content types. The current stable version, 1.1.1, demonstrates active maintenance, though a formal release cadence is not specified. A key differentiator is its robust handling of chunked and compressed responses, automatically decompressing and recompressing as needed, allowing developers to work with response bodies as strings, buffers, or streams without manual stream manipulation for these complexities. It offers conditional execution of interceptors via `for()` and `if()` methods, enabling targeted and efficient middleware application.

npm install express-intercept
INSTALL
IMPORT
SIG · EXPRESS-INTERCEPT
E
express-intercept
web-frameworkjavascriptv1.1.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

responseHandler
✓ import { responseHandler } from 'express-intercept';
✗ const responseHandler = require('express-intercept').responseHandler;
The library primarily uses named exports and is designed for ESM. While CommonJS might work with specific transpilation, ESM is the intended usage.
requestHandler
✓ import { requestHandler } from 'express-intercept';
✗ const { requestHandler } = require('express-intercept');
Similar to `responseHandler`, `requestHandler` is a named export, with ESM imports being the standard.
requestHandler, responseHandler (TypeScript types)
✓ import type { RequestHandlerBuilder, ResponseHandlerBuilder } from 'express-intercept';
✗ import { RequestHandlerBuilder, ResponseHandlerBuilder } from 'express-intercept';
When only importing types, use `import type` to ensure they are stripped from the JavaScript output, preventing potential runtime errors or unnecessary imports.

This quickstart demonstrates how to use `express-intercept` to replace content in HTML responses, log specific data from JSON login responses, and save the full body of 500-level error responses to a file, showcasing conditional interception and various body handling methods.

import express from "express"; import { requestHandler, responseHandler } from "express-intercept"; import fs from "fs/promises"; // For writeFile example const app = express(); const port = 3000; // Example 1: Replace response string if Content-Type is HTML. app.use(responseHandler() .if(res => /html/i.test(String(res.getHeader("content-type")))) .replaceString(body => body.replace(/MacBook/g, "Surface"))); // Example 2: Log access_token for /login path if response is JSON. app.use(responseHandler() .for(req => (req.path === "/login")) .if(res => /json/i.test(String(res.getHeader("content-type")))) .getString(body => { try { console.warn("Logged access_token:", JSON.parse(body).access_token); } catch (e) { console.error("Failed to parse JSON for /login:", e); } })); // Example 3: Dump 500 Internal Server Error response body to a file. app.use(responseHandler() .if(res => (+res.statusCode === 500)) .getBuffer(async body => { try { await fs.writeFile("debug_error_response.log", body); console.warn("Dumped 500 error response to debug_error_response.log"); } catch (e) { console.error("Failed to write error response:", e); } })); // Simple routes for demonstration app.get("/", (req, res) => { res.setHeader("Content-Type", "text/html"); res.send("<h1>Welcome to the MacBook Store!</h1><p>Visit our new MacBook Pro section.</p>"); }); app.post("/login", express.json(), (req, res) => { // Simulate a login response with an access token res.json({ message: "Login successful", access_token: "fake-jwt-token-12345" }); }); app.get("/error", (req, res) => { res.status(500).send("Something went wrong on the server."); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); console.log("Try: "); console.log(`- GET http://localhost:${port}/ (Check console for Surface replacement)`); console.log(`- POST http://localhost:${port}/login (Check console for access_token log)`); console.log(`- GET http://localhost:${port}/error (Check for debug_error_response.log file)`); });
Debug
Known issues
gotchaThe order of middleware in Express is crucial. Place `express-intercept` middleware carefully, typically before other middleware that might send a response or modify headers in a way that conflicts with interception (e.g., compression middleware might need to be after, depending on the desired interception point).
fix
Experiment with middleware ordering. Generally, place `express-intercept` early in the chain if you want to modify responses before other transformations, or later if you want to inspect/modify the final output.
affects: >=1.0.0
gotchaIntercepting and buffering large response bodies, especially for `replaceString`, `replaceBuffer`, `getString`, or `getBuffer`, can consume significant memory and CPU resources. This can impact application performance and scalability.
fix
Use conditional interception (`.for()`, `.if()`) to target only necessary responses. For very large responses or streaming transformations, prefer `interceptStream()` to process data as it flows, avoiding full buffering in memory.
affects: >=1.0.0
gotchaAttempting to send headers or response data directly using `res.send()`, `res.json()`, `res.end()` etc., *before* `express-intercept` has had a chance to intercept the response stream, can lead to 'Headers already sent' errors or unpredictable behavior.
fix
Ensure `express-intercept` middleware is placed such that it wraps the actual route handler or other middleware that generates the response. The library works by replacing the standard `res.write` and `res.end` methods, which only works if they haven't been called yet by upstream middleware.
affects: >=1.0.0
Errors
Common errors & fixes
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\path\to\node_modules\express-intercept\index.js from C:\path\to\your\app.js not supported.
`express-intercept` is primarily an ES Module (ESM) package. Trying to import it using CommonJS `require()` syntax in a CommonJS project will fail.
fix
Migrate your project to use ES Modules (by setting `"type": "module"` in `package.json` and using `import` statements) or use a dynamic `import()` call: `import('express-intercept').then(lib => { const { requestHandler } = lib; /* ... */ });`.
Error: Can't set headers after they are sent.
This error typically occurs when an Express application attempts to modify response headers or send data after the response has already been committed (headers sent, or body started). In the context of `express-intercept`, this might happen if other middleware or the route handler implicitly sends headers before `express-intercept` can take control, or if an interceptor itself tries to directly send a response instead of using the provided replacement methods.
fix
Review the order of your Express middleware. Ensure `express-intercept` is placed appropriately to intercept the response before other middleware might finalize it. Within interceptors, always use the methods provided by `express-intercept` (`replaceString`, `interceptStream`, etc.) to modify the response body, rather than directly calling `res.send()` or `res.end()`.
Upgrade
Version history
1.1.1latest on npm
Audit
Dependencies
expressrequiredThis package is an Express.js middleware and requires Express to function.
Agent activity
22 hits · last 30 days
node
18
OpenAI (training)
2
Resources
express-intercept — npm install express-intercept · libregistry