HTTP caching headers help browsers and servers save time and data by reusing stored responses instead of downloading them again.
HTTP caching headers (ETag, Cache-Control) in Express
res.set('Cache-Control', 'public, max-age=3600'); res.set('ETag', 'unique-identifier');
Cache-Control tells browsers how long to keep the response (in seconds).
ETag is a unique ID for the response content to check if it changed.
res.set('Cache-Control', 'no-store');
res.set('Cache-Control', 'public, max-age=86400');
res.set('ETag', '12345abcde');
This Express server sends JSON data with Cache-Control and ETag headers.
If the client sends the same ETag in If-None-Match, the server replies with 304 Not Modified, saving bandwidth.
import express from 'express'; const app = express(); app.get('/data', (req, res) => { const data = { message: 'Hello, world!' }; const jsonData = JSON.stringify(data); const etag = 'W/"' + Buffer.from(jsonData).toString('base64') + '"'; res.set('Cache-Control', 'public, max-age=60'); res.set('ETag', etag); if (req.headers['if-none-match'] === etag) { res.status(304).end(); } else { res.json(data); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
ETags help browsers know if content changed without downloading it again.
Cache-Control max-age is in seconds and controls how long to keep cached data.
Always test caching behavior using browser DevTools Network tab to see headers and responses.
HTTP caching headers improve website speed and reduce data usage.
Use Cache-Control to set how long browsers keep content.
Use ETag to identify content versions and avoid unnecessary downloads.