Tutorial · Step 2 of 12
Controllers & routing
Routes, params, response helpers, and composing controllers into one app.
On this page
A real controller#
A controller is a RhythmRouter: a chain of routes with full paths, so each route spells out /api/notes. Start the notes feature with an in-memory list — the database arrives in step 8:
// src/notes/notes.controller.ts
import { RhythmRouter } from "@rhythmjs/router";
import { error, json } from "@rhythmjs/router/response";
interface Note {
id: string;
title: string;
content: string;
}
const notes = new Map<string, Note>();
export const notesController = new RhythmRouter({ name: "notes" })
.get("/api/notes", (ctx) => {
json(ctx, [...notes.values()]);
})
.get("/api/notes/:id", (ctx) => {
const note = notes.get(ctx.params.id);
if (!note) return error(ctx, 404, "Note not found");
json(ctx, note);
})
.post("/api/notes", async (ctx) => {
const input = (await ctx.request.json()) as { title: string; content?: string };
const note: Note = { id: crypto.randomUUID(), title: input.title, content: input.content ?? "" };
notes.set(note.id, note);
json(ctx, note, 201);
})
.delete("/api/notes/:id", (ctx) => {
if (!notes.delete(ctx.params.id)) return error(ctx, 404, "Note not found");
ctx.response.status = 204;
});Mount it in the app module next to the starter controller: .use(mount(notesController)) (the modules step later wraps the controller and its service in a module of their own). A static segment always beats a param segment when both match, and ctx.params is typed from the path — :id gives ctx.params.id: string, and reading a name the path does not declare is a compile error.
The context and response helpers#
Every handler receives the HTTP context from @rhythmjs/router/context: the Web-standard ctx.request, Bun's ctx.server, a mutable ctx.response (status, headers, body), and the response helpers, plain functions imported from @rhythmjs/router/response that take the context first: json(ctx, data, status?), text, html, error(ctx, status, message?), and redirect(ctx, url, status?).
Query strings are the plain Web platform — no magic parsing:
.get("/api/notes", (ctx) => {
const q = new URL(ctx.request.url).searchParams.get("q") ?? "";
json(ctx, [...notes.values()].filter((n) => n.title.includes(q)));
})Middleware on a controller#
Controllers accept use() like the app does, and middleware wraps the routes of that router in registration order — the onion. A timing middleware wraps the matched route:
export const notesController = new RhythmRouter({ name: "notes" })
.use(async (ctx, next) => {
const start = performance.now();
await next(); // run the matched route
ctx.response.headers.set("x-elapsed", `${Math.round(performance.now() - start)}ms`);
})
.get("/api/notes", (ctx) => { /* ... */ });A router's middleware runs only when one of its own routes matches the method and path, so a guard in one controller never answers another controller's requests. A middleware that returns without calling next() short-circuits: nothing downstream runs. That is the entire control-flow story — no interceptors, pipes, or guards as separate concepts; each is just middleware placed at the right point in the chain.
Many controllers, one app#
An app is a stack of mounted controllers. mount() always continues with the next middleware once the router is done, and a request no router answered leaves the app untouched, which toFetchHandler turns into a plain 404 (text/plain):
import { Rhythm, decorate, mount } from "@rhythmjs/rhythm";
export const appModule = new Rhythm({ name: "app" })
.register(decorate(() => ({ appService })))
.use(mount(appController)) // GET /
.use(mount(notesController)); // /api/notes/*mount(plugin, condition) takes an optional second argument, a function of the context, and runs the plugin only when it returns true. pathIs(pattern) from @rhythmjs/router/path builds the common condition, for example mount(someRouter, pathIs("/internal/**")); later pages use conditions to keep documentation out of production.
Route patterns come from rou3: :param, :param?, *, and ** all work in any segment. See the router docs for matching details and static file serving.