Lesson 14 / 32

Writing a Fetch Handler

Build an edge function with the Request/Response fetch handler model, use bindings from env, and run it locally.

By · 15 years in web development

The fetch handler model

An edge function is usually written as a fetch handler: a function that receives a standard Request and returns a Response, or a promise of one. In the Cloudflare Workers module syntax you export a default object with an async fetch(request, env, ctx) method. env holds bindings: environment variables, secrets and handles to platform resources such as KV namespaces, queues or databases, declared in the project's Wrangler configuration rather than hard-coded. ctx.waitUntil(promise) lets work such as sending analytics continue after the response has been returned, without delaying the user. Because everything uses Web-standard Request and Response, the same handler shape runs on Deno, Bun and Node.js and inside several frameworks, which makes logic easy to test locally: build a new Request(...), call the handler, inspect the response. Routing is plain code on new URL(request.url), or a small router such as Hono.

A Worker you can run with plain Node.js

Node.js 18 and later ship the same Request and Response globals, so calling the handler directly works as a unit test.

// A Cloudflare Workers-style module: one fetch handler, Web-standard APIs only.
const worker = {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (url.pathname === '/hello') {
      const name = url.searchParams.get('name') ?? 'edge';
      return Response.json({ greeting: `Namaste, ${name}`, region: env.REGION });
    }
    return new Response('Not found', { status: 404 });
  },
};
export default worker;

// Node 18+ has the same Request/Response globals, so we can call it locally.
const res = await worker.fetch(new Request('https://example.com/hello?name=Ravi'), { REGION: 'local' }, {});
console.log(res.status, await res.text());
const miss = await worker.fetch(new Request('https://example.com/nope'), {}, {});
console.log(miss.status, await miss.text());

Output:

200 {"greeting":"Namaste, Ravi","region":"local"}
404 Not found

Declaring bindings in configuration

A minimal wrangler.json. The vars entry becomes env.REGION; the KV binding becomes env.CACHE. The compatibility date pins runtime behaviour so platform updates do not change your code silently.

{
  "name": "hello-edge",
  "main": "src/index.js",
  "compatibility_date": "2025-01-01",
  "vars": { "REGION": "global" },
  "kv_namespaces": [
    { "binding": "CACHE", "id": "<your-namespace-id>" }
  ]
}

Do not block the response on bookkeeping

Logging to an analytics endpoint with await fetch(...) before returning makes every user wait for it. Use ctx.waitUntil(fetch(...)) instead so the response goes out immediately and the platform keeps the isolate alive until the extra work finishes.

Quick check: In a Cloudflare Worker `fetch(request, env, ctx)`, what is `env` used for?

  • Reading bindings such as variables, secrets and KV namespaces
  • Setting the HTTP status code of the response
  • Accessing the Node.js `process` object
  • Choosing which PoP the request is routed to
Answer

Reading bindings such as variables, secrets and KV namespaces — `env` carries the bindings declared in configuration. The response status is set on the `Response` you return, and PoP routing is done by the network.