Brett Brett - 1 month ago 11
Node.js Question

How can I add a custom value to my Node.js HTTP request for Express to consume

I have an Express server listening on a Unix Domain Socket. I'm making an http request like so:

const requestOptions = {socketPath, method, path, headers, _custom: {foo: () => 'bar'}}
http.request(requestOptions, responseCb)


And want to use
_custom
in my Express route handlers

app.get('/', (req, res) => {
console.log(req._custom)
})


Is this possible?

EDIT:
_custom
is an object with functions.

EDIT: The answer I marked as correct is the best solution I could find, however it does not allow sending of objects (which is what I really want).

Answer

You can add _custom to your req object by adding custom middleware in your Express server prior to your routes that need to use req._custom.

app.use((req, res, next) => {

  if (req.get('X-Custom-Header')) {
   // add custom to your request object
   req._custom = req.get('X-Custom-Header');
  } 

  return next();
});

On the client side you can add the custom header

let headers = {
  'X-Custom-Header': 'my-custom-value'
};

const requestOptions = {socketPath, method, path, headers};
http.request(requestOptions, responseCb)
Comments