How to add the Cache-Control header in Express

Adding Cache-Control via the res.set function

You can add the Cache-Control header to your response by calling res.set in your route handler. This function takes the header name as the first argument and the header value as the second argument. This will apply the Cache-Control header to the response for this route only.

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.set('Cache-Control', 'no-transform, max-age=3600, s-maxage=7200')
  res.send('Hello World!')
})

app.listen(3000, () => {
  console.log('Example app listening on port 3000!')
})

Adding Cache-Control via middleware function

If we want to apply the Cache-Control header to responses across the application, we can use a middleware function. Then, routes will have the Cache-Control header applied by default, and we can override it in specific routes if we want.

app.use((req, res, next) => {
  res.set('Cache-Control', 'no-transform, max-age=3600, s-maxage=7200')
  next()
})

app.get('/', (req, res) => {
  // This will be cached automatically
  res.send('Hello World!')
})

app.get('/no-cache', (req, res) => {
  // This will not be cached
  res.set('Cache-Control', 'no-store')
  res.send('Hello World!')
})