Issue capturing response in http-proxy-middleware - Stack Overflow most recent 30 from stackoverflow.com 2026-04-14T22:23:20Z https://stackoverflow.com/feeds/question/79916360 https://creativecommons.org/licenses/by-sa/4.0/rdf https://stackoverflow.com/q/79916360 1 Issue capturing response in http-proxy-middleware S7H https://stackoverflow.com/users/2869971 2026-03-28T20:32:45Z 2026-03-29T08:47:49Z <p>I am writing a proxy to relay websocket messages to a backend server.</p> <p>Client initiates a request over HTTP to upgrade to WS using a Sec-WebSocket-Key header. The proxy has to intercept the request and add additional headers to the request and relay the request to backend service.</p> <p>Backend will accept the upgrade request and will return a Sec-WebSocket-Accept header along with a request-Id header.</p> <p>During this communication I need to intercept the response and get the request-id returned from the Backend service.</p> <p>I have written this code to get the request-id. When I initiate the request I can see logs from <code>proxyReqWs</code> hook but I don't see any logs from <code>proxyRes`</code> hook. I can see that the proxy has relayed the response to the client as I can see <code>Sec-Websocket-Accept</code> and <code>xyz-req-id</code> headers in the Network tab in Developer Console. The proxy should have intercepted the response and changed the header names, but that has not happened.</p> <p>What am I missing in this code? I need to change the response header.</p> <p>// proxy.js</p> <pre><code>export const setupProxy = (proxyConfig: ProxyConfig): RequestHandler =&gt; { const proxyOptions: Options = { target: proxyConfig.endpoint, changeOrigin: true, secure: true, ws: true, on: { proxyReq: (proxyReq, req, res) =&gt; { log('--------------------------------------'); logRequest(req as Request, 'Original Request from Client'); // Log original client request proxyReq.setHeader('Authorization', `Bearer ${proxyConfig.details.apiKey}`); logRequest(proxyReq, 'MODIFIED request to Backend)'); // Log modified request }, proxyRes: (proxyRes, req, res) =&gt; { logResponse(proxyRes, req as Request, 'Original Response from Backend'); // Log response from Backend const isWebSocketSuccess = proxyRes.statusCode === 101; let requestId: string | undefined; if(isWebSocketSuccess) { const requestId = proxyRes.headers['xyz-req-id']; } if (requestId) { log(requestId); proxyRes.headers['x-xyz-request-id'] = requestId; } delete proxyRes.headers['xyz-req-id']; logResponse(proxyRes, req as Request, 'MODIFIED response to Client)'); // Log modified response log('--------------------------------------'); }, proxyReqWs: (proxyReq, req, socket, options, head) =&gt; { log('proxyReqWs event triggered for:', { method: req.method, url: req.url }); proxyReq.setHeader('Authorization', `Bearer ${proxyConfig.details.apiKey}`); }, error: (err, req, res) =&gt; { logError('Proxy Error:', err.message, 'Target:', target); if (res.writeHead &amp;&amp; !res.headersSent) { res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Bad Gateway', message: err.message })); } } }, router: (req) =&gt; { return proxyConfig.endpoint; } }; return createProxyMiddleware(proxyOptions); }; </code></pre> <p>// server.js</p> <pre><code>import express from 'express'; import { setupProxy } from './proxy'; import config from './config'; import http from 'http'; const app = express(); const PORT = config.port; // --- Express Middleware --- // --- Health Check Endpoint --- app.get('/health', (req, res) =&gt; { console.log('Health Check Request Received'); res.status(200).send('Proxy is healthy!'); }); const proxy = setupProxy(config); app.use('/', proxy); // --- Start the Server --- const server = http.createServer(app); server.on('upgrade', proxy.upgrade); server.listen(PORT, () =&gt; { console.log(`[SERVER] Express Proxy listening on port ${PORT}`); console.log(`[SERVER] Forwarding requests to Backend endpoint: ${config.endpoint}`); }); // Handle server errors server.on('error', (error: NodeJS.ErrnoException) =&gt; { if (error.syscall !== 'listen') { throw error; } const bind = typeof PORT === 'string' ? 'Pipe ' + PORT : 'Port ' + PORT; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(`${bind} requires elevated privileges`); process.exit(1); break; case 'EADDRINUSE': console.error(`${bind} is already in use`); process.exit(1); break; default: throw error; } }); export default app; </code></pre> <p>How should I fix this proxy so that I can intercept both request and response and call an external service after intercepting them?</p> https://stackoverflow.com/questions/79916360/-/79916490#79916490 1 Answer by traynor for Issue capturing response in http-proxy-middleware traynor https://stackoverflow.com/users/4321299 2026-03-29T08:47:49Z 2026-03-29T08:47:49Z <p><code>proxyRes</code> is for HTTP traffic, intercepting websocket response is not supported:</p> <blockquote> <p><a href="https://github.com/chimurai/http-proxy-middleware/discussions/635" rel="nofollow noreferrer">Websocket response interceptor? #635</a></p> </blockquote> <p>possible workarounds:</p> <blockquote> <p><a href="https://github.com/http-party/node-http-proxy/pull/991" rel="nofollow noreferrer">Added ability to intercept and manipulate web socket messages #991</a></p> <p><a href="https://github.com/http-party/node-http-proxy/pull/1301/files" rel="nofollow noreferrer">[ws] add options to transform client and server streams #1301</a></p> </blockquote>