rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Serve your first route#

The router uses Web-standard requests and a mutable response object; the final Response is created when the app is served. A router is a pipeline, not an app of its own: it has request-time use() middleware and routes, but no startup phase, and a Rhythm host app mounts it with mount(router). There is no server wrapper: toFetchHandler(app) turns the app into a plain (request, server?) => Promise<Response> handler, and Bun.serve in your own main.ts is the server.

TypeScript
import { Rhythm, mount } from "@rhythmjs/rhythm";
import { RhythmRouter } from "@rhythmjs/router";
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { json } from "@rhythmjs/router/response";

const router = new RhythmRouter().get("/users/:id", (ctx) => {
  json(ctx, { id: ctx.params.id });
});

const app = new Rhythm().use(mount(router));

const server = Bun.serve({ port: 3000, fetch: toFetchHandler(app) });
console.log(`listening on ${server.url}`);

mount widens the host's input to cover what the router needs (the request and the response), so the host needs no type arguments. Pass fetch: toFetchHandler(app) directly rather than wrapping it: Bun then hands its server to the handler, and every route sees it as ctx.server (for ctx.server?.requestIP(ctx.request), publish, upgrade). Called without a server, ctx.server is undefined.

Everything else composes into the same Bun.serve call by hand, with no magic between you and Bun: static files are Bun's built-in routes; WebSockets are @rhythmjs/ws, mounted next to the router and served by one websocket handler; and scheduled work is @rhythmjs/cron, started with the app.

Match paths#

Register routes with get, post, put, patch, and delete. Each takes a full path and one or more handlers; multiple handlers compose left to right like middleware. There is no prefix option: write the whole path on each route. A path that does not start with / throws a TypeError when the route is registered.

Patterns follow rou3, the router behind h3:

:name#
Exactly one segment, captured as ctx.params.name. :name? is optional, and :id(\d+) is constrained by a regex. Values are URI-decoded; a malformed escape does not match.
*#
An unnamed wildcard captured as ctx.params["0"]. It is not limited to one segment; it is greedy: /files/* matches /files/a and /files/a/b ("a/b"), and /a/*/c matches /a/x/y/c. It may also match nothing: /files/* matches /files, with no "0" param.
**#
The rest of the path, captured as ctx.params._, or under a name with **:name. /files/**:path gives params.path === "a/b/c.txt" for /files/a/b/c.txt.

A static segment always wins over a :param segment, regardless of registration order. Trailing slashes are ignored, matching is method-specific, and there are no dedicated HEAD or OPTIONS registration methods. Params are typed from the path: /users/:id gives params.id: string, :id? gives string | undefined, and reading a name that is not in the path is a compile error.

Compose routers#

A router is a pipeline, so it mounts into a host the same way as everything else, and a host can mount as many as it likes.

TypeScript
const users = new RhythmRouter({ name: "users" })
  .get("/api/users", (ctx) => json(ctx, []))
  .get("/api/users/:id", (ctx) => json(ctx, { id: ctx.params.id }));

const posts = new RhythmRouter({ name: "posts" }).get("/api/posts", (ctx) => json(ctx, []));

const app = new Rhythm().use(mount(users)).use(mount(posts));

router.use(middleware) wraps every route of that router, wherever it was added, and runs only when one of the router's own routes matches the method and path. A guard on users therefore never answers a request that belongs to posts, and a request that matches nothing never reaches it. If the middleware does not call next(), the route handlers do not run.

TypeScript
const admin = new RhythmRouter({ name: "admin" })
  .use(async (ctx, next) => {
    if (!ctx.request.headers.has("x-admin")) return error(ctx, 403);
    await next();
  })
  .get("/admin/stats", (ctx) => json(ctx, { users: 42 }));

To mount a router only for some requests, pass a condition: mount(admin, pathIs("/admin/**")), with pathIs from @rhythmjs/router/path. A router can also be mounted from a catch-all route of another router (outer.get("/api/**", mount(inner))).

Derive route context#

derive(fn) can be the router's use() argument, which widens the context for all its routes, or the first handler of one route, which widens it for that route only. A route takes at most one such derive-style handler, and it must come first; the handlers after it see the added fields typed.

TypeScript
import { derive } from "@rhythmjs/rhythm";
import { json } from "@rhythmjs/router/response";

const me = new RhythmRouter()
  .use(derive(() => ({ requestId: crypto.randomUUID() })))
  .get(
    "/me",
    derive(async (ctx) => ({ body: await ctx.request.json() })),
    (ctx) => json(ctx, { id: ctx.requestId, body: ctx.body }),
  );

The route context is strict: it has only what was added, so ctx.nope is a compile error. Startup values come from the host. Declare what a router expects from it in its type, new RhythmRouter<{ db: Db }>(), and the host supplies it with decorate. A host that does not would need it as input, and toFetchHandler rejects such an app at compile time.

Provide a fallback#

An unmatched request leaves the context untouched and the host carries on with its next middleware. If nothing wrote a response, toFetchHandler answers 404 Not Found as plain text. For a custom 404, add a final middleware to the host. After a plugin runs, mount always calls next(), so check whether a response was written.

TypeScript
const app = new Rhythm()
  .use(mount(users))
  .use((ctx) => {
    if (ctx.response.body === null) json(ctx, { success: false, status: 404, message: "Not Found" }, 404);
  });

Handle errors#

A route that throws makes the fetch handler reject. Errors thrown inside a mounted router are wrapped as mounted router "users" failed with the original as cause, so put filter() from @rhythmjs/middleware on the router, not the host. In your own fetch, errorToResponse(error) maps a thrown error to a status-aware response:

TypeScript
const handler = toFetchHandler(app);

Bun.serve({
  async fetch(request, server) {
    try {
      return await handler(request, server);
    } catch (error) {
      return errorToResponse(error);
    }
  },
});

It uses the error's own status or statusCode when that is an integer from 400 to 599, looking through the cause chain, and otherwise logs and answers a generic 500.

Wrap a fetch handler#

Libraries that expose a (request) => Response handler (Better Auth, tRPC, a webhook SDK) mount with fromFetch. Combine it with pathIs so the handler only sees its own paths.

TypeScript
import { fromFetch } from "@rhythmjs/router/fetch";
import { pathIs } from "@rhythmjs/router/path";

const app = new Rhythm()
  .use(mount(fromFetch((request) => auth.handler(request)), pathIs("/api/auth/**")))
  .use(mount(router));

The returned Response becomes the response: status, headers, body stream, and every Set-Cookie.

Write a response#

Set status, statusText, headers, and body on ctx.response. Bodies support strings, ArrayBuffer, Uint8Array, Blob, FormData, URLSearchParams, byte streams, and null.

For the common shapes, response helpers from @rhythmjs/router/response set the content type, body, and status in one call. They are plain functions over ctx.response, not context methods, so mixing both styles is fine, and later writes win.

TypeScript
router
  .get("/users/:id", (ctx) => {
    json(ctx, { id: ctx.params.id }, 200);
  })
  .get("/hello", (ctx) => {
    html(ctx, "<h1>hello</h1>");
  })
  .get("/gone", (ctx) => {
    error(ctx, 410);
  })
  .get("/old", (ctx) => {
    redirect(ctx, "/users/1", 301);
  });
  • json(ctx, data, status?): serializes data and sets application/json; charset=utf-8.
  • text(ctx, body, status?) / html(ctx, body, status?): bodies with text/plain; charset=utf-8 and text/html; charset=utf-8.
  • error(ctx, status, message?): sets the status and a plain-text message, defaulting the message from the status code (error(ctx, 404) → "Not Found").
  • redirect(ctx, url, status = 302): sets the location header and clears the body. The status must be 301, 302, 303, 307 or 308, and the URL is used as given, so never pass a user-supplied target without checking it.

See Serving files for static assets.