Brett Brett - 1 year ago 95
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
in my Express route handlers

app.get('/', (req, res) => {

Is this possible?

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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download