How to send an external HTTP request from proxyReq, proxyRes and proxyReqWs hooks
07:56 31 Mar 2026

I am building a http proxy with websockets. I need to intercept an incoming request, call an external service to get some headers, add the additional headers to the incoming request and send it to the target server.

On response, I need to intercept the call again, call an external service and return the response to client.

I have this code that I am trying to test but I get `Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client` error message when I try to set additional headers to the incoming request.

I get error on statement:

proxyReq.setHeader('additional-header-1', additionalHeader.header1);
import httpProxy from 'http-proxy';

const proxy = httpProxy.createProxyServer({
    target:         endpoint,
    changeOrigin:   true,
    secure:         true,
    ws:             true
});

proxy.on('proxyReq', onRequest);
proxy.on('proxyRes', onResponse);

const onRequest = (proxyReq, req) => {
    (async () => {
        try {
            
            const getAdditionalHeaders = await fetch(`${externalServiceUrl}/getAdditionalHeaders`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': authorizationToken
                }
            });

            let additionalHeader = await getAdditionalHeaders.json();
            proxyReq.setHeader('additional-header-1', additionalHeader.header1); // Getting the error on this statement.
            proxyReq.setHeader('additional-header-1', additionalHeader.header2);
        } catch (err) {
            console.log(err);
        }
    })();
};

How can I call an external service, await the response, from proxyReq, proxyRes or proxyReqWs events?

node.js express http-proxy