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 ?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With