Search code examples
javascriptnode.jsexpresshttp-headershttp-proxy

How to modify response headers with express-http-proxy


Background

I'm using express-http-proxy to proxy a handful of requests between my SPA (single page application) and a CouchDB instance. I'm doing this proxy on a per call basis, NOT creating a proxy server (this will be important in a moment).

example of current use

app.use(`some/url`, proxy(dburl, {
  forwardPath: req => {return 'some/url'+require('url').parse(req.url).path;}
 }) );

Which means I am NOT using httpProxy.createServer. I want to send some snippet of text data along with my responses as a header. After looking through the documentation I've come to the conclusion that what I want will be using intercept. Unfortunately I've not quite managed to grasp how to use it, and the only related questions I've found so far appear to be based on httpProxy.createServer which appears (from my limited understanding) to work differently.

We are using individual request proxying because we wish to proxy different requests to different micro-services, and found this to be the most concise way (that we knew of & at the time) of doing that.

The Question

Given the code

const text = 'asdf';
app.use(`some/url`, proxy(dburl, {
  forwardPath: req => {return 'some/url'+require('url').parse(req.url).path;},
  intercept: function(rsp, data, req, res, callback) {
    //SUSPECT LOCATION
  }
}) );

Is there some code at SUSPECT LOCATION which would allow me to place text on the header for the final response without further affects to the (currently otherwise working) proxy?

Additional Notes

Headers and network requests in general are not very familiar to me, my apologies if the answer seems self evident.

Bonus points for a link to a resource that helps explain either the finer points of using this library for proxying, a similar library for proxying, or the underlying technologies which would make it clear how to use this library for proxying. AKA I'd rather spend some of my own time looking further into this and not come back for further questions.

I am not entirely confident that the place for my code will be SUSPECT LOCATION and I will happily listen if it needs to go somewhere else, or if we need to approach this problem in a different way.


Solution

  • The accepted answer is now outdated. Intercept does not exist anymore.

    Instead, use your own middleware before the proxy function

    router.route('/my-route').get((req, res, next) => {
      res.set('My-Header', 'my-header-value');
      next();
    }, proxyFunction);