Skip to the workspace
Pebellslearn by building
Workers and Workers KV  ›  Lesson

Request In, Response Out

Request/Response Handling 12 minA Worker's fetch handler reads the incoming Request — method, URL, headers and body — and must return exactly one Response with a status, headers and body.

cloudflare / Request In, Response Out

Explore each scene at your own pace.

01 · The rule

The rule

Request In, Response Out

Hoplink has three jobs: answer GET /cat with a redirect, answer POST /links by creating a new short link, and say "not found" to everything else. All three are the same shape of problem — read the incoming request, decide, and hand back a response.

The rule

Read the Request, decide, return exactly one Response.

A Request object carries everything the visitor sent:

  • request.method — "GET", "POST" and so on.
  • request.url — the full URL as a string. Wrap it in new URL(...) to get pathname and searchParams.
  • request.headers — read one with request.headers.get("user-agent").
  • The body — read it with await request.json() or await request.text(). A body is a stream, so it can be read once; use request.clone() first if two pieces of code need it.

A Response is what you give back: a body plus a status and headers. Three helpers cover most cases:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    if (request.method === "GET" && url.pathname === "/cat") {
      return Response.redirect("https://example.com/all-about-cats", 302);
    }
    if (request.method === "POST" && url.pathname === "/links") {
      const body = await request.json();
      return Response.json({ created: body.code }, { status: 201 });
    }
    return new Response("No such link", { status: 404 });
  },
};

Response.redirect sets the Location header for you, Response.json sets content-type: application/json, and new Response(body, { status, headers }) handles everything else.

The status code is the first thing a browser, a crawler or another program reads, so choose it with care. 2xx means it worked, 3xx means "look elsewhere", 4xx means the caller asked for something wrong, and 5xx means your Worker failed. Headers carry the rest of the instructions: cache-control says how long a copy may be kept, and content-type says how to read the body. For Hoplink, a 302 keeps the door open to change a link's target later, while a 301 tells browsers the move is permanent and they may remember it for a long time.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.