How to forward headers between microservices?

Issue

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?

Solution

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`
  …
});

Answered By – robertklep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published