Leo Jiang
Leo Jiang

Reputation: 26105

Changing the "expires" header in ExpressJS?

I tried the following, but the expiration is set to 1 minute:

app.get(['/css/*','/js/*'],express.static('public',{maxAge:7*86400000}));
app.get(['/fonts/*'],express.static('public',{maxAge:30*86400000}));

How do set the expiration time using ExpressJS? In the code above, I tried setting the expiration time to 1 week and 1 month respectively.

Upvotes: 5

Views: 8856

Answers (2)

Alexander Art
Alexander Art

Reputation: 1589

You use Express static, and it's perfecly fine, it's rather powerfull tool to serve static files.

express.static is the only built-in middleware in Express. It is based on serve-static, and is responsible for serving the static assets of an Express application.

Besides maxage support it also supports ETags.

Just use it this way:

app.use(express.static(__dirname + '/public', { maxAge: '1d' }));

Here is the very good explanation.

Upvotes: 11

num8er
num8er

Reputation: 19372

Use https://github.com/expressjs/serve-static
Example:

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.get(['/css/*','/js/*'],express.static('public',{maxAge:7*86400000}));
app.get(['/fonts/*'],express.static('public',{maxAge:30*86400000}));

function setCustomCacheControl(res, path) {
  if (serveStatic.mime.lookup(path) === 'text/html') {
    // Custom Cache-Control for HTML files
    res.setHeader('Cache-Control', 'public, max-age=0')
  }
}
app.use(serveStatic(__dirname + '/public/css/', {
  maxAge: '7d',
  setHeaders: setCustomCacheControl
}))

app.use(serveStatic(__dirname + '/public/js/', {
  maxAge: '7d',
  setHeaders: setCustomCacheControl
}))

app.use(serveStatic(__dirname + '/public/fonts/', {
  maxAge: '30d',
  setHeaders: setCustomCacheControl
}))

app.listen(3000)

Upvotes: 3

Related Questions