Caching

Lesson 10 of 14 · 22 min

x
71%

HTTP Caching & Browser Behavior

Before your request even reaches your server, the browser may already have the answer. HTTP caching headers tell browsers and intermediaries what to cache, for how long, and when to revalidate. Cache-Control is the primary header. max-age=3600 caches the response for one hour. no-cache forces revalidation with the server before using a stored copy. no-store prevents caching entirely — use for sensitive data. ETag provides a fingerprint of the response content; on revalidation, the server returns 304 Not Modified if the ETag matches, saving bandwidth. Last-Modified and Expires are older headers still widely supported. For static assets (JS, CSS, images), use long max-age with cache-busting filenames (app.a1b2c3.js). For API responses, use short max-age or no-cache with ETag validation.

Before
No cache headers — browser re-fetches everything
// Server sends no caching directives
app.get('/api/config', (req, res) => {
  res.json({ theme: 'dark', locale: 'en' });
});
// Browser requests /api/config on every page load
After
Proper cache headers per resource type
// Static assets — cache for 1 year
app.get('/assets/*', (req, res) => {
  res.set('Cache-Control', 'public, max-age=31536000, immutable');
  res.sendFile(...);
});

// API — revalidate with ETag
app.get('/api/config', (req, res) => {
  const config = getConfig();
  const etag = hash(JSON.stringify(config));
  if (req.headers['if-none-match'] === etag) {
    return res.status(304).end();
  }
  res.set('Cache-Control', 'private, max-age=60');
  res.set('ETag', etag);
  res.json(config);
});

Key Takeaway

Cache-Control and ETag are your browser caching toolkit — long TTL for static assets, short or revalidated TTL for dynamic API responses.

PreviousNext Lesson