Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Workers

Requests, Responses and Routing in Cloudflare Workers

Build a Worker router: read the URL, method, headers and JSON body, return JSON and redirects, set status codes and CORS headers, and handle errors cleanly.

Every Worker lives or dies by how well it reads a Request and builds a Response. These are the same Fetch API objects you know from the browser, so the skills transfer in both directions. This lesson builds a small router: it inspects the method and path, parses a JSON body, returns JSON, redirects, and answers cross-origin requests correctly.

The runnable examples use real Request and Response objects, so they behave the way a deployed Worker does. Only the platform around them (deployment, bindings) is missing here.

Reading the request

Almost everything you need is on the Request:

JavaScript
export default {
  async fetch(request) {
    const url = new URL(request.url);
    url.pathname;                         // "/api/users"
    url.searchParams.get("page");         // "2"
    request.method;                       // "GET", "POST", ...
    request.headers.get("user-agent");
    request.headers.get("cf-connecting-ip");   // visitor IP, added by Cloudflare
    request.cf?.country;                  // "DE": Cloudflare adds a `cf` object
    return new Response("ok");
  },
};

Cloudflare adds extra information to requests: CF-Connecting-IP (the visitor's address), CF-IPCountry (country code) and a request.cf object with fields such as country, city, colo (the data center code) and asn. These exist only on the real platform, so in a stand-in you fake them.

Reading bodies uses the standard methods: await request.json(), request.text(), request.formData(), request.arrayBuffer(). A body can be read once; call request.clone() first if two parts of your code need it.

Building responses

JavaScript
new Response("plain text");                                   // 200, text/plain
Response.json({ ok: true }, { status: 201 });                 // JSON helper
Response.redirect("https://example.com/new", 301);            // redirect
new Response(null, { status: 204 });                          // empty
new Response("nope", { status: 404, headers: { "cache-control": "no-store" } });

Response.json() sets the content-type: application/json header for you. Headers on a response you got from fetch() are immutable; to change them, copy the response: new Response(res.body, res) and then edit .headers.

A routing pattern

You can use a framework (Hono is popular on Workers, with a tiny footprint), but the plain pattern is worth knowing because everything else builds on it: match on method and path, return early, and have one fallback.

JS A tiny router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

URLPattern is available in Workers and in modern runtimes; it matches paths such as /api/users/:id and gives you the named groups. If your browser does not support it, the example may report an error: the code is still what you would write in a Worker.

CORS

When a page on https://app.example.com calls your Worker at https://api.example.com, the browser sends an Origin header and, for non-simple requests, a preflight OPTIONS request first. Your Worker must answer both. The rules:

  1. Answer OPTIONS with 204 and the Access-Control-Allow-* headers.
  2. Add Access-Control-Allow-Origin to every real response too.
  3. Never reflect any origin blindly if the API uses cookies; check the origin against an allow-list.
JS CORS helper with an allow-list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the vary: origin header: without it a cache could serve one origin's CORS headers to another. This ties into caching rules.

Errors and status codes

Unhandled exceptions in a Worker produce a generic error page (HTTP 500, usually shown as Cloudflare error 1101). Wrap risky work and return something useful:

JavaScript
export default {
  async fetch(request, env, ctx) {
    try {
      return await handle(request, env, ctx);
    } catch (err) {
      console.error("unhandled", err);            // visible in logs and `wrangler tail`
      return Response.json({ error: "Internal error" }, { status: 500 });
    }
  },
};

Good API habits: 400 for invalid input, 401/403 for authentication and permission, 404 for unknown routes, 405 with an Allow header for a wrong method, 429 for rate limiting, 5xx only for your own faults. Never put internal error text in a response body.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many times can you read a request body without cloning it?

    A body is a stream that is consumed when read. Use request.clone() if you need to read it twice.
  2. 2. A browser sends an OPTIONS request before a cross-origin POST with a JSON body. What should the Worker return?

    That is the CORS preflight. Answer it quickly with the allowed methods and headers, then send the real response with Access-Control-Allow-Origin as well.
  3. 3. Why add 'Vary: Origin' when you echo an allowed origin?

    Without Vary, a shared cache could hand one origin's Access-Control-Allow-Origin value to a different origin.
  4. 4. Which is the helper for returning JSON with the right content type?

    Response.json() serializes the value and sets content-type: application/json.

Summary

  • A Worker reads a standard Request (URL, method, headers, one-time body) and returns a standard Response.
  • Cloudflare adds CF-Connecting-IP, CF-IPCountry and request.cf to incoming requests.
  • A router is a loop over method and path matches (URLPattern or a framework like Hono) with a 404 fallback.
  • Handle CORS preflights with 204 and a strict allow-list, and add Vary: Origin.
  • Catch exceptions, log them, and return a clean error response.

Next: Subrequests and the Cache API