Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Cloudflare Workers: Edge Compute Guide

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.

Edge Compute Request FlowUser BrowserSydney / EU / USCloudflare PoPWorker (V8)Auth, cache, rewriteKV / R2 lookupOrigin ServerLaravel / Node / WPEdge wins when logic runs here, not at originJWT validation, geo routing, bot filtering, A/B testsStatic asset transforms, API aggregation, rate limits
Cloudflare Workers edge compute routes requests through the nearest PoP before optional origin fetch

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

  1. Run wrangler dev locally with hot reload.
  2. Run wrangler deploy to push to Cloudflare's network.
  3. Attach a route: wrangler routes add api.example.com/* or set it in the dashboard.
  4. Test with curl from multiple regions using a VPN or an external monitor.
Worker Deploy PipelineLocal Devwrangler devGit PushGitLab CI / GH Actionswrangler deploySecrets via CI varsEdge PoPs300+ citiesPost-deploy checklist1. Route matches hostname + path pattern2. Secrets set: wrangler secret put API_KEY3. KV/R2 bindings point to correct namespace4. Test cache headers and error fallbacks
Deploy Cloudflare Workers through Wrangler locally or via CI for repeatable edge releases

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.

CriteriaCloudflare WorkersAWS LambdaOrigin (Laravel/VPS)
Cold start~0–5 ms (V8 isolate)50–500+ ms (container)Always warm if running
Global latencyRuns at nearest PoPRegional unless CloudFront pairedSingle region unless multi-region
RuntimeJavaScript/TypeScript (+ WASM)Many languagesPHP, anything you install
CPU time limitCPU ms per request (plan-dependent)Up to 15 minNo hard limit
Database accessHTTP to DB proxy (Hyperdrive) or D1VPC peering to RDSDirect MySQL/PostgreSQL
Best forAuth gates, caching, routing, BFF APIsBatch jobs, heavy backend logicCRUD 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.

Where Should This Logic Run?New feature requestEdge WorkerAuth, cache, rewriteLaravel originCRUD, Eloquent, adminQueue workerEmail, reports, importsRule of thumb for 2026 stacksEdge = fast path. Origin = business logic. Queue = slow path.See Laravel queue guide for slow-path patterns
Use this decision tree to split logic between Cloudflare Workers, Laravel origin, and queue workers

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.

Production GotchasKV eventual consistencyNot for live inventory countsCPU time exceededHeavy JSON transforms failCached auth responsesUser A sees User B dataMissing waitUntilSilent log and cache lossFix: test with wrangler tail + load testsUse /services/testing-and-optimization-in-nepal for origin-side auditsValidate JSON payloads with /tools/json-formatter during dev
Avoid these Cloudflare Workers production pitfalls before they reach live traffic

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 put and 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

Serverless JavaScript functions on Cloudflare's global edge network using V8 isolates, not containers. They handle HTTP requests at the nearest PoP before traffic reaches your origin.

Install Wrangler globally with npm 12 and Node.js 26 LTS, run wrangler login, then scaffold with npm create cloudflare@latest. Configure bindings in wrangler.toml, test locally with wrangler dev, deploy with wrangler deploy, and attach a route via wrangler routes add or the dashboard. Store secrets with wrangler secret put, never in git. Production deploys can run through GitHub Actions or GitLab CI for repeatable releases, the same CI pattern used for Laravel sites on shared EC2.

Cloudflare offers a free tier with daily request limits for prototypes and low-traffic APIs. Paid plans raise request, CPU, and KV limits. Check current Cloudflare pricing before budgeting.

No. Workers run JavaScript, TypeScript, Rust via WASM, and Python in beta. PHP 8.5 and Laravel 13 stay at your origin; the Worker proxies HTTPS requests to them.

Workers excel at request-scoped logic with low CPU time: auth gates, edge caching, routing, and BFF APIs with zero to five millisecond cold starts at the nearest PoP. They struggle with heavy computation, large file processing, long-running jobs, and full PHP runtimes. Keep CRUD apps, admin panels, queue workers, and Horizon jobs on your Laravel VPS or managed host. On a booking platform, availability checks and payment webhooks belong at origin; geo-based currency display and CDN cache key logic belong at the edge.

Laravel stays on your VPS while Workers sit in front as a BFF or smart reverse proxy. Common patterns: validate JWT or API keys at the PoP before PHP-FPM sees junk traffic; fetch from Laravel on cache miss and store JSON in KV or the Cache API with short TTLs; route by request.cf.country for Nepal payment flows versus Stripe elsewhere. For endpoints that must never be cached, bypass cache on authenticated POST routes. WordPress 7.1 sites can strip cookies on anonymous page views at the edge while origin handles PHP.

Workers KV is an eventually consistent key-value store for config, feature flags, and cached blobs. Writes can take up to sixty seconds to propagate globally, so it is wrong for transactional data. Use KV for semi-static JSON like forex rates at the edge, with origin fallback on miss. For transactional workloads, use D1, Hyperdrive, or your origin MySQL 9.7 database instead.

Five issues show up repeatedly: treating KV as a real-time database; chaining multiple origin fetches in one Worker, which burns CPU time and adds latency; forgetting ctx.waitUntil for async logging and cache writes, so work terminates when the response is sent; caching authenticated responses that include session cookies or user-specific JSON; and debugging blind without Workers Logs and Tail Workers. Correlate edge request IDs with Laravel application logs. Edge compute does not replace origin hardening with fail2ban on your Ubuntu server.

Workers use V8 isolates with roughly zero to five millisecond cold starts and run at every Cloudflare PoP globally. Lambda uses containers with fifty to five hundred plus millisecond cold starts and stays regional unless paired with CloudFront. Workers run JavaScript and TypeScript plus WASM; Lambda supports many languages. Lambda allows up to fifteen minutes CPU time; Workers have per-request CPU millisecond limits. Workers win on latency-sensitive request middleware. Lambda wins on long-running batch jobs and polyglot backends.

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, processing requests before they reach your origin. Both use the same fetch-event model with Request and Response Web APIs, but they operate at different layers. Browser Service Workers improve client-side resilience; Cloudflare Workers cut global round-trip latency for API and auth logic near the user.

Workers process HTTP logic at the edge—rewriting headers, enforcing rate limits, caching JSON, or proxying to your backend. Cloudflare Tunnel exposes private origin servers without opening inbound ports. They complement each other: Tunnel secures origin connectivity while Workers handle request processing at the PoP. Use both when you need private Laravel hosting plus programmable edge middleware.

R2 is S3-compatible object storage with zero egress fees through Workers, useful for serving files or caching API payloads at the edge. Durable Objects provide strongly consistent state with single-threaded coordination for chat rooms, distributed locks, and counters. Workers themselves stay stateless. KV, R2, and Durable Objects cover config, blobs, and coordinated state respectively. Queues handle async message processing between Workers and external systems.

Use wrangler secret put JWT_SECRET or similar from your terminal after deploy setup. Secrets bind to your Worker environment at runtime via the env parameter. Never commit secrets to git or wrangler.toml—the same discipline as keeping .env files out of Laravel repositories managed with Deployer 7. Rotate secrets independently of code deploys when credentials change.

Use the Cache API or KV. On cache miss, fetch from your ORIGIN_URL, clone the response, set Cache-Control with a short max-age like sixty seconds, and use ctx.waitUntil to cache.put without blocking the client response. For semi-dynamic endpoints, KV bindings like RATES_KV with json type work well. Return X-Cache HIT headers on KV hits. Never cache routes with session cookies or user-specific JSON. Bypass cache entirely for authenticated endpoints like /api/me.

Install Node.js 26 LTS and npm 12 on your dev machine. Install Wrangler globally with npm install -g wrangler, authenticate with wrangler login, and confirm identity via wrangler whoami. Scaffold projects using npm create cloudflare@latest, then run wrangler dev for local hot reload. Production deploys use wrangler deploy or CI pipelines like GitHub Actions and GitLab CI. Test deployed Workers from multiple regions with a VPN or external monitor after attaching hostname routes.

Share this article

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.

Quick Contact Options
Choose how you want to connect me: