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-interceptVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
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; /* ... */ });`.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()`.