Work with HTTP headers in Express

By

Published · Updated

Tagged: Express.js

Learn how to read and change HTTP headers in Express using req.headers, req.header() to get one value, res.set() to set a header, and the res.type() shortcut.

In Express you read HTTP headers from the req object, and you set them on the res object. Headers carry metadata about a request or a response: the content type, the user agent, caching instructions, and more.

Let’s see both directions.

Access HTTP headers values from a request

You can access all the HTTP headers using the Request.headers property:

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

This is a plain JavaScript object. Node lowercases every header name, so you’ll find user-agent in there, not User-Agent:

app.get('/', (req, res) => {
  console.log(req.headers['user-agent'])
  // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...
})

Use the Request.header() method to access one individual request header’s value:

app.get('/', (req, res) => {
  req.header('User-Agent')
})

This method is case-insensitive, so you can write the header name any way you like. If the header is missing, it returns undefined.

Change any HTTP header value for a response

You can change any HTTP header value using Response.set():

res.set('Content-Type', 'text/html')

You can also pass an object to set several headers in one call:

res.set({
  'Content-Type': 'text/html',
  'Cache-Control': 'no-store'
})

There is a shortcut for the Content-Type header, however:

res.type('.html')
// => 'text/html'

res.type('html')
// => 'text/html'

res.type('json')
// => 'application/json'

res.type('application/json')
// => 'application/json'

res.type('png')
// => image/png:

To read back a header you already set on the response, use res.get():

res.get('Content-Type') // 'text/html'

Be careful with the order

Headers travel at the very start of the HTTP response. Once you send the body with res.send() or res.json(), they’re gone.

If you try to set a header after that, Node throws an error:

app.get('/', (req, res) => {
  res.send('hello')
  res.set('Cache-Control', 'no-store')
  // Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers
  // after they are sent to the client
})

The fix is to set every header before the call that sends the body. This error also shows up when one middleware sends a response and a later handler tries to send another one. If you see it, look for two responses on the same request.

If you’re not sure what a response header does, paste your headers into my HTTP headers explainer tool and it will explain each one.

Want me to talk about your product? You can sponsor this site.

Related posts about express: