MarcoLe
MarcoLe

Reputation: 2509

Node - express-http-proxy - set Header before proxying

Before I proxy to a address I want to set the header of the proxy (Smth like an interceptor). I use the express-http-library and express with Node.JS. So far my code looks as follow. Btw. the docs of this library did not make me any wiser.

app.use('/v1/*', proxy('velodrome.usefixie.com', {
userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
    // recieves an Object of headers, returns an Object of headers.
    headers = {
        Host: 'api.clashofclans.com',
        'Proxy-Authorization': `Basic ${new Buffer('token').toString('base64')}`
    };
    console.log(headers);

    return headers;
}

}));

And even though the console prints me out the headers obj. as expected the proxy authorization did not work:

{ Host: 'api.clashofclans.com',
  'Proxy-Authorization': 'Basic token' }

Can anyone help me out?

Upvotes: 5

Views: 9775

Answers (2)

Chris Concannon
Chris Concannon

Reputation: 443

express-http-proxy allows you to pass in an options object (same object as used in the request library) via proxyReqOptDecorator:

app.use("/proxy", proxy("https://target.io/api", {
  proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
    proxyReqOpts.headers = {"Authorization": "Bearer token"};
    return proxyReqOpts;
  }
}));

or

app.use("/proxy", proxy("https://target.io/api", {
  proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
    proxyReqOpts.auth = `${username}:${password}`;
    return proxyReqOpts;
  }
}));

The documentation for proxyReqOptDecorator can be found here

Upvotes: 9

ruedamanuel
ruedamanuel

Reputation: 1930

If all you need to do is add some middleware to change some headers, you should be able to just do something like this:

app.use('/v1/*', (req, res, next) => {
    req.headers['Proxy-Authorization'] = `Basic ${new Buffer('token').toString('base64')}`;
    next();
});

Upvotes: 1

Related Questions