Created
January 8, 2021 16:20
-
-
Save corocoto/d151079c3b2c232a843742081a7490e9 to your computer and use it in GitHub Desktop.
HTTP Caching by using serve-static package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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