Skip to content

Cloudflare Workers Introduction -- Serverless at the Edge

DodaTech 4 min read

In this tutorial, you'll learn about Cloudflare Workers Introduction. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Cloudflare Workers is a Serverless execution environment that runs JavaScript, TypeScript, or WebAssembly at over 330 data centers worldwide, enabling you to modify HTTP traffic, build APIs, and create dynamic applications without managing any infrastructure.

Why Cloudflare Workers Matters

Traditional server-based applications require provisioning, scaling, patching, and monitoring infrastructure. Workers eliminates all of that by running your code on Cloudflare's global edge network, close to your users. This reduces latency from hundreds of milliseconds to single digits, improves reliability through geographical redundancy, and scales automatically from zero to millions of requests without any configuration changes. For developers building with Cloudflare, Workers is the compute layer that unlocks the full power of the edge.

Real-world use: A weather API built with Workers serves forecast data from the nearest edge location, cutting response times from 200ms to under 10ms for users worldwide. The same Workers script caches responses in Workers KV with a 60-second TTL, reducing origin load by 95 percent.

Workers Architecture

flowchart LR
    U[User Request] --> E[Cloudflare Edge 330+ locations]
    E --> R[Workers Runtime]
    R --> K[Workers KV]
    R --> D[Durable Objects]
    R --> S[R2 Storage]
    R --> Q[Queues]
    R --> O[Origin Server]
    E --> C[Cache Layer]
    style E fill:#f90,color:#fff
    style R fill:#f90,color:#fff

Your First Worker

A Worker is simply a JavaScript module that listens for fetch events and returns a Response.

export default {
  async fetch(request) {
    const url = new URL(request.url);
    const name = url.searchParams.get('name') || 'Visitor';
    const body = JSON.stringify({ greeting: `Hello, ${name}!`, region: request.cf?.colo });
    return new Response(body, {
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

Expected output: Visiting https://my-worker.example.workers.dev?name=Maria returns {"greeting":"Hello, Maria!","region":"LHR"}. The request.cf.colo property reveals which Cloudflare data center handled the request.

Module Syntax vs Service Worker Syntax

Workers supports two syntax styles. Module syntax (shown above) is the modern, recommended approach.

// Service Worker syntax (legacy)
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  return new Response('Hello from legacy Workers!', {
    status: 200,
    headers: { 'Content-Type': 'text/plain' }
  });
}

Expected output: Any request returns Hello from legacy Workers! as plain text. Service Worker syntax is deprecated in favor of module syntax.

Returning Different Content Types

Workers can return HTML, JSON, XML, images, or streams. Here is an HTML response with dynamic content.

export default {
  async fetch(request) {
    const day = new Date().toLocaleDateString('en-US', { weekday: 'long' });
    const html = `<!DOCTYPE html>
<html>
<head><title>Worker Page</title></head>
<body>
<h1>Today is ${day}</h1>
<p>Served from ${request.cf?.colo} data center.</p>
</body>
</html>`;
    return new Response(html, {
      headers: { 'Content-Type': 'text/html' }
    });
  }
}

Expected output: Returns a full HTML page displaying the current day of the week and the serving data center code (e.g. LHR, IAD, NRT).

Common Errors

Error Cause Fix
SCRIPT_ERROR Uncaught exception in Worker code Wrap risky operations in try/catch
EXCEEDED_CPU Worker exceeded 50ms CPU time (10ms on free) Optimize loops, use waitUntil for background tasks
EXCEEDED_MEMORY Response body exceeds 128MB Stream large responses instead of buffering
Unexpected token Invalid JavaScript syntax or missing semicolons Validate code with ESLint before deploying
Cannot read properties of undefined Accessing request.cf without checking Guard with request.cf?.colo optional chaining

Practice Questions

  1. What is the key difference between module syntax and Service Worker syntax in Cloudflare Workers?
  2. How does running code at Cloudflare's edge reduce latency compared to traditional servers?
  3. What HTTP response status code does a Worker return by default if no response is constructed?

FAQ

{{< faq "What is the free plan CPU limit for Cloudflare Workers?">}} The free plan allows 100,000 requests per day with a 10ms CPU time limit per request. Paid plans increase this to 50ms CPU time and millions of requests per day. {{< /faq >}}

{{< faq "Can I use npm packages in Cloudflare Workers?">}} Yes, Workers supports npm packages that are compatible with the Workers runtime. Use wrangler.toml to specify dependencies or bundle them with esbuild during deployment. {{< /faq >}}

Summary

Cloudflare Workers runs your code at 330+ edge locations, eliminating server management while delivering sub-10ms response times. You write JavaScript modules that handle HTTP requests and return responses, scaling automatically from zero to global traffic. This technology powers projects like Doda Browser's privacy proxy and Durga Antivirus Pro's threat feed aggregation. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro -- security-first tools for the modern web.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro