skip to content

In Cloudflare Workers, what does an ES module Worker export, and what do the fetch handler's request, env and ctx parameters carry?

level: juniorimportance: must knowfreq 75%

answer

  1. default export, not event listener
  2. one method per kind of input
  3. bindings arrive as a parameter
  4. fetch(request, env, ctx) returns a Response

basics

~20 s

An ES module Worker's default export is an object of handlers such as fetch and scheduled. fetch(request, env, ctx) gets the Request, env with bindings, vars and secrets, and ctx with waitUntil() and passThroughOnException(), and returns a Response.

solid answer

~40 s

A current Worker is an ES module whose `export default` is an object of handler methods: `fetch` for HTTP requests, `scheduled` for Cron Triggers, and others for inputs such as queues. For HTTP the runtime calls `fetch(request, env, ctx)` and expects a `Response`, or a promise of one, back. `request` is a standard `Request` with Cloudflare's `request.cf` metadata; `env` holds the bindings from the Wrangler file, such as a KV namespace, vars and secrets; `ctx` is the execution context with `ctx.waitUntil()` and `ctx.passThroughOnException()`. This replaces the deprecated `addEventListener("fetch")` Service Worker syntax, where bindings were globals and `respondWith()` and `waitUntil()` lived on the event. Durable Objects and gradual deployments need the module form.

code

javascript · 18 lines
javascript
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (url.pathname === "/top") {
      const top = (await env.RANKINGS.get("top", "json")) ?? [];
      return Response.json({ top });
    }
    return new Response("Not found", { status: 404 });
  },

  async scheduled(controller, env, ctx) {
    const scores = { ada: 42, lin: 57, grace: 50 };
    const top = Object.entries(scores)
      .sort((a, b) => b[1] - a[1])
      .map(([name]) => name);
    await env.RANKINGS.put("top", JSON.stringify(top));
  },
};

go deeper

for a junior

Recall the shape: export default with a fetch method, three parameters, a Response returned. Know that env carries bindings such as a KV namespace and ctx carries waitUntil().

for a middle

Explain what moved from the Service Worker syntax: globals to env, event.waitUntil() to ctx, respondWith() to a return value, and the scheduled listener to a scheduled() method.

for a senior

Show you know the traps in production code: env may be shared across requests, module scope is not per-request state, and destructuring ctx breaks its methods.

for a principal

Be ready to argue why a team should migrate remaining Service Worker syntax Workers: Durable Objects, newer bindings and gradual deployments all require the module format.

## What a Worker module exports A Cloudflare Worker written in the current format is an **ES module**. The runtime does not look for event listeners in it; it looks at the module's **default export** and calls methods on that export by name. Those methods are **handlers**: each one receives one kind of external input and is invoked from outside the Worker. For a leaderboard API Worker that also recomputes its rankings every hour, the default export carries two handlers: - `fetch(request, env, ctx)` answers HTTP requests such as `GET /top`. - `scheduled(controller, env, ctx)` runs when a **Cron Trigger** fires, here to rebuild the rankings. Other handlers exist for other inputs, such as a queue consumer or inbound email, and each has its own lesson. The shape stays the same: one exported object, one method per kind of input, and `env` and `ctx` arriving as the later parameters. ```javascript export default { async fetch(request, env, ctx) { const top = (await env.RANKINGS.get("top", "json")) ?? []; return Response.json({ top }); }, async scheduled(controller, env, ctx) { await env.RANKINGS.put("top", JSON.stringify(["lin", "grace", "ada"])); }, }; ``` ## The fetch handler's three parameters | Parameter | What it is | Leaderboard use | |---|---|---| | `request` | A standard `Request`: method, URL, headers, a one-use body stream, plus Cloudflare's `request.cf` metadata | Route on the URL path | | `env` | The Worker's **bindings**: KV namespaces, R2 buckets, D1 databases, Durable Object namespaces, service bindings, vars and secrets | `env.RANKINGS.get("top")` | | `ctx` | The **execution context**: `ctx.waitUntil()` and `ctx.passThroughOnException()`, plus newer members such as `ctx.props`, `ctx.exports` and `ctx.tracing` | Schedule work that runs after the response | The handler must return a `Response`, or a promise that resolves to one. Anything else fails the request: a handler that returns a plain string gets `TypeError: Incorrect type for Promise: the Promise did not resolve to 'Response'.` and the client sees a 500. `env` deserves one more note. While the Worker's configuration has not changed, the runtime may pass the **same `env` object** to many requests, so it is a place to read configuration and resources, never a place to store per-request data. Bindings can also be reached outside a handler by importing `env` from `cloudflare:workers`; the lesson on bindings covers when that helps. The default export may also be a class that extends `WorkerEntrypoint`, with `fetch()` as a method and `env` and `ctx` available as `this.env` and `this.ctx`. The RPC methods such a class can expose belong to the lesson on service bindings. ## The legacy Service Worker syntax Older Workers use the **Service Worker syntax**: the script registers `addEventListener("fetch", event => event.respondWith(handle(event.request)))`. Cloudflare marks this form deprecated but still runs it, and new features may not support it. Moving to modules changes five things: 1. `event.respondWith(promise)` becomes a `return` from `fetch()`. 2. `event.request` becomes the first parameter, `request`. 3. Bindings and vars stop being **globals** (`RANKINGS.get(...)`) and arrive on `env` (`env.RANKINGS.get(...)`). 4. `event.waitUntil()` and `event.passThroughOnException()` move to `ctx`. 5. `addEventListener("scheduled", ...)` becomes a `scheduled()` method on the default export. The reasons to migrate are concrete. With globals as bindings, the runtime must create a new JavaScript execution context for every request, while a module Worker can reuse one across requests. Durable Object classes require the module format, the D1, Workers AI, Vectorize, Workflows and Images bindings work only from module Workers, and gradual deployments need it too. ## Mistakes interviewers listen for - Reading a binding as a bare global inside a module Worker: there is no global `RANKINGS` there, only `env.RANKINGS`. - Calling `event.respondWith()` in a module handler: there is no event object, the handler returns the response. - Looking for bindings on `ctx`: `ctx` controls the invocation's lifecycle, `env` carries the resources. - Destructuring the context (`const { waitUntil } = ctx`), which detaches the method from `ctx` and throws `Illegal invocation`. - Sending HTTP traffic to a Worker whose export has no `fetch`: the request fails with `Handler does not export a fetch() function.` A good junior answer names the default export, the three parameters and the returned `Response`; a stronger one explains what moved when the Service Worker syntax gave way to modules, and why a team should finish that migration rather than keep two styles side by side.

  • What happens when an HTTP request reaches a Worker whose default export has no fetch method?
    The request fails rather than falling through: the runtime reports `Handler does not export a fetch() function.` and the client gets an error response, a 500 under `wrangler dev`. A Worker that exists only to run Cron Triggers can export just `scheduled()`, as long as nothing routes HTTP traffic to it.
  • Is env a fresh object for every request in a Cloudflare Worker?
    Not necessarily. While the Worker's configuration has not changed, the runtime may pass the same `env` object to many requests. Treat it as read-only configuration and resources; per-request data belongs in local variables, never on `env` or in module scope.
  • Can the default export of a Worker be a class instead of an object?
    Yes. `export default class extends WorkerEntrypoint` with an `async fetch(request)` method works, and the bindings and context are then `this.env` and `this.ctx`. The class form matters mostly when the Worker also exposes RPC methods to other Workers.

  • A module Worker reads its KV binding as a bare global, like RANKINGS.get().
  • A module Worker's fetch handler sends its response by calling event.respondWith().
  • The ctx parameter is where a Worker's bindings and secrets live.
  • A module Worker receives Cron Triggers through addEventListener('scheduled').
  • The fetch handler can return a plain string and the runtime wraps it in a 200.
  • The Service Worker syntax was removed and no longer runs at all.