Requests, routing and responses
Build the shortener's three routes with URLPattern, Request and Response, and put validation and error handling in one place.
- lesson
- 03 of 08
- read
- 14 min
The shortener’s API has three operations: create a link, look one up, and follow one. This lesson implements them with the web-standard objects the runtime provides (URL, URLPattern, Request, Response) and no framework, and it routes every failure through one error boundary. Links are kept in a Map for now, which sets up the problem lesson 5 solves.
What happens when a handler throws
Here is a handler that trusts its input. Try it if you like; the rest of the lesson replaces it.
export default {
async fetch(request): Promise<Response> {
const body = (await request.json()) as { url: string };
return Response.json({ host: new URL(body.url).host });
},
} satisfies ExportedHandler<Env>;curl -i -X POST http://localhost:8791/api/links -d 'not json'HTTP/1.1 500 Internal Server Error
...The body is an HTML error page, and the dev server logs the cause:
12:10:09 AM [vite+] Internal server error: Unexpected token 'o', "not json" is not valid JSON
...In production the client would get Cloudflare’s error 1101, “Worker threw a JavaScript exception” (errors reference). In both cases a client that sent bad input is told the server broke, in a format an API client cannot parse. The Worker has to decide what its own error responses look like.
Errors that carry a status
Create a small module for the HTTP plumbing:
export class HttpError extends Error {
readonly status: number;
readonly headers: Record<string, string>;
constructor(status: number, message: string, headers: Record<string, string> = {}) {
super(message);
this.status = status;
this.headers = headers;
}
}
export async function readJsonObject(request: Request): Promise<Record<string, unknown>> {
let body: unknown;
try {
body = await request.json();
} catch {
throw new HttpError(400, "request body must be valid JSON");
}
if (typeof body !== "object" || body === null || Array.isArray(body)) {
throw new HttpError(400, "request body must be a JSON object");
}
return body as Record<string, unknown>;
}HttpError lets any function deep in a request say “this is a 400” by throwing, without building a Response itself. readJsonObject turns the two ways a JSON body can be wrong into two specific 400s. A request body is a stream and can be read once, so read it in one place.
A stand-in for storage
export type Link = { url: string; createdAt: string };
// Lives in one isolate's memory and disappears with it. Lesson 5 replaces it.
const links = new Map<string, Link>();
// Crockford's base32 alphabet: no i, l, o or u, so codes survive being read aloud.
const ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
export function newCode(length = 6): string {
const bytes = crypto.getRandomValues(new Uint8Array(length));
let code = "";
for (const byte of bytes) {
code += ALPHABET[byte % ALPHABET.length];
}
return code;
}
export function getLink(code: string): Link | undefined {
return links.get(code);
}
export function saveLink(code: string, link: Link): void {
links.set(code, link);
}The Map is the per-isolate cache from lesson 1 used as a database, which is wrong on purpose and will be shown failing at the end of this lesson.
newCode draws bytes from crypto.getRandomValues(), so codes cannot be predicted from earlier ones the way Math.random() output can. The alphabet has 32 characters, and 256 is a multiple of 32, so byte % 32 maps bytes to characters without favoring any of them. Six characters give 32^6 codes, a little over a billion.
The route table
src/index.ts is shown in three parts, top to bottom. First the types and the table:
import { HttpError, readJsonObject } from "./http.ts";
import { getLink, newCode, saveLink } from "./links.ts";
type RouteArgs = {
request: Request;
env: Env;
ctx: ExecutionContext;
params: Record<string, string | undefined>;
};
type Handler = (args: RouteArgs) => Response | Promise<Response>;
const routes: Array<[method: string, pattern: URLPattern, handler: Handler]> = [
["POST", new URLPattern({ pathname: "/api/links" }), postLink],
["GET", new URLPattern({ pathname: "/api/links/:code" }), showLink],
["GET", new URLPattern({ pathname: "/:code" }), followLink],
];URLPattern matches a URL against a pattern and extracts named groups such as :code. It is one of the web standards the runtime implements. A pattern that only specifies pathname accepts any host and query string. The patterns are built once in module scope, which is within the rules: constructing one involves no I/O, and losing it costs nothing.
Each handler receives a single object. Later lessons need env and ctx in some handlers, and this shape lets a handler pick what it uses without changing the others.
The error boundary and the dispatcher
export default {
async fetch(request, env, ctx): Promise<Response> {
try {
return await route(request, env, ctx);
} catch (err) {
if (err instanceof HttpError) {
return Response.json({ error: err.message }, { status: err.status, headers: err.headers });
}
console.error(err);
return Response.json({ error: "internal error" }, { status: 500 });
}
},
} satisfies ExportedHandler<Env>;
async function route(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const allowed: string[] = [];
for (const [method, pattern, handler] of routes) {
const match = pattern.exec(request.url);
if (!match) continue;
if (method === request.method) {
return handler({ request, env, ctx, params: match.pathname.groups });
}
allowed.push(method);
}
if (allowed.length > 0) {
throw new HttpError(405, "method not allowed", { Allow: allowed.join(", ") });
}
throw new HttpError(404, "not found");
}The fetch handler does nothing except call route and translate failures. An HttpError becomes a JSON response with its status and headers. Anything else is a bug: it is logged with console.error and the client gets a 500 that reveals nothing about the internals. The await in return await route(...) is required. Without it the promise would be returned before it rejects and the catch block would never run.
route walks the table. pattern.exec() returns null or a match whose pathname.groups holds the captured segments. If a path matches but the method does not, the response is 405 with an Allow header listing the methods that would work, which RFC 9110 requires. If no path matches, it is a 404.
The three handlers
async function postLink({ request }: RouteArgs): Promise<Response> {
const body = await readJsonObject(request);
const target = parseTarget(body.url);
const code = newCode();
const link = { url: target.href, createdAt: new Date().toISOString() };
saveLink(code, link);
return Response.json(
{ code, ...link, short: new URL(`/${code}`, request.url).href },
{ status: 201, headers: { Location: `/api/links/${code}` } },
);
}
function showLink({ params }: RouteArgs): Response {
const code = params.code ?? "";
const link = getLink(code);
if (!link) throw new HttpError(404, "no such link");
return Response.json({ code, ...link });
}
function followLink({ params }: RouteArgs): Response {
const link = getLink(params.code ?? "");
if (!link) throw new HttpError(404, "no such link");
return Response.redirect(link.url, 302);
}
function parseTarget(value: unknown): URL {
if (typeof value !== "string" || !URL.canParse(value)) {
throw new HttpError(400, "url must be an absolute URL");
}
const target = new URL(value);
if (target.protocol !== "http:" && target.protocol !== "https:") {
throw new HttpError(400, "url must use http or https");
}
return target;
}postLink answers 201 Created with a Location header pointing at the new resource, and includes the short URL in the body. Response.json() serializes the value and sets the content-type header.
parseTarget is where the security decision lives. A shortener sends browsers wherever the stored URL says, so the stored URL must be one you are willing to redirect to. Only http: and https: are accepted, which keeps javascript: and data: URLs out.
followLink redirects with 302 and not 301. A 301 is cacheable by default, so a browser that has seen it once may go straight to the target next time. That would skip the Worker, which means no visit count and no way to expire or change the link. A 302 is not cached unless you say so. The semantics of each redirect code are in RFC 9110, section 15.4.
Try it
With pnpm exec cf dev --port 8791 running:
curl -i -X POST http://localhost:8791/api/links -d '{"url":"https://developers.cloudflare.com/workers/"}'HTTP/1.1 201 Created
...
content-type: application/json
location: /api/links/c6kgrt
...
{"code":"c6kgrt","url":"https://developers.cloudflare.com/workers/","createdAt":"2026-11-28T22:09:55.706Z","short":"http://localhost:8791/c6kgrt"}Your code will differ. Follow it and look it up:
curl -i http://localhost:8791/c6kgrt
curl http://localhost:8791/api/links/c6kgrtHTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/workers/
...
{"code":"c6kgrt","url":"https://developers.cloudflare.com/workers/","createdAt":"2026-11-28T22:09:55.706Z"}Now the failures. A URL with the wrong scheme is a 400:
curl -X POST http://localhost:8791/api/links -d '{"url":"javascript:alert(1)"}'{"error":"url must use http or https"}A known path with the wrong method is a 405:
curl -i http://localhost:8791/api/linksHTTP/1.1 405 Method Not Allowed
...
allow: POST
...
{"error":"method not allowed"}A path that matches no route, such as /a/b/c, returns a 404 with {"error":"not found"}.
State that does not last
Add a blank line to src/links.ts, save, and follow the link again:
curl -i http://localhost:8791/c6kgrtHTTP/1.1 404 Not Found
...
{"error":"no such link"}The dev server reloaded the module and the Map started empty. In production the same thing happens whenever an isolate is evicted, and a link created in one isolate never exists in the others. Lesson 5 moves links to storage that lives outside the isolate.
Update the test
The echo is gone, so the test from lesson 2 needs a new assertion. One fact will stay true for the rest of the course:
import { SELF } from "cloudflare:test";
import { expect, it } from "vite-plus/test";
it("answers 404 for a code that does not exist", async () => {
const response = await SELF.fetch("https://example.com/zzzzzz");
expect(response.status).toBe(404);
expect(await response.json()).toEqual({ error: "no such link" });
});pnpm test and pnpm check should both pass.
When a router library earns its place
The dispatcher above is fifteen lines and will not grow in this course. A router library such as Hono starts paying for itself when a project has dozens of routes or needs middleware that composes, with authentication on one group of routes and CORS on another. Path parameters and request bodies that are typed and validated in one declaration are the other common reason. The cost is a dependency in your bundle and a layer between you and the platform’s Request and Response. For a Worker with a handful of routes, a table and URLPattern take less time to read than the library’s documentation.
Lesson 4 removes the hard-coded values in this code and protects link creation with a secret.
Exercises
curl -I http://localhost:8791/<code>sends aHEADrequest and currently gets a 405. MakeHEADwork on everyGETroute. The result is correct whencurl -Ion a code shows302with alocationheader, andcurl -I http://localhost:8791/api/linksstill shows405withallow: POST.- Add
DELETE /api/links/:code. It should answer204with an empty body when the code existed and404otherwise. AfterwardsGETon the same code returns 404, and aPUTto that path returns 405 with anallowheader that listsGETandDELETE. /favicon.icocurrently reachesfollowLinkand returnsno such link. Constrain:codewith a regular expression group in the pattern so that only six characters from the alphabet match. The result is correct whencurl http://localhost:8791/favicon.icoprints{"error":"not found"}and real codes still redirect.