JSON Response Transformation for node-http-proxy
node-http-proxy-json is a specialized library, currently at version 0.1.9, designed to intercept and transform JSON responses from a proxied server when used in conjunction with node-http-proxy. Its primary function is to allow developers to modify JSON payloads on the fly, making it suitable for scenarios like API mocking, data manipulation, or stripping sensitive information before the response reaches the client. The library handles responses compressed with `gzip` or `deflate`, as well as uncompressed data. Unlike general-purpose stream manipulation tools such as Harmon, which targets HTML/XML, node-http-proxy-json focuses exclusively on JSON. Given its last commit in 2016, the project appears to be abandoned, with no active development or maintenance, and no clear release cadence, making it potentially unsuitable for new projects requiring ongoing support or modern features.
Common errors
-
TypeError: Cannot read properties of null (reading 'age')
cause The `body` passed to the modification callback was `null` or undefined, likely because the response could not be parsed as valid JSON or had an unsupported encoding.fixAdd a check `if (body) { ... }` before attempting to access properties of the `body` object. Verify the `Content-Type` header and `Content-Encoding` from the `proxyRes` object to ensure it's JSON and uses a supported compression. -
Error: Unsupported content-encoding: br
cause The proxied server's response is compressed using Brotli ('br'), which is not supported by `node-http-proxy-json`.fixConfigure the target server to use 'gzip', 'deflate', or no compression. Alternatively, consider using a different proxy library or implementing a custom `proxyRes` handler to decompress Brotli manually before processing the JSON.
Warnings
- breaking The project is abandoned, with the last commit in 2016. It is not maintained, may have unpatched vulnerabilities, and is unlikely to receive updates for newer Node.js versions or dependencies. Use with caution or consider alternatives.
- gotcha This library only supports 'gzip', 'deflate', and uncompressed content encodings. If the target server uses 'br' (Brotli) or other compression types, the response body will not be parsed correctly, and modifications will fail.
- gotcha The library assumes `Content-Type: application/json`. If a proxied response has a different content type but contains JSON, or if the content type is `application/json` but the body is not valid JSON, parsing will fail, and `body` passed to the callback might be `null` or cause errors.
Install
-
npm install node-http-proxy-json -
yarn add node-http-proxy-json -
pnpm add node-http-proxy-json
Imports
- modifyResponse
import modifyResponse from 'node-http-proxy-json';
const modifyResponse = require('node-http-proxy-json'); - modifyResponse function signature
modifyResponse(proxyRes, res, function (body) { ... });modifyResponse(res, proxyRes, function (body) { ... });
Quickstart
const zlib = require('zlib');
const http = require('http');
const httpProxy = require('http-proxy');
const modifyResponse = require('node-http-proxy-json');
// Create a proxy server
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:5001'
});
// Listen for the `proxyRes` event on `proxy` to modify JSON responses
proxy.on('proxyRes', function (proxyRes, req, res) {
// Only modify if Content-Type is application/json
const contentType = proxyRes.headers['content-type'];
if (contentType && contentType.includes('application/json')) {
modifyResponse(res, proxyRes, function (body) {
if (body) {
// Example modification: change age, remove version field
body.age = 2;
delete body.version;
console.log('Modified response body:', body);
}
return body; // Return the modified body (can be a Promise)
});
} else {
console.log('Skipping modification for non-JSON response.');
}
});
// Create your main server that proxies requests
const server = http.createServer(function (req, res) {
proxy.web(req, res);
}).listen(5000, () => {
console.log('Proxy server listening on port 5000');
});
// Create your target server that provides JSON responses (e.g., gzipped)
const targetServer = http.createServer(function (req, res) {
const gzip = zlib.Gzip();
const _write = res.write;
const _end = res.end;
gzip.on('data', function (buf) { _write.call(res, buf); });
gzip.on('end', function () { _end.call(res); });
res.write = function (data) { gzip.write(data); };
res.end = function () { gzip.end(); };
res.writeHead(200, {'Content-Type': 'application/json', 'Content-Encoding': 'gzip'});
res.write(JSON.stringify({name: 'original-name', age: 1, version: '1.0.0', status: 'active'}));
res.end();
}).listen(5001, () => {
console.log('Target server listening on port 5001');
console.log('Test with: curl -H "Accept-Encoding: gzip" http://localhost:5000');
});