1. Param route
A path with :id declares a dynamic segment; the matched value appears on req.params.id.
"/api/users/:id": {Typorithm · medium
Step 1 of 8 · intro card
Web & Sockets
Bun.serve({ routes }) maps URL patterns like "/api/users/:id" to per-method handlers that read req.params; a route value can also be a static Response. The top-level fetch(req) handler is the fallback for unmatched requests, and Response.json sends JSON.
Bun.serve takes a routes object whose keys are URL patterns. Patterns like "/api/users/:id" capture dynamic segments, exposed on req.params.id inside the handler.
A route can map HTTP methods (GET, POST, DELETE) to separate handlers, or be a single static Response such as new Response("ok") that Bun serves directly with no function call.
The top-level fetch(req) handler is the fallback that runs for any request no route matched, which is where you return a 404 or other catch-all response.
routes maps patterns like "/api/users/:id" to handlers.
req.params holds the captured :id segment.
fetch(req) is the fallback for unmatched requests.
Bun.serve({
routes: {
"/api/users/:id": {
GET: req => Response.json({ id: req.params.id }),
DELETE: req => new Response(null, { status: 204 }),
},
"/health": new Response("ok"),
},
fetch(req) {
return new Response("Not Found", { status: 404 });
},
});Connect each part of the code to the concept before you type.
A path with :id declares a dynamic segment; the matched value appears on req.params.id.
"/api/users/:id": {Mapping HTTP verbs to handlers lets one route serve GET, POST, DELETE and others separately.
GET: req => Response.json({ id: req.params.id })Response.json serializes the object and sets Content-Type: application/json for you.
Response.json({ id: req.params.id })A route value can be a pre-built Response object, served directly without a handler function.
"/health": new Response("ok")The default fetch(req) handler catches any request that no route matched.
fetch(req) {Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.