Skip to main content

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 ✓ Cloudflare setup ✓ Cache invalidation on deploy ✓ CDN comparison

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
Cloudflare310+Workers (V8)Custom origin, WAF, global apps
Vercel100+Edge FunctionsNext.js, React, frontend teams
CloudFront450+Lambda@EdgeAWS-native, S3 static sites
Fastly85+Compute (Wasm)Enterprise, low-latency APIs
Netlify25+Edge FunctionsJAMstack, 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.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Related Articles

Apr 2, 2026 · 22 min read

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.

Apr 2, 2026 · 25 min read

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.

Mar 26, 2026 · 16 min read

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.

Apr 2, 2026 · 11 min read

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.

Mar 27, 2026 · 18 min read

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.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →