{"id":17258,"library":"http-proxy-middleware-body","title":"HTTP Proxy Middleware Response Body Extractor","description":"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.","status":"maintenance","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/fatalxiao/http-proxy-middleware-body","tags":["javascript","http-proxy-middleware"],"install":[{"cmd":"npm install http-proxy-middleware-body","lang":"bash","label":"npm"},{"cmd":"yarn add http-proxy-middleware-body","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-proxy-middleware-body","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is an extension for http-proxy-middleware and requires it to function.","package":"http-proxy-middleware","optional":false},{"reason":"Used internally to buffer the response stream.","package":"bufferhelperconcat-stream","optional":false}],"imports":[{"note":"`getBody` is used as a function to process the response stream within `onProxyRes`.","wrong":"import { getBody } from 'http-proxy-middleware-body'; // getBody is likely a default export in CJS contexts.","symbol":"getBody","correct":"import getBody from 'http-proxy-middleware-body'; // ESM\nconst getBody = require('http-proxy-middleware-body'); // CommonJS"},{"note":"`http-proxy-middleware` is primarily used with named imports for `createProxyMiddleware`. Note that `http-proxy-middleware` v4+ is moving to ESM-only.","wrong":"const createProxyMiddleware = require('http-proxy-middleware'); // Incorrect for named export.","symbol":"createProxyMiddleware","correct":"import { createProxyMiddleware } from 'http-proxy-middleware'; // ESM\nconst { createProxyMiddleware } = require('http-proxy-middleware'); // CommonJS"}],"quickstart":{"code":"const express = require('express');\nconst { createProxyMiddleware } = require('http-proxy-middleware');\nconst getBody = require('http-proxy-middleware-body');\n\nconst app = express();\nconst PORT = 3000;\nconst TARGET_URL = process.env.PROXY_TARGET_URL || 'http://localhost:3001';\n\napp.use('/api', createProxyMiddleware({\n    target: TARGET_URL,\n    changeOrigin: true,\n    onProxyRes: (proxyRes, req, res) => getBody(res, proxyRes, rawBody => {\n        if (!rawBody) {\n            console.log('No raw body received or it was empty.');\n            // Ensure the original response still flows if no body to process\n            return;\n        }\n\n        try {\n            const body = JSON.parse(rawBody);\n            console.log('Intercepted proxy response body:', body);\n\n            // Example: Modify response based on content\n            if (body && body.code === 'TOKEN_EXPIRED_CODE') {\n                console.warn('Token expired detected! Handling...');\n                // In a real app, you might redirect, refresh token, or modify response status\n                res.statusCode = 401; // Unauthorized\n                res.statusMessage = 'Token Expired';\n                res.setHeader('Content-Type', 'application/json');\n                res.end(JSON.stringify({ message: 'Authentication required. Please log in again.' }));\n                return;\n            }\n            \n            // If not handled, simply send the raw body back\n            res.setHeader('Content-Type', proxyRes.headers['content-type'] || 'application/json');\n            res.end(rawBody);\n\n        } catch (e) {\n            console.error('Error parsing proxy response body:', e);\n            // Fallback: send original raw body or an error response\n            res.setHeader('Content-Type', proxyRes.headers['content-type'] || 'text/plain');\n            res.end(rawBody || 'Error processing response.');\n        }\n    })\n}));\n\n// A simple target server for demonstration\napp.get('/target', (req, res) => {\n    res.json({ message: 'Hello from target!', code: 'SUCCESS' });\n});\n\napp.get('/target-expired', (req, res) => {\n    res.json({ message: 'Your token has expired.', code: 'TOKEN_EXPIRED_CODE' });\n});\n\napp.listen(PORT, () => {\n    console.log(`Proxy server listening on port ${PORT}`);\n    console.log(`Target server running on ${TARGET_URL}. Use /api/target or /api/target-expired`);\n});\n\n// To run this example, create a target server (e.g., on port 3001)\n// const express = require('express');\n// const app = express();\n// app.listen(3001, () => console.log('Target server on 3001'));\n// app.get('/', (req, res) => res.json({ message: 'Default target response' }));\n// app.get('/target', (req, res) => res.json({ message: 'Hello from target!', code: 'SUCCESS' }));\n// app.get('/target-expired', (req, res) => res.json({ message: 'Your token has expired.', code: 'TOKEN_EXPIRED_CODE' }));\n","lang":"javascript","description":"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."},"warnings":[{"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(...) }`.","message":"This 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+).","severity":"breaking","affected_versions":">=3.0.0 of http-proxy-middleware"},{"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).","message":"This 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate migrating to `http-proxy-middleware`'s `responseInterceptor` feature for response body manipulation, which is actively supported.","message":"`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.","severity":"deprecated","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","cause":"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.","error":"SyntaxError: Unexpected token < in JSON at position 0"},{"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';`.","cause":"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.","error":"TypeError: getBody is not a function"},{"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.","cause":"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.","error":"ERR_STREAM_PREMATURE_CLOSE"}],"ecosystem":"npm","meta_description":null}