Registry / http-networking / http-proxy-middleware-body

http-proxy-middleware-body

JSON →
library1.0.0jsnpmunverified

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.

npm install http-proxy-middleware-body
INSTALL
IMPORT
SIG · HTTP-PROXY-MIDDLEW
H
http-proxy-middleware-body
http-networkingjavascriptv1.0.0
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

getBody
✓ import getBody from 'http-proxy-middleware-body'; // ESM const getBody = require('http-proxy-middleware-body'); // CommonJS
✗ import { getBody } from 'http-proxy-middleware-body'; // getBody is likely a default export in CJS contexts.
`getBody` is used as a function to process the response stream within `onProxyRes`.
createProxyMiddleware
✓ import { createProxyMiddleware } from 'http-proxy-middleware'; // ESM const { createProxyMiddleware } = require('http-proxy-middleware'); // CommonJS
✗ const createProxyMiddleware = require('http-proxy-middleware'); // Incorrect for named export.
`http-proxy-middleware` is primarily used with named imports for `createProxyMiddleware`. Note that `http-proxy-middleware` v4+ is moving to ESM-only.

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' }));
Debug
Known issues
breakingThis package (`http-proxy-middleware-body`) is likely incompatible with `http-proxy-middleware` versions that have breaking changes to the `onProxyRes` signature or streaming behavior. Given `http-proxy-middleware` has undergone several major versions and introduced `responseInterceptor` since, this package might not work as expected with newer `http-proxy-middleware` versions (e.g., v3+ or v4+).
fix
Consider migrating to `http-proxy-middleware`'s built-in `responseInterceptor` function, which provides similar functionality and is actively maintained. Set `selfHandleResponse: true` in `http-proxy-middleware` options and use `on: { proxyRes: responseInterceptor(...) }`.
affects: >=3.0.0 of http-proxy-middleware
gotchaThis package buffers the entire response body in memory. For very large response payloads, this can lead to high memory consumption and potential performance issues, especially under heavy load. Ensure that the expected response sizes are manageable or implement additional safeguards.
fix
Monitor memory usage in production. If large responses are expected, consider if buffering the entire body is necessary or if stream-based processing can be implemented directly using `http-proxy-middleware`'s native stream handling capabilities in `onProxyRes` (which is more complex).
affects: >=1.0.0
deprecated`http-proxy-middleware-body` has not been updated in over three years and appears to be in maintenance mode or abandoned. Its parent library, `http-proxy-middleware`, is actively developed and has introduced `responseInterceptor` which can achieve similar outcomes directly. Relying on an unmaintained package can introduce security risks or compatibility issues with newer Node.js versions or other dependencies.
fix
Evaluate migrating to `http-proxy-middleware`'s `responseInterceptor` feature for response body manipulation, which is actively supported.
affects: >=1.0.0
gotchaThe package currently uses CommonJS `require` syntax in its examples and likely does not officially support ESM out of the box. With the Node.js ecosystem shifting towards ESM, and `http-proxy-middleware` itself moving to ESM-only in future major versions (v4+), this can lead to compatibility challenges in modern ESM-only projects.
fix
For ESM projects, use a CommonJS wrapper or a build step to handle compatibility, or preferably migrate to `http-proxy-middleware`'s native `responseInterceptor` if targeting modern Node.js environments.
affects: >=1.0.0
Errors
Common errors & fixes
SyntaxError: Unexpected token < in JSON at position 0
The response body being parsed by `JSON.parse` is not valid JSON. This often happens when a non-JSON response (e.g., HTML, plain text, or an error page) is received but treated as JSON.
fix
Always wrap `JSON.parse` calls in a `try...catch` block. Inspect the `rawBody` content (e.g., log it) before parsing to understand its format. Check `proxyRes.headers['content-type']` to confirm if the response is actually 'application/json' before attempting to parse it.
TypeError: getBody is not a function
The `getBody` function was not correctly imported or required. This typically happens with incorrect CommonJS `require` syntax (e.g., `const { getBody } = require(...)` instead of `const getBody = require(...)`) if `getBody` is a default export, or a mixup between CommonJS and ESM.
fix
Ensure you are using the correct `require` statement for CommonJS: `const getBody = require('http-proxy-middleware-body');`. For ESM, use `import getBody from 'http-proxy-middleware-body';`.
ERR_STREAM_PREMATURE_CLOSE
This error might occur if the response stream (`proxyRes`) is being read or consumed by another part of your application or another middleware before `http-proxy-middleware-body` attempts to process it.
fix
Ensure that `http-proxy-middleware-body`'s `getBody` function is the *only* handler attempting to read the `proxyRes` stream. If other middlewares or custom `onProxyRes` logic also access the stream, they might interfere. Consider the order of middleware execution or consolidate stream handling.
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies
http-proxy-middlewarerequiredThis package is an extension for http-proxy-middleware and requires it to function.
bufferhelperconcat-streamrequiredUsed internally to buffer the response stream.
Agent activity
10 hits · last 30 days
node
10
Resources
http-proxy-middleware-body — npm install http-proxy-middleware-body · libregistry