Performance: HTTP caching headers (ETag, Cache-Control)
This affects how fast the browser can load resources by reusing cached files instead of downloading them again.
app.use(express.static('public', { maxAge: '1d', etag: true }))
app.use(express.static('public')) // no cache headers set
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching headers | N/A | N/A | High due to delayed resource loading | [X] Bad |
| Cache-Control with max-age and ETag | N/A | N/A | Low due to cached resources | [OK] Good |
ETag header in Express HTTP responses?res.set() or res.header() to set headers. Both work, but res.set() is common and correct here.max-age=3600 is correct. res.header('Cache-Control', 'no-cache') uses 'no-cache' which disables caching. res.cache('max-age=3600') is invalid method. res.setHeader('Cache-Control', 'max-age=60') sets max-age to 60 seconds, not 1 hour.If-None-Match matching the ETag?app.get('/data', (req, res) => {
const data = { message: 'Hello' };
const etag = '12345';
res.set('ETag', etag);
if (req.headers['if-none-match'] === etag) {
res.status(304).end();
} else {
res.json(data);
}
});If-None-Match header equals the ETag '12345', the server responds with status 304 and no body.app.get('/resource', (req, res) => {
const content = 'data';
res.setHeader('Cache-Control', 'max-age=600');
res.set('ETag', 'abc123');
res.send(content);
});res.setHeader and res.set both set headers correctly; using both is allowed and does not conflict.Cache-Control and ETag headers to achieve this?max-age=300 is correct to allow caching for that duration.ETag allows clients to check if the cached version is still valid before using it.Pass the test and this pattern moves unknown