Edge Caching and Website Speed
Edge caching is storing content on CDN servers near the user. Instead of requesting from origin in Europe, a user in Asia gets a response from the nearest edge node in 10–30ms instead of 200–300ms.
Cloudflare: Cache Configuration
# Cache Rules via Cloudflare API
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets" \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
--data '{
"name": "Cache Rules",
"kind": "zone",
"phase": "http_request_cache_settings",
"rules": [
{
"expression": "(http.request.uri.path matches \"^/api/\")",
"action": "set_cache_settings",
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 60
},
"browser_ttl": {
"mode": "override_origin",
"default": 0
}
},
"description": "Cache API responses 60s"
},
{
"expression": "(http.request.uri.path matches \"\.(js|css|woff2|png|webp|avif)$\")",
"action": "set_cache_settings",
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 2592000
},
"browser_ttl": {
"mode": "override_origin",
"default": 31536000
}
},
"description": "Static assets: 30 days edge, 1 year browser"
}
]
}'
HTTP Cache-Control Headers
Proper headers at origin are the foundation for effective CDN caching:
# Nginx: static resources (with hash in name → forever caching)
location ~* \.(js|css|woff2|ico)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Vary "Accept-Encoding";
gzip_static on;
}
# Images
location ~* \.(jpg|jpeg|png|webp|avif|svg|gif)$ {
add_header Cache-Control "public, max-age=2592000"; # 30 days
add_header Vary "Accept";
}
# HTML: don't cache in browser, but allow CDN
location / {
add_header Cache-Control "public, max-age=0, s-maxage=300, must-revalidate";
# s-maxage=300: CDN caches for 5 minutes
# max-age=0: browser always validates freshness
}
# API endpoints: caching depends on data
location /api/products {
add_header Cache-Control "public, max-age=60, s-maxage=60";
add_header Vary "Accept-Language, Accept-Encoding";
}
# Private data — don't cache on CDN
location /api/user {
add_header Cache-Control "private, no-cache, no-store";
}
Next.js: Cache Management
// App Router: fetch with cache control
async function getProducts() {
const res = await fetch('https://api.mysite.com/products', {
next: {
revalidate: 300, // ISR: update every 5 minutes
tags: ['products'], // for on-demand revalidation
},
});
return res.json();
}
// On-demand revalidation via webhook (CMS)
// app/api/revalidate/route.ts
export async function POST(request: Request) {
const { secret, tag } = await request.json();
if (secret !== process.env.REVALIDATION_SECRET) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
revalidateTag(tag); // Invalidates all cache with this tag
return Response.json({ revalidated: true });
}
Varnish Cache: Server Cache Before Origin
# /etc/varnish/default.vcl
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "3000";
.connect_timeout = 5s;
.first_byte_timeout = 30s;
}
sub vcl_recv {
# Don't cache authorized requests
if (req.http.Authorization || req.http.Cookie ~ "session=") {
return (pass);
}
# URL normalization
set req.url = regsuball(req.url, "[?&](utm_source|utm_medium|utm_campaign|fbclid)=[^&]*", "");
# Remove unnecessary cookies for cached pages
if (req.url ~ "\.(css|js|png|jpg|webp|woff2)(\?.*)?$") {
unset req.http.Cookie;
}
}
sub vcl_backend_response {
# Force TTL for static
if (bereq.url ~ "\.(css|js|woff2)(\?.*)?$") {
set beresp.ttl = 30d;
set beresp.http.Cache-Control = "public, max-age=2592000";
}
# TTL for HTML
if (beresp.http.Content-Type ~ "text/html") {
set beresp.ttl = 5m;
}
}
Monitor Cache Hit Rate
# Cloudflare Analytics API
curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/analytics/dashboard" \
-H "Authorization: Bearer {token}" \
| jq '.result.totals.cached / .result.totals.requests * 100'
# Nginx: add X-Cache-Status header
add_header X-Cache-Status $upstream_cache_status;
# Check via curl
curl -I https://mysite.com/api/products | grep -i x-cache
# X-Cache-Status: HIT
# X-Cache-Status: MISS
# X-Cache-Status: BYPASS
Target Metrics:
- Static assets: Cache Hit Rate > 99%
- HTML pages: > 80%
- API responses (public): > 70%
Setup Cloudflare caching with Cache Rules and optimal headers — 1–2 working days.







