Caching & CDN Strategy
Cache-Control headers, stale-while-revalidate, CDN purging, and serving a global audience fast
Skills taught: deployment.cache-control, deployment.cdn, deployment.stale-while-revalidate, deployment.cache-purging, deployment.etag
Why caching matters
A CDN (Content Delivery Network) caches your files in data centers around the world. When a user in Tokyo requests your app hosted in us-east-1, instead of traveling across the Pacific (150ms), they get the response from a Tokyo CDN edge node (5ms). But CDN caching only works if your server sets the right HTTP headers. Understanding Cache-Control is the difference between a CDN that helps and a CDN that silently passes every request to your origin.
Cache-Control header reference
Cache-Control: public, max-age=31536000, immutable
│ │ │ │
│ │ │ └─ Content will never change
│ │ │ (browser can skip revalidation)
│ │ └─ Cache for 1 year (31,536,000 seconds)
│ └─ Both browser AND CDN can cache this
└─ The header name
Common patterns:
Fingerprinted static assets (main.abc123.js, logo.def456.png):
Cache-Control: public, max-age=31536000, immutable
→ Cache forever — the URL changes when content changes
HTML pages:
Cache-Control: public, max-age=0, must-revalidate
→ Never serve stale HTML (users need the latest)
API responses (public, rarely changing):
Cache-Control: public, max-age=300, stale-while-revalidate=86400
→ Fresh for 5 minutes; serve stale for 24 hours while revalidating
User-specific data (authenticated):
Cache-Control: private, no-store
→ Only the user's browser caches this (CDN skips it)
No caching at all:
Cache-Control: no-cache, no-store, must-revalidate
→ Never cache (use sparingly — defeats the purpose of a CDN)
DIRECTIVES:
public → CDN and browser may cache
private → Only browser may cache (not CDN)
max-age=N → Cache is fresh for N seconds
s-maxage=N → CDN max-age (overrides max-age for CDNs only)
no-cache → Must revalidate before serving (not 'no caching'!)
no-store → Never store anywhere
immutable → Don't revalidate even when max-age expires (browser)
stale-while-revalidate=N → Serve stale while fetching fresh in background
Setting cache headers in your app
import express from 'express';
const app = express();
// Static assets: cache forever (Vite fingerprints filenames)
app.use('/assets', express.static('dist/assets', {
maxAge: '1y',
immutable: true,
// Adds: Cache-Control: public, max-age=31536000, immutable
}));
// HTML: never serve stale
app.get('/', (req, res) => {
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');
res.sendFile('dist/index.html');
});
// API: public data with stale-while-revalidate
app.get('/api/products', async (req, res) => {
res.setHeader('Cache-Control', 'public, max-age=300, stale-while-revalidate=86400');
const products = await db.query('SELECT * FROM products');
res.json(products);
});
// API: private/user data — CDN must not cache
app.get('/api/user/profile', requireAuth, async (req, res) => {
res.setHeader('Cache-Control', 'private, no-store');
const user = await db.query('SELECT * FROM users WHERE id = $1', [req.user.id]);
res.json(user);
});
// Vary header: tells CDN to store separate caches for different Accept-Encoding
// (prevents serving compressed content to clients that don't support gzip)
app.use((req, res, next) => {
res.setHeader('Vary', 'Accept-Encoding');
next();
});
Vite's asset fingerprinting
PROBLEM: If you cache main.js for 1 year, how do users get the new version?
VITE'S SOLUTION: Content hashing
Source file: src/main.tsx
Build output: dist/assets/main.BhJj3X.js ← hash of file content
When content changes: dist/assets/main.KpQr9Y.js ← different hash
Your index.html references the exact filename:
<script src="/assets/main.BhJj3X.js"></script>
When you deploy a new build:
→ index.html changes (no-cache, so browsers always get latest)
→ index.html references main.KpQr9Y.js
→ Browser sees a different URL → fetches the new file
→ Old cached main.BhJj3X.js is automatically abandoned
This is why you can safely cache hashed assets for 1 year:
The cache is NEVER invalidated (the URL just stops being used)
Vite config:
export default defineConfig({
build: {
rollupOptions: {
output: {
assetFileNames: 'assets/[name].[hash][extname]', // default
chunkFileNames: 'assets/[name].[hash].js', // default
},
},
},
});
CDN cache purging
# When you need to invalidate cached content immediately:
# Cloudflare: purge by URL or tag
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://myapp.com/api/products"]}'
# Purge all (use sparingly — causes CDN cold start):
# --data '{"purge_everything":true}'
# AWS CloudFront: create invalidation
aws cloudfront create-invalidation \
--distribution-id $CLOUDFRONT_DIST_ID \
--paths "/api/*" "/index.html"
# Cost: first 1,000 paths/month free, then $0.005 each
# Wildcard /api/* counts as 1 path
# Integrate into deploy script:
# After 'npm run build && deploy to S3':
npm run deploy
aws cloudfront create-invalidation \
--distribution-id $CLOUDFRONT_DIST_ID \
--paths "/index.html"
# (No need to invalidate /assets/* — Vite hashes those files)
Tip: stale-while-revalidate is one of the most underused performance tools. With Cache-Control: max-age=60, stale-while-revalidate=3600, the CDN serves the cached response immediately (0ms wait) while simultaneously fetching a fresh copy in the background. The NEXT request gets the updated version. Users never wait for an origin request. This pattern works great for product listings, blog posts, or any frequently-read but infrequently-changed data.
Frequently Asked Questions
Should I set up a CDN for a small app?
Yes, for free. Cloudflare's free plan is a full CDN — just change your domain's nameservers to Cloudflare, and your site is behind their CDN immediately. No configuration required. You get DDoS protection, SSL, caching, and global distribution. Even if you have 10 users, there's no reason not to.