Cloudflare Workers for Edge Performance
Cloudflare Workers run code at the edge, closer to your users. Learn how to use them for faster TTFB, A/B testing, and dynamic content.
Cloudflare Workers execute JavaScript at 300+ edge locations worldwide, bringing your server logic within milliseconds of every user. This can reduce TTFB from 200-500ms to under 20ms.
What Are Cloudflare Workers?
Workers are serverless functions that run at the edge — not in a centralized data center, but at the Cloudflare PoP (Point of Presence) closest to each user.
// A basic Worker
export default {
async fetch(request) {
return new Response('Hello from the edge!', {
headers: { 'content-type': 'text/html' },
});
},
};
Edge vs. Serverless vs. Traditional
| Architecture | TTFB (US user, US server) | TTFB (EU user, US server) |
|---|---|---|
| Traditional server | 50-100ms | 200-400ms |
| Serverless (Lambda) | 100-500ms (cold start) | 200-600ms |
| Cloudflare Worker | 5-20ms | 5-20ms |
Performance Use Cases
1. Edge-Side HTML Rendering
Generate pages at the edge instead of your origin:
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/') {
return new Response(renderHomepage(), {
headers: {
'content-type': 'text/html',
'cache-control': 'public, max-age=3600',
},
});
}
// Fall through to origin for other paths
return fetch(request);
},
};
2. Smart Caching and Rewriting
export default {
async fetch(request) {
const cache = caches.default;
let response = await cache.match(request);
if (!response) {
response = await fetch(request);
// Cache successful responses for 1 hour
if (response.ok) {
response = new Response(response.body, response);
response.headers.set('cache-control', 'public, max-age=3600');
await cache.put(request, response.clone());
}
}
return response;
},
};
3. Image Optimization at the Edge
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname.startsWith('/images/')) {
// Use Cloudflare Image Resizing
return fetch(request, {
cf: {
image: {
width: 800,
quality: 75,
format: 'avif',
},
},
});
}
return fetch(request);
},
};
4. A/B Testing Without Client-Side JavaScript
export default {
async fetch(request) {
const url = new URL(request.url);
// Determine variant from cookie or randomly assign
const cookie = request.headers.get('cookie') || '';
let variant = cookie.includes('ab=B') ? 'B' :
cookie.includes('ab=A') ? 'A' :
Math.random() < 0.5 ? 'A' : 'B';
// Rewrite to variant page
url.pathname = `/variants/${variant}${url.pathname}`;
const response = await fetch(url.toString());
// Set cookie for consistency
const newResponse = new Response(response.body, response);
if (!cookie.includes('ab=')) {
newResponse.headers.set('set-cookie', `ab=${variant}; path=/; max-age=86400`);
}
return newResponse;
},
};
5. Bot Detection and Security
export default {
async fetch(request) {
const userAgent = request.headers.get('user-agent') || '';
// Block known bad bots
if (/BadBot|Scraper/i.test(userAgent)) {
return new Response('Blocked', { status: 403 });
}
// Add security headers
const response = await fetch(request);
const secured = new Response(response.body, response);
secured.headers.set('X-Frame-Options', 'DENY');
secured.headers.set('X-Content-Type-Options', 'nosniff');
return secured;
},
};
Workers KV for Edge Data
Store data at the edge for sub-millisecond reads:
export default {
async fetch(request, env) {
const config = await env.CONFIG_KV.get('site-config', 'json');
return new Response(renderPage(config), {
headers: { 'content-type': 'text/html' },
});
},
};
Performance Impact
| Before Workers | After Workers | Improvement |
|---|---|---|
| TTFB: 300ms | TTFB: 15ms | 95% faster |
| Global variance: 100-500ms | Global variance: 10-25ms | Consistent worldwide |
| Origin requests: 100% | Origin requests: 10-20% | 80% reduction |
Monitor Your Edge Performance
Edge functions add a layer between users and your origin. Monitor both to ensure optimal performance.
Ready to stop wasting ad spend?
Track your landing page performance, monitor Core Web Vitals, and calculate exactly how much slow pages cost you.
Start Free — No Credit Card