HTTP Proxy Middleware Response Body Extractor

1.0.0 · maintenance · verified Wed Apr 22

The `http-proxy-middleware-body` package, currently at version `1.0.0` (last published three years ago), provides a utility function to capture and process the response body from proxied requests when using `http-proxy-middleware`. This is particularly useful for scenarios where introspection or modification of the proxy's response payload is required, such as error handling, token expiration checks, or data transformation before sending the response back to the client. While `http-proxy-middleware` itself focuses on proxying, this package extends its capabilities by exposing the `onProxyRes` event's full response data stream, enabling developers to parse JSON or other raw body formats by buffering the entire stream. Its release cadence is inactive, as `1.0.0` is the current and seemingly only major version. It differentiates itself by offering a simple way to access the full response body, a feature that the core `http-proxy-middleware` API did not directly provide in early versions, though newer versions of `http-proxy-middleware` now offer `responseInterceptor` for similar functionality.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `http-proxy-middleware-body` with an Express server to intercept and process the response body from a proxied target, specifically showing how to check for an expired token code and modify the response returned to the client. It also illustrates error handling for JSON parsing. You need to ensure a target server is running (e.g., on port 3001) for the proxy to forward requests to.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const getBody = require('http-proxy-middleware-body');

const app = express();
const PORT = 3000;
const TARGET_URL = process.env.PROXY_TARGET_URL || 'http://localhost:3001';

app.use('/api', createProxyMiddleware({
    target: TARGET_URL,
    changeOrigin: true,
    onProxyRes: (proxyRes, req, res) => getBody(res, proxyRes, rawBody => {
        if (!rawBody) {
            console.log('No raw body received or it was empty.');
            // Ensure the original response still flows if no body to process
            return;
        }

        try {
            const body = JSON.parse(rawBody);
            console.log('Intercepted proxy response body:', body);

            // Example: Modify response based on content
            if (body && body.code === 'TOKEN_EXPIRED_CODE') {
                console.warn('Token expired detected! Handling...');
                // In a real app, you might redirect, refresh token, or modify response status
                res.statusCode = 401; // Unauthorized
                res.statusMessage = 'Token Expired';
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({ message: 'Authentication required. Please log in again.' }));
                return;
            }
            
            // If not handled, simply send the raw body back
            res.setHeader('Content-Type', proxyRes.headers['content-type'] || 'application/json');
            res.end(rawBody);

        } catch (e) {
            console.error('Error parsing proxy response body:', e);
            // Fallback: send original raw body or an error response
            res.setHeader('Content-Type', proxyRes.headers['content-type'] || 'text/plain');
            res.end(rawBody || 'Error processing response.');
        }
    })
}));

// A simple target server for demonstration
app.get('/target', (req, res) => {
    res.json({ message: 'Hello from target!', code: 'SUCCESS' });
});

app.get('/target-expired', (req, res) => {
    res.json({ message: 'Your token has expired.', code: 'TOKEN_EXPIRED_CODE' });
});

app.listen(PORT, () => {
    console.log(`Proxy server listening on port ${PORT}`);
    console.log(`Target server running on ${TARGET_URL}. Use /api/target or /api/target-expired`);
});

// To run this example, create a target server (e.g., on port 3001)
// const express = require('express');
// const app = express();
// app.listen(3001, () => console.log('Target server on 3001'));
// app.get('/', (req, res) => res.json({ message: 'Default target response' }));
// app.get('/target', (req, res) => res.json({ message: 'Hello from target!', code: 'SUCCESS' }));
// app.get('/target-expired', (req, res) => res.json({ message: 'Your token has expired.', code: 'TOKEN_EXPIRED_CODE' }));

view raw JSON →