An Introduction to Cloudflare Workers
Edge computing explained in plain terms, with examples and short snippets.
The Short & Simple Explanation
Imagine you could run a tiny piece of JavaScript not on your own server, and not in a single data center, but instantly on hundreds of data centers around the world, right at the edge of the internet.
That is a Cloudflare Worker. It is a serverless function that runs on Cloudflare's global network. When a user makes a request, it is handled by the data center closest to them, which creates very fast response times.
The Core Concept: The Edge
Traditional server-based applications run in one or a few locations. A user in one region may be routed to a server far away, and that adds latency. Cloudflare Workers run at the edge, meaning the code is deployed to hundreds of points of presence globally, which reduces latency.
Key Features & Why They Are Powerful
- Unmatched Performance & Low Latency: Response is served from the nearest PoP.
- Serverless: No servers, VMs, or containers to manage; just deploy code.
- Exceptional Scalability: The network scales automatically for traffic spikes.
- Cost Effective: Pay for requests and CPU duration; a generous free tier exists.
- Powerful Use Cases: Entire applications can be built with Durable Objects and Workers KV.
Common Use Cases
- A/B testing and percent based routing
- Authentication and authorization at the edge
- Smart routing and load balancing
- On-the-fly data transformation and HTML minification
- Custom caching strategies
- API aggregation and static site delivery
- Full applications using Durable Objects and Workers KV
How to Write a Basic Worker
A Worker is a module that listens for fetch events. Below are two short examples. First, the simple "Hello World" Worker, then a geo-redirect example.
Raw snippet
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
return new Response('Hello World from a Cloudflare Worker!', {
status: 200,
headers: { 'Content-Type': 'text/plain' },
});
}Highlighted snippet (visual)
"color:#e6b450;">addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); }); "color:#e6b450;">async "color:#e6b450;">function handleRequest(request) { "color:#e6b450;">return "color:#e6b450;">new Response('Hello World from a Cloudflare Worker!', { status: 200, headers: { 'Content-Type': 'text/plain' }, }); }
Geo-redirect example
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const country = request.cf.country;
// if (country === 'US') {
return Response.redirect('https://us.example.com/welcome', 302);
} else if (country === 'FR') {
return Response.redirect('https://eu.example.com/bienvenue', 302);
}
return fetch('https://example.com/default');
}"color:#e6b450;">addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); }); "color:#e6b450;">async "color:#e6b450;">function handleRequest(request) { "color:#e6b450;">const country = request.cf.country; // "color:#e6b450;">if (country === 'US') { "color:#e6b450;">return Response.redirect('https://us.example.com/welcome', 302); } "color:#e6b450;">else "color:#e6b450;">if (country === 'FR') { "color:#e6b450;">return Response.redirect('https://eu.example.com/bienvenue', 302); } "color:#e6b450;">return fetch('https://example.com/default'); }
Development and Deployment
Cloudflare provides Wrangler (CLI), a web Playground, and a Dashboard for analytics, secrets, and logs. A common workflow is to create a project, develop locally, then deploy to Cloudflare's network.
# Create a new project
npm create cloudflare@latest my-worker
cd my-worker
# Develop locally
npm run dev
# Deploy
npm run deployComparison to Other Services
| Service | Primary Model | Strength |
|---|---|---|
| Cloudflare Workers | Isolated V8 Runtime (Edge) | Ultra-low latency, global distribution, pay-per-use |
| AWS Lambda | Container-based (Regional) | Deep AWS integration, longer runtimes |
| Vercel Edge Functions | Edge (often on CF Workers) | Tight frontend platform integration |
| Netlify Functions | AWS Lambda-based (Regional) | Tight deployment workflow for frontend sites |
Summary
Cloudflare Workers are a platform for running serverless code at the edge. They are ideal when you need low latency, automatic scaling, and the ability to reduce load on an origin server. Modern features like Durable Objects and Workers KV let you build complex and stateful applications at the edge.