Skip to content
Caching

Lesson 10 of 14 · 22 min

x
10/14

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

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
1// Server sends no caching directives2app.get('/api/config', (req, res) => {3  res.json({ theme: 'dark', locale: 'en' });4});5// Browser requests /api/config on every page load
After
Proper cache headers per resource type
1// Static assets — cache for 1 year2app.get('/assets/*', (req, res) => {3  res.set('Cache-Control', 'public, max-age=31536000, immutable');4  res.sendFile(...);5});6 7// API — revalidate with ETag8app.get('/api/config', (req, res) => {9  const config = getConfig();10  const etag = hash(JSON.stringify(config));11  if (req.headers['if-none-match'] === etag) {12    return res.status(304).end();13  }14  res.set('Cache-Control', 'private, max-age=60');15  res.set('ETag', etag);16  res.json(config);17});

Exercise

For a static asset route set long-lived Cache-Control with immutable (plus hashed filenames). For a private API config route set private + short max-age or revalidation with ETag. Document why Authorization responses are sensitive to shared caches.

Previous

Progress is saved in this browser.

Next Lesson