Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Cache-Control per file with ExpressJS

Is there a way to set the Cache-Control property per files in your ExpressJS app ? I would like a granular control over the caching of the files in my app... how can i achieve this ? Whats the best practises in regards to Cache-Control ?

like image 317
Brett Avatar asked Dec 27 '22 10:12

Brett


2 Answers

app.use(function (req, res, next) {
  if (req.url.match(/* some filter */)) {
    res.setHeader('Cache-Control', ...)
  } else if (req.url.match(/* some filter */)) {
    res.setHeader('Cache-Control', ...)
  }

  next()
})

app.use(express.static(__dirname + '/public'))

No need to make it complicated.

like image 54
Jonathan Ong Avatar answered Dec 31 '22 10:12

Jonathan Ong


This thread is quite old but there is a simpler way to implement basic cache control on static files. Simply add an options object to the express.static() built-in middleware function like this:

let options = {
    maxAge: "1d"
}

app.use(express.static(__dirname + '/public', options))

This will enable cache-control for all of your static assets, by default. It would set the Cache-Control header to public, max-age=86400.

like image 28
TColbert Avatar answered Dec 31 '22 10:12

TColbert