HTTP Proxy Response Rewrite

0.0.1 · abandoned · verified Wed Apr 22

http-proxy-response-rewrite is a Node.js library designed to simplify the modification of response bodies when using `http-proxy`. Its core functionality involves transparently handling common compression formats like `gzip` and `deflate` to decompress the response body, allowing developers to manipulate the plain text or JSON content, and then re-compress it before sending it to the client. The library is currently at version 0.0.1 and has not been updated in approximately 8 years, indicating it is no longer actively maintained. Its primary differentiator was providing a streamlined way to intercept and modify compressed `http-proxy` responses, a task that would otherwise require manual zlib handling. Due to its abandoned status, developers should consider more modern and actively maintained alternatives for proxy response manipulation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up an HTTP proxy to intercept and modify a gzipped JSON response from a target server. It parses the body, changes an attribute, deletes another, and then re-serializes and re-compresses the response.

const zlib = require('zlib');
const http = require('http');
const httpProxy = require('http-proxy');
const modifyResponse = require('http-proxy-response-rewrite');

// Create a proxy server
const proxy = httpProxy.createProxyServer({
    target: 'http://localhost:5001'
});

// Listen for the `proxyRes` event on `proxy` to modify responses
proxy.on('proxyRes', function (proxyRes, req, res) {
    modifyResponse(res, proxyRes.headers['content-encoding'], function (body) {
        if (body) {
            // Modify the response body (e.g., JSON manipulation)
            let modifiedBody = JSON.parse(body);
            modifiedBody.age = 2;
            delete modifiedBody.version;
            return JSON.stringify(modifiedBody);
        }
        return body;
    });
});

// Create your server and then proxies the request
const server = http.createServer(function (req, res) {
    proxy.web(req, res);
}).listen(5000, () => console.log('Proxy server listening on port 5000'));

// Create a target server with gzipped content
const targetServer = http.createServer(function (req, res) {
    const gzip = zlib.createGzip();
    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: 'http-proxy-json', age: 1, version: '1.0.0'}));
    res.end();
}).listen(5001, () => console.log('Target server listening on port 5001'));

view raw JSON →