What HTTP caching headers (Cache-Control, ETag) can a Node.js/Express API use to let clients and CDNs cache responses?
Short answer
Cache-Control specifies directives like max-age (how long a response can be cached) and public/private (whether shared caches like CDNs may store it); ETag provides a unique fingerprint of a response version, letting a client send If-None-Match on a subsequent request so the…
Advertisement
AModel answer
Cache-Control specifies directives like max-age (how long a response can be cached) and public/private (whether shared caches like CDNs may store it); ETag provides a unique fingerprint of a response version, letting a client send If-None-Match on a subsequent request so the server can respond with a lightweight 304 Not Modified instead of resending the full body if nothing has changed -- both let caching happen outside the application, at the browser or CDN level.
app.get('/api/products', (req, res) => {
res.set('Cache-Control', 'public, max-age=300');
res.set('ETag', computeEtag(products));
if (req.headers['if-none-match'] === computeEtag(products)) {
return res.status(304).end();
}
res.json(products);
});Real-world example
A public product-catalog API sets Cache-Control: public, max-age=300 on its GET endpoints, letting a CDN serve the vast majority of read traffic directly from edge locations without ever reaching the origin server.
Likely follow-ups
- What's the difference between the 'public' and 'private' Cache-Control directives, and when should an API use 'private' or 'no-store' instead?
- How does an ETag differ from a Last-Modified header for conditional requests?
Related topics