CDN Setup & Edge Caching Guide
A well-configured CDN can reduce TTFB from 800ms to <50ms by serving assets from edge nodes close to users. The key is setting the right Cache-Control headers for each asset type and invalidating efficiently on deploy.
Cache-Control Header Recipes
# Static assets with content hash — cache forever # (JS/CSS/images with [hash] in filename) Cache-Control: public, max-age=31536000, immutable # HTML pages — revalidate every time Cache-Control: public, max-age=0, must-revalidate # API responses (non-sensitive) — cache 60 seconds Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=60 # Private data (user-specific) — browser only, no CDN Cache-Control: private, max-age=300 # Never cache (payments, real-time) Cache-Control: no-store # Service worker — always recheck Cache-Control: no-cache
CDN Provider Comparison
| Provider | PoPs | Edge Compute | Best For |
|---|---|---|---|
| Cloudflare | 310+ | Workers (V8) | Custom origin, WAF, global apps |
| Vercel | 100+ | Edge Functions | Next.js, React, frontend teams |
| CloudFront | 450+ | Lambda@Edge | AWS-native, S3 static sites |
| Fastly | 85+ | Compute (Wasm) | Enterprise, low-latency APIs |
| Netlify | 25+ | Edge Functions | JAMstack, static + serverless |
Cloudflare Page Rules Setup
# Cloudflare — via Terraform or API
resource "cloudflare_page_rule" "static_assets" {
zone_id = var.zone_id
target = "example.com/_next/static/*"
priority = 1
actions {
cache_level = "cache_everything"
edge_cache_ttl = 31536000 # 1 year at edge
browser_cache_ttl = 31536000 # 1 year in browser
}
}
resource "cloudflare_page_rule" "html" {
zone_id = var.zone_id
target = "example.com/*.html"
priority = 2
actions {
cache_level = "bypass" # Always revalidate HTML
}
} Cache Invalidation on Deploy (CI/CD)
# GitHub Actions: invalidate Cloudflare cache after deploy
- name: Purge Cloudflare cache
run: |
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://example.com/","https://example.com/sitemap.xml"]}'
env:
CF_ZONE_ID: ${{ secrets.CF_ZONE_ID }}
CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
# AWS CloudFront invalidation
- name: Invalidate CloudFront
run: |
aws cloudfront create-invalidation \
--distribution-id ${{ secrets.CF_DISTRIBUTION_ID }} \
--paths "/*" Vercel Edge Config (next.config.js)
// next.config.js — fine-tune Vercel CDN headers
module.exports = {
async headers() {
return [
{
source: '/_next/static/:path*',
headers: [{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
}],
},
{
source: '/(.*)',
headers: [
{ key: 'X-DNS-Prefetch-Control', value: 'on' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
],
},
];
},
}; Frequently Asked Questions
What is the difference between a CDN and edge computing?▼
A CDN (Content Delivery Network) caches static assets (HTML, CSS, JS, images) at edge nodes distributed globally, reducing latency by serving content from a node close to the user. Edge computing goes further — it runs server-side code at the edge node, enabling personalized responses, A/B testing, authentication, and dynamic content generation without round-tripping to an origin server. Vercel Edge Functions, Cloudflare Workers, and Fastly Compute are edge computing platforms. Traditional CDNs (CloudFront, CloudFlare in cache mode) primarily serve cached static content.
What Cache-Control headers should I use for different asset types?▼
Static assets with content hashes (app.abc123.js): `Cache-Control: public, max-age=31536000, immutable`. HTML files (no hash): `Cache-Control: public, max-age=0, must-revalidate` or `no-cache`. API responses: `Cache-Control: private, max-age=60` or `no-store` for sensitive data. Images with hashes: `public, max-age=31536000, immutable`. Service worker file (sw.js): `Cache-Control: no-cache` — always re-fetched so updates deploy immediately.
How do I invalidate CDN cache after a deployment?▼
The preferred approach is to use content-addressed filenames (app.[hash].js) — each deploy generates new URLs, so no invalidation is needed, and old files remain cached. For files with fixed names (HTML, sw.js), invalidate via the CDN API after deployment: AWS CloudFront CreateInvalidation, Cloudflare Cache Purge API, or Fastly instant purge. In CI/CD, call the invalidation API as a post-deploy step. Never rely on TTL alone for HTML files — always invalidate manually after deploy.
Should I use Cloudflare, CloudFront, or a platform CDN like Vercel?▼
Platform CDNs (Vercel, Netlify, Cloudflare Pages) are easiest — zero configuration, automatic edge deployment, and integrated edge functions. Use these if your stack supports them. Cloudflare (with custom origin) gives the most control: 300+ PoPs, advanced WAF, DDoS protection, Workers for edge logic, and R2 for storage. CloudFront (AWS) is best if you're already in AWS — integrates with S3, Lambda@Edge, Shield. For a new project, Cloudflare or a platform CDN is usually the right choice.
Related Products
on GumroadDevToolkit Starter Kit
A ready-to-deploy developer tools website with 12 built-in tools. Astro + Preact + Tailwind. Deploy to Cloudflare Pages for free. Built-in SEO, dark mode, and ad-ready layout.
Buy on Gumroad →Premium Workflow Pack
Production-grade workflows, architecture guides, and deployment scripts for teams that ship. 10 advanced CI/CD workflows (blue-green, canary, E2E, security), 5 architecture deep-dives, code review checklist, PR process guide, and 5 battle-tested Bash deployment scripts.
Buy on Gumroad →GitHub Actions CI/CD Templates Pack
12 production-ready GitHub Actions workflow templates covering Node.js, Python, Docker, multi-environment deployments, security scanning, and auto-changelog. Copy, paste, ship.
Buy on Gumroad →You Might Also Need
LLM Prompt Caching Calculator
Calculate cost savings from LLM prompt caching. Compare Anthropic Claude and OpenAI GPT-4 caching pricing. Estimate monthly savings based on call volume and cache hit rate.
Open free tool →
Web Performance Checklist
Interactive web performance checklist covering images, fonts, JavaScript, CSS, caching, and server. Check off items to track your score out of 100 and export as Markdown.
Open free tool →
Web Vitals Analyzer
Analyze and score Core Web Vitals. Enter LCP, INP, CLS, TTFB, and FCP values to get good/needs improvement/poor ratings with optimization tips.
Open free tool →
More Free Tools
Related Articles
CDN and Edge Caching 2026: Complete Guide to Content Delivery Networks and Edge Computing
Comprehensive guide to CDN and edge caching strategies for 2026. Covers Cloudflare, Fastly, Akamai, AWS CloudFront, edge functions, cache invalidation, real-time synchronization, and multi-CDN strategies with code examples.
Performance Optimization 2026: Complete Guide to Frontend, Backend, and Infrastructure
Comprehensive performance optimization guide for 2026 covering Core Web Vitals, JavaScript bundle optimization, server-side rendering, caching strategies, database query optimization, CDN configuration, and real-world benchmarks.
Caching Strategies for Web Developers: Browser, CDN, Server-Side, and Database
Complete guide to web caching strategies. Covers HTTP cache headers, CDN configuration, Redis/Memcached patterns, service workers, and database query caching with practical code examples and performance benchmarks.
Redis Caching Patterns for Node.js Applications
Master Redis caching in Node.js with practical patterns: cache-aside, write-through, cache invalidation, TTL strategies, pub/sub, and production-ready implementation with ioredis.
Redis Caching Patterns: Cache-Aside, Write-Through, and Beyond in 2026
A practical guide to Redis caching strategies: cache-aside, write-through, write-behind, TTL management, cache stampede prevention, and distributed caching patterns.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →