Typorithm · medium

Bun.serve Routes

bun-routesbunrouteshttpparams
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Bun.serve Routes

0%

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.

01

routes maps patterns like "/api/users/:id" to handlers.

02

req.params holds the captured :id segment.

03

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 });
  },
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Param route

A path with :id declares a dynamic segment; the matched value appears on req.params.id.

"/api/users/:id": {

2. Method handler

Mapping HTTP verbs to handlers lets one route serve GET, POST, DELETE and others separately.

GET: req => Response.json({ id: req.params.id })

3. JSON response

Response.json serializes the object and sets Content-Type: application/json for you.

Response.json({ id: req.params.id })

4. Static route

A route value can be a pre-built Response object, served directly without a handler function.

"/health": new Response("ok")

5. Fallback fetch

The default fetch(req) handler catches any request that no route matched.

fetch(req) {

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Bun.serve Routes: Lesson & Practice · Typorithm | ApplyDjinn