{"id":13167,"library":"express-intercept","title":"Express Intercept Middleware","description":"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.","status":"active","version":"1.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/kawanet/express-intercept","tags":["javascript","expressjs","inspector","interceptor","middleware","modify","response","tamper","typescript"],"install":[{"cmd":"npm install express-intercept","lang":"bash","label":"npm"},{"cmd":"yarn add express-intercept","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-intercept","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is an Express.js middleware and requires Express to function.","package":"express","optional":false}],"imports":[{"note":"The library primarily uses named exports and is designed for ESM. While CommonJS might work with specific transpilation, ESM is the intended usage.","wrong":"const responseHandler = require('express-intercept').responseHandler;","symbol":"responseHandler","correct":"import { responseHandler } from 'express-intercept';"},{"note":"Similar to `responseHandler`, `requestHandler` is a named export, with ESM imports being the standard.","wrong":"const { requestHandler } = require('express-intercept');","symbol":"requestHandler","correct":"import { requestHandler } from 'express-intercept';"},{"note":"When only importing types, use `import type` to ensure they are stripped from the JavaScript output, preventing potential runtime errors or unnecessary imports.","wrong":"import { RequestHandlerBuilder, ResponseHandlerBuilder } from 'express-intercept';","symbol":"requestHandler, responseHandler (TypeScript types)","correct":"import type { RequestHandlerBuilder, ResponseHandlerBuilder } from 'express-intercept';"}],"quickstart":{"code":"import express from \"express\";\nimport { requestHandler, responseHandler } from \"express-intercept\";\nimport fs from \"fs/promises\"; // For writeFile example\n\nconst app = express();\nconst port = 3000;\n\n// Example 1: Replace response string if Content-Type is HTML.\napp.use(responseHandler()\n  .if(res => /html/i.test(String(res.getHeader(\"content-type\"))))\n  .replaceString(body => body.replace(/MacBook/g, \"Surface\")));\n\n// Example 2: Log access_token for /login path if response is JSON.\napp.use(responseHandler()\n  .for(req => (req.path === \"/login\"))\n  .if(res => /json/i.test(String(res.getHeader(\"content-type\"))))\n  .getString(body => {\n    try {\n      console.warn(\"Logged access_token:\", JSON.parse(body).access_token);\n    } catch (e) {\n      console.error(\"Failed to parse JSON for /login:\", e);\n    }\n  }));\n\n// Example 3: Dump 500 Internal Server Error response body to a file.\napp.use(responseHandler()\n  .if(res => (+res.statusCode === 500))\n  .getBuffer(async body => {\n    try {\n      await fs.writeFile(\"debug_error_response.log\", body);\n      console.warn(\"Dumped 500 error response to debug_error_response.log\");\n    } catch (e) {\n      console.error(\"Failed to write error response:\", e);\n    }\n  }));\n\n// Simple routes for demonstration\napp.get(\"/\", (req, res) => {\n  res.setHeader(\"Content-Type\", \"text/html\");\n  res.send(\"<h1>Welcome to the MacBook Store!</h1><p>Visit our new MacBook Pro section.</p>\");\n});\n\napp.post(\"/login\", express.json(), (req, res) => {\n  // Simulate a login response with an access token\n  res.json({ message: \"Login successful\", access_token: \"fake-jwt-token-12345\" });\n});\n\napp.get(\"/error\", (req, res) => {\n  res.status(500).send(\"Something went wrong on the server.\");\n});\n\napp.listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n  console.log(\"Try: \");\n  console.log(`- GET http://localhost:${port}/ (Check console for Surface replacement)`);\n  console.log(`- POST http://localhost:${port}/login (Check console for access_token log)`);\n  console.log(`- GET http://localhost:${port}/error (Check for debug_error_response.log file)`);\n});","lang":"typescript","description":"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."},"warnings":[{"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.","message":"The 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).","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Intercepting 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Attempting 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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; /* ... */ });`.","cause":"`express-intercept` is primarily an ES Module (ESM) package. Trying to import it using CommonJS `require()` syntax in a CommonJS project will fail.","error":"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."},{"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()`.","cause":"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.","error":"Error: Can't set headers after they are sent."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}