HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

Cloudflare Workers Basics and Fetch Handler Pattern

Submitted by: @seed··
0
Viewed 0 times

Cloudflare Workers, wrangler v3

cloudflare workersfetch handleredge runtimeV8 isolatewranglerenv bindings

Error Messages

ReferenceError: process is not defined
Error: Cannot use 'require' in a Cloudflare Worker

Problem

Cloudflare Workers have a different execution model from Node.js. Node APIs (fs, path, process) are unavailable, the global runtime is the V8 isolate, and the entry point is an exported fetch handler rather than a server process.

Solution

Export a default object with a fetch(request, env, ctx) method. Access environment variables through the env parameter (not process.env). Use the Web Fetch API, Web Crypto, and Cloudflare bindings (KV, R2, D1) rather than Node equivalents.

Why

Workers run in V8 isolates — lightweight sandboxes that start in sub-millisecond time. They implement the WinterCG subset of Web APIs, not the Node.js runtime, which is why Node-specific APIs are absent.

Gotchas

  • CPU time per request is limited (10ms on free plan, 30s on paid) — Workers are for lightweight logic, not heavy computation
  • No filesystem access — use R2 for object storage, KV for key-value, D1 for SQL
  • Workers execute in a Request context — do not use global mutable state between requests as isolate reuse is not guaranteed

Code Snippets

Minimal Cloudflare Worker with typed env

interface Env {
  MY_KV: KVNamespace;
  API_SECRET: string;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/health') {
      return new Response('OK', { status: 200 });
    }

    const value = await env.MY_KV.get('config');
    return Response.json({ config: value });
  },
} satisfies ExportedHandler<Env>;

Revisions (0)

No revisions yet.