Express headers

Setting up HTTP headers in Express

Headers in Express are set using a response method set() as follows:

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

You can also set multiple headers at once in Express by passing an object, like this:

  'Content-Type': 'text/plain',
  'Cache-control': 'public'

Following is a simple Express middleware function to set up headers:

const setHeaders = function (req, res, next) {
  res.set('Cache-control', `public`)
  next() // remember the next() function!

To use the above setHeaders middleware function to set headers for all requests in an Express app, just pass it into app.use() like this:


See a full article on setting up cache header in Express to achieve better performance even from small servers.

Powered by

Copyright 2019 - present