Home > Mobile >  Node.js | How to forward headers between microservices?
Node.js | How to forward headers between microservices?

Time:09-01

Main Question:

Do I need to pass the header in every internal microservice request to have it in the other microservice if it is created by common proxy server?

Example:

Structure:

enter image description here

In Nginx.conf: proxy_set_header X-Request-ID $request_id;

and when I request to any of these microservices, I can get the header value by using req.headers["x-request-id"]

But, when I do like:

enter image description here

// calling ms2 from ms1
const response = await fetch("http://ms2/");

In ms1 (the 1st hop) I can get the header as I show before, but in ms2 I can't.

I know express server processes a bunch of requests concurrently and it because of that. But anyways it feels weird when you need to pass the header every time with the internal requests:

// calling ms2 from ms1
const response = await fetch("http://ms2/", {
    headers: {
      "X-Request-ID": req.headers["x-request-id"],
    },
});
// when do like this I can get the value in ms2.

Is there any way, or it is what it is?

CodePudding user response:

If you need to perform the request to ms2 for every request to (a) specific endpoint(s) on ms1, you could create an Express middleware that would at least save you the trouble of having to perform the request each time manually:

const makeMs2Request = async (req, res, next) => {
  const response = await fetch("http://ms2/", {
    headers: {
      "X-Request-ID": req.headers["x-request-id"],
    }
  );
  req.ms2data = await response.json();
  next();
});

app.get('/my/endpoint/on/ms1', makeMs2Request, (req, res) => {
  // here you can use `req.ms2data`
  …
});
  • Related