hijackresponse
raw JSON → 5.0.0 verified Fri May 01 auth: no javascript
Module for hijacking and rewriting HTTP response bodies in middleware stacks. Version 5.0.0 requires Node >=8.0.0. It is a spiritual successor to express-hijackresponse, with no direct coupling to Express and support for streams2. Main use cases are content filtering, inline script injection, and transpiler/preprocessor middleware (e.g., express-processimage, express-autoprefixer). It provides fine-grained control over response interception via a promise-based API.
Common errors
error TypeError: res._implicitHeader is not a function ↓
cause Node's HTTP response methods being called after hijack but before piping.
fix
Ensure you set headers (via setHeader) only after the hijack promise resolves, and avoid direct res.write/end – always use the writable stream.
error Error [ERR_STREAM_WRITE_AFTER_END]: write after end ↓
cause Writing to res after hijack has ended the writable stream or after pipe completed.
fix
Do not write to res directly after hijacking; write to the writable stream only.
Warnings
gotcha If you forget to pipe the readable to writable, the response will hang and never send. ↓
fix Always call readable.pipe(writable) (possibly through a transform) in the hijack callback, or use destroyAndRestore() to restore original behavior.
gotcha The hijacked response's Content-Length header must be removed explicitly when modifying the body, otherwise the browser may wait for expected bytes. ↓
fix Call res.removeHeader('Content-Length') before piping through a transform stream.
gotcha Do not call next() before awaiting hijackResponse resolution; otherwise the next middleware may write to the original response before hijack takes effect. ↓
fix Pass next as the second argument to hijackResponse, or await the promise before calling next.
Install
npm install hijackresponse yarn add hijackresponse pnpm add hijackresponse Imports
- hijackResponse wrong
const hijackResponse = require('hijackresponse')correctimport hijackResponse from 'hijackresponse'
Quickstart
import express from 'express';
import hijackResponse from 'hijackresponse';
const app = express();
app.use((req, res, next) => {
hijackResponse(res, next).then(({ readable, writable, destroyAndRestore }) => {
// Don't hijack HTML responses:
if (/^text\/html/.test(res.getHeader('Content-Type'))) {
return readable.pipe(writable);
}
res.setHeader('X-Hijacked', 'yes!');
res.removeHeader('Content-Length');
// Example: transform to uppercase (replace with your transform stream)
const transformStream = new (require('stream').Transform)({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
}
});
readable.pipe(transformStream).pipe(writable);
});
});
app.get('/', (req, res) => {
res.send('hello world');
});
app.listen(3000);