5

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?

1
  • the answer I provided is more complete than the accepted answer and it continues to get upvotes even now, 3 years later... could you please mark my answer as the accepted one? Commented Aug 17, 2021 at 22:30

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

1

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.