rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

A first look#

Startup values are added once with register. Middleware runs for each call. The resulting context carries your startup values, the caller's input, and anything derived along the way.

TypeScript
import { Rhythm, decorate } from "@rhythmjs/rhythm";

const app = new Rhythm<{}, { name: string }>()
  .register(decorate(() => ({ greeting: "Hello" })))
  .use((ctx) => {
    console.log(`${ctx.greeting}, ${ctx.name}`);
  });

await app.callback()({ name: "world" }); // Hello, world

Create a project#

Start from the template rather than wiring a project up file by file: it is a minimal, runnable application organized the way NestJS organizes its starter, expressed with Rhythm primitives. rhythmx clones it into a new directory, names the package after it, starts a fresh git history, and installs the dependencies. Every package is ESM and runs on Bun 1.2 or newer; the ecosystem is built on Bun's native APIs, with no runtime adapters.

Shell
bunx rhythmx new my-app
cd my-app

Leave the name off and rhythmx asks for it. Pass --no-install to skip bun install, or --template <git url or path> to start from a different template. Prefer to do it by hand? git clone https://github.com/rhythmjs/template my-app gives the same files, and GitHub's "Use this template" button works too.

Run it#

Start the watcher; the server answers on port 3000.

Shell
bun run dev # bun --watch src/main.ts

curl http://localhost:3000/ # Hello World!
curl http://localhost:3000/missing # {"success":false,"status":404,"message":"Not Found"}

What’s inside#

Five small files cover the whole Nest-style pattern: a module, a controller, a service, a spec, and your own server entry point.

Text
src/
  main.ts your own Bun.serve call over toFetchHandler(appModule)
  app.module.ts Rhythm instance: holds the service in its startup context, mounts the controller
  app.controller.ts RhythmRouter instance: routes and handlers
  app.service.ts plain object holding the business logic
  app.controller.spec.ts bun:test specs for the controller

The pattern#

The service holds business logic and knows nothing about HTTP. The module adds it to the startup context with decorate, which places it on the request context of everything mounted in that module. The controller declares that dependency in its context type, so handlers use ctx.appService with full type safety: the type-level equivalent of constructor injection.

TypeScript
export const appModule = new Rhythm({ name: "app" })
  .register(decorate(() => ({ appService })))
  .use(mount(appController));

The controller states what it needs from its host:

TypeScript
export const appController = new RhythmRouter<AppContext>().get("/", (ctx) => {
  text(ctx, ctx.appService.getHello());
});

A request nothing answers gets a plain 404 Not Found from toFetchHandler, so the module needs no 404 handler of its own.

Test it#

The controller spec avoids booting the whole application: runHttpMiddleware runs mount(appController) directly with a service placed on the context. Substituting a stub service proves the controller delegates instead of hardcoding responses.

Shell
bun test # bun test runner
bun run typecheck # tsc --noEmit
bun run check # prettier --check + oxlint + tsc

Grow the app#

Add a feature by repeating the pattern: a users.service.ts, a users.controller.ts router with full paths (/users/:id; routers have no prefix), add the service with another decorate in the module, and add .use(mount(usersController)). Validation, sessions, logging, CORS, and friends come from the Middleware, HTTP, Security, and Observability packages. Scheduled work comes from @rhythmjs/cron, mounted or started the same way.

Under the hood#

There is no scaffolding magic in the template: it is just the kernel and the router, which you could install and wire up yourself.

Shell
bun add @rhythmjs/rhythm @rhythmjs/router

The kernel alone composes middleware over any input. register runs once at startup; use runs per call; the typed context carries both.

TypeScript
import { Rhythm, decorate } from "@rhythmjs/rhythm";

const app = new Rhythm<{}, { name: string }>()
  .register(decorate(() => ({ greeting: "Hello" })))
  .use((ctx) => {
    console.log(`${ctx.greeting}, ${ctx.name}`);
  });

await app.callback()({ name: "world" }); // Hello, world

Serve HTTP#

The router registers routes with named parameters and mounts into a Rhythm host app with mount(); a plain Bun.serve call, written by you in your own main.ts, starts the host app. The host's input type is inferred from what it mounts, so there is nothing to declare. Run it with bun src/main.ts.

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

Add validation#

Ecosystem packages drop into the same chain. Here validate checks the body against a zod schema and exposes the typed output as ctx.valid.body; an invalid body answers 400 before the handler runs. It is the first handler of the route, and its type flows into the handler after it.

TypeScript
import { validate } from "@rhythmjs/middleware/validate";
import { z } from "zod";
import { json } from "@rhythmjs/router/response";

const createUser = z.object({ name: z.string().min(1) });

router.post("/users", validate("body", createUser), (ctx) => {
  json(ctx, ctx.valid.body, 201);
});

Where to go next#

Read the philosophy, or browse the package groups: Middleware, HTTP, Security, and Observability each document their modules and full API.