Skip to content

Instantly share code, notes, and snippets.

@corocoto
Created January 8, 2021 16:20
Show Gist options
  • Save corocoto/d151079c3b2c232a843742081a7490e9 to your computer and use it in GitHub Desktop.
Save corocoto/d151079c3b2c232a843742081a7490e9 to your computer and use it in GitHub Desktop.
HTTP Caching by using serve-static package
/**
* Docs about `serve-static` package: https://expressjs.com/en/resources/middleware/serve-static.html#setheaders
* Link on full Glitch project and article about HTTP caching: https://web.dev/codelab-http-cache/
*/
const express = require('express');
const app = express();
app.use(express.static('public', {
etag: true,
lastModified: true,
setHeaders: (res, path) => {
const hashRegExp = new RegExp('\\.[0-9a-f]{8}\\.');
if (path.endsWith('.html')) {
// All of the project's HTML files end in .html
res.setHeader('Cache-Control', 'no-cache')
} else if (hashRegExp.test(path)) {
// If the RegExp matched, then we have a versioned URL.
res.setHeader('Cache-Control', 'max-age=31536000');
}
}
}));
const listener = app.listen(process.env.PORT, function() {
console.log('Your server is running on port ' + listener.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment