
September 10, 2026
11 min read
By Kokil Thapa | Last reviewed: September 2026
Your API sits in Kathmandu. A user in Sydney waits 400 ms before PHP even runs. That round-trip cost is predictable, and it compounds on every request. This Cloudflare Workers: Edge Compute Guide shows how to run JavaScript at Cloudflare's 300+ PoPs so logic executes near the user—not near your origin. If you already use Cloudflare CDN setup and best practices, Workers are the next step: programmable edge, not just cached static files.
What is Cloudflare Workers and how does edge compute work?
Cloudflare Workers are serverless functions that run on Cloudflare's edge network. They use V8 isolates—not containers—so cold starts measure in single-digit milliseconds. Each Worker receives a fetch event, processes the request, and returns a Response.
Think of Workers as middleware with global reach. They sit between the browser and your API development stack. You can rewrite headers, enforce rate limits, serve cached JSON, or proxy to a Laravel backend in Nepal.
The runtime supports the standard Web APIs: fetch, Request, Response, Headers, URL, crypto, and TextEncoder. Node.js compatibility mode covers many npm packages, but not everything. Check the package before you depend on it.
Official docs live at developers.cloudflare.com/workers. The runtime API reference is at developers.cloudflare.com/workers/runtime-apis.
Core building blocks
- Workers — stateless JavaScript/TypeScript functions triggered by HTTP requests.
- Workers KV — eventually consistent key-value store for config, feature flags, and cached blobs.
- R2 — S3-compatible object storage with zero egress fees through Workers.
- Durable Objects — strongly consistent state with single-threaded coordination (chat rooms, locks, counters).
- Queues — async message processing between Workers and external systems.
For a storage cost breakdown, see our Cloudflare R2 vs AWS S3 cost breakdown. R2 pairs well with Workers when you serve files or cache API payloads at the edge.
How do you deploy your first Cloudflare Worker in 2026?
Wrangler is Cloudflare's CLI. Install it with npm 12 and Node.js 26 LTS on your dev machine. Production deploys can run through GitHub Actions or GitLab CI—the same pattern I use for Laravel sites on shared EC2.
Step 1: Install Wrangler and authenticate
npm install -g wrangler
wrangler login
wrangler whoami Step 2: Scaffold a project
npm create cloudflare@latest my-edge-api
cd my-edge-api
npm install Choose the "Hello World" Worker template. Wrangler creates wrangler.toml, src/index.js, and a package.json.
Step 3: Write a minimal Worker
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (url.pathname === "/health") {
return new Response(JSON.stringify({ ok: true }), {
headers: { "Content-Type": "application/json" },
});
}
if (url.pathname === "/api/rates") {
const cached = await env.RATES_KV.get("npr-usd", "json");
if (cached) {
return Response.json(cached, {
headers: { "X-Cache": "HIT" },
});
}
}
return fetch(request);
},
}; This pattern mirrors what you'd build with a Nepal forex rates tool—serve cached JSON at the edge and fall back to origin on miss.
Step 4: Configure bindings in wrangler.toml
name = "my-edge-api"
main = "src/index.js"
compatibility_date = "2026-01-01"
[[kv_namespaces]]
binding = "RATES_KV"
id = "your-kv-namespace-id"
[vars]
ORIGIN_URL = "https://api.example.com" Step 5: Deploy and verify
- Run
wrangler devlocally with hot reload. - Run
wrangler deployto push to Cloudflare's network. - Attach a route:
wrangler routes add api.example.com/*or set it in the dashboard. - Test with curl from multiple regions using a VPN or an external monitor.
Store secrets with wrangler secret put JWT_SECRET. Never commit secrets to git. This matches how I handle .env files on Laravel deploys with Deployer 7.
When should you choose Cloudflare Workers over traditional server compute?
Not every workload belongs at the edge. Workers excel at request-scoped logic with low CPU time. They struggle with heavy computation, large file processing, or workloads needing a full PHP runtime.
| Criteria | Cloudflare Workers | AWS Lambda | Origin (Laravel/VPS) |
|---|---|---|---|
| Cold start | ~0–5 ms (V8 isolate) | 50–500+ ms (container) | Always warm if running |
| Global latency | Runs at nearest PoP | Regional unless CloudFront paired | Single region unless multi-region |
| Runtime | JavaScript/TypeScript (+ WASM) | Many languages | PHP, anything you install |
| CPU time limit | CPU ms per request (plan-dependent) | Up to 15 min | No hard limit |
| Database access | HTTP to DB proxy (Hyperdrive) or D1 | VPC peering to RDS | Direct MySQL/PostgreSQL |
| Best for | Auth gates, caching, routing, BFF APIs | Batch jobs, heavy backend logic | CRUD apps, queues, admin panels |
For a deeper side-by-side, read our Cloudflare Workers vs AWS Lambda comparison. The short version: Workers win on latency-sensitive request middleware. Lambda wins on long-running jobs and polyglot backends.
On a booking platform like Adventure Third Pole Trek, I'd keep availability checks and payment webhooks on Laravel. I'd move geo-based currency display and CDN cache key logic to Workers.
Long-running imports belong in a queue. See Laravel cron job vs queue worker when to use each for that split. Workers are not a replacement for Horizon or Supervisor.
How do you integrate Cloudflare Workers with Laravel and PHP backends?
Laravel stays on your VPS or managed host. Workers sit in front as a backend-for-frontend layer or a smart reverse proxy. PHP 8.5 and Laravel 13 run at origin. JavaScript runs at the edge.
Pattern 1: Edge auth gate
Validate JWT or API keys at the PoP. Reject bad tokens before they hit your server. This cuts junk traffic and saves PHP-FPM workers.
async function validateBearer(request, env) {
const auth = request.headers.get("Authorization");
if (!auth || !auth.startsWith("Bearer ")) {
return new Response("Unauthorized", { status: 401 });
}
const token = auth.slice(7);
const valid = await verifyJwt(token, env.JWT_SECRET);
if (!valid) {
return new Response("Forbidden", { status: 403 });
}
return null;
} Pair this with the rate-limiting patterns in our API rate limiting and abuse prevention guide.
Pattern 2: Cache API responses at the edge
Fetch from Laravel on cache miss. Store JSON in KV or use the Cache API. Set short TTLs for semi-dynamic data.
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
let response = await cache.match(cacheKey);
if (!response) {
response = await fetch(env.ORIGIN_URL + url.pathname, request);
response = new Response(response.body, response);
response.headers.set("Cache-Control", "public, max-age=60");
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
return response; For endpoints that must never be cached, follow Cloudflare DNS cache bypass for API endpoints. One wrong cache rule breaks authenticated POST requests.
Pattern 3: Geographic routing
Cloudflare exposes request.cf.country. Route Nepal users to a local payment flow. Send others to Stripe. I've used similar logic for multi-currency eCommerce stores.
Pattern 4: WordPress and static sites
WordPress 7.1 sites benefit from Workers that strip cookies on anonymous page views. See WordPress Cloudflare integration for speed for the origin-side config. Workers handle the edge half.
For greenfield apps, web development in Nepal projects often combine Laravel 12/13 backends with Cloudflare for DNS, CDN, and Workers. The stack is boring and fast—that's the point.
What are common Cloudflare Workers pitfalls in production?
Workers look simple until traffic hits. These issues show up repeatedly on client projects and in my own deploys.
1. Treating KV like a real-time database
KV is eventually consistent. Writes can take up to 60 seconds to propagate globally. Use KV for config and cache. Use D1, Hyperdrive, or your origin MySQL 9.7 database for transactional data.
2. Exceeding CPU and subrequest limits
Each request has a CPU time budget. Chaining five origin fetches in one Worker adds latency and burns CPU. Aggregate at origin or use a single BFF endpoint instead.
3. Forgetting waitUntil for async work
Logging, cache writes, and analytics must use ctx.waitUntil(promise). Without it, the isolate terminates when the response is sent. Your log line never fires.
4. Caching authenticated responses
Never cache responses that include session cookies or user-specific JSON. Vary on cookie or bypass cache entirely for /api/me routes.
5. Debugging blind in production
Enable Workers Logs and Tail Workers. Pipe output to your existing monitoring stack. On Laravel origins, correlate edge request IDs with application logs.
Edge compute does not remove the need for origin hardening. Pair Workers with fail2ban vs Cloudflare for DDoS protection on your Ubuntu server. Cloudflare absorbs volumetric attacks. fail2ban still helps on direct-origin access.
For teams comparing edge orchestration options, K3s lightweight Kubernetes for the edge covers self-hosted edge clusters. Workers trade control for zero ops—a fair swap for most SMB sites.
Static frontends can live on Cloudflare Pages vs Netlify vs Vercel. Bind a Worker to the same hostname for API routes. One domain, one TLS cert, one bill.
Key Takeaways
- Deploy with Wrangler, route by hostname, and test from multiple regions before go-live.
- Use Workers for auth, caching, routing, and BFF aggregation—not heavy CRUD or long jobs.
- Keep Laravel, MySQL, and queue workers at origin; let Workers shave latency on the hot path.
- Treat KV as cache/config storage; use D1, Hyperdrive, or origin DB for transactional data.
- Set secrets via
wrangler secret putand never cache authenticated API responses. - Monitor with Workers Logs and correlate edge request IDs with origin application logs.
People Also Ask
Is Cloudflare Workers free?
Cloudflare offers a free tier with daily request limits suitable for prototypes and low-traffic APIs. Paid plans raise limits on requests, CPU time, and KV operations. Check current pricing on Cloudflare's site before budgeting—a busy API can outgrow free tier quickly.
Can Cloudflare Workers run PHP?
No. Workers run JavaScript, TypeScript, Rust (via WASM), and Python (beta). PHP runs at your origin server. The typical pattern proxies from Worker to a Laravel or WordPress backend over HTTPS.
What is the difference between Cloudflare Workers and Service Workers?
Browser Service Workers run in the user's browser for offline caching and push notifications. Cloudflare Workers run on Cloudflare's servers at the edge. Our JavaScript Service Workers for offline apps article covers the browser side. Both use the same fetch-event model but serve different layers.
How do Cloudflare Workers compare to Cloudflare Tunnel?
Workers process HTTP logic at the edge. Cloudflare Tunnel exposes private origin servers without opening inbound ports. They complement each other: Tunnel for secure origin connectivity, Workers for request processing. See Cloudflare Tunnel vs traditional VPN for the networking angle.
Ship faster at the edge
This Cloudflare Workers: Edge Compute Guide gives you the deploy path, integration patterns, and production guardrails to run logic globally without rebuilding your Laravel stack. Start with one route—a health check, a cache layer, or an auth gate—and expand from measured wins.
Need help wiring Workers into an existing Laravel app, WordPress site, or e-commerce platform? I deploy and maintain production stacks with Cloudflare, GitLab CI, and zero-downtime releases. Contact us to discuss your edge architecture, or explore speed optimization services if latency is already costing you conversions.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

