Ilja
Ilja

Reputation: 46479

How to remove a header from express req object?

I'm trying to figure out how to remove header from req object in express. I believe this res.disable("Header Name") removes it from res object, but same doesn't work for req.headers

Upvotes: 6

Views: 13403

Answers (3)

Christopher
Christopher

Reputation: 193

Just thought I would mention that in node/ express the header key gets lowercased.

So this did not work for me:

  delete req.headers['Authorization']

BUT this did work for me:

  delete req.headers['authorization']

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 9933

You can simply delete headers from your request object, like i am doing below-

console.log(req.headers)

// { host: 'localhost:8081',
//   connection: 'keep-alive',
//   auth_token: 'c79d2f80029c1a1382b2e831643e5447b902a6f9',
//   'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36',
//   'postman-token': 'b2cef620-f85d-556c-acc1-8337da2d5e81',
//   'cache-control': 'no-cache',
//   api_key: 'FB499A4FF77901AFCD2278457658B7F7B17EAC112B489DAA304D3F2A059DFCC4',
//   'content-type': 'application/json',
//   accept: '*/*',
//   dnt: '1',
//   'accept-encoding': 'gzip, deflate, sdch, br',
//   'accept-language': 'en-US,en;q=0.8' }

// Now Delete the headers from your request object.

delete req.headers;

console.log(req.headers) // undefined

If you want to remove any key from header then use below code:

delete req.headers['auth_token'];

Upvotes: 1

robertklep
robertklep

Reputation: 203286

That could be as simple as adding this middleware:

app.use(function(req, res, next) {
  delete req.headers['header-name']; // should be lowercase
  next();
});

Upvotes: 11

Related Questions