rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Follow the onion#

Middleware receives (ctx, next). Awaiting next() runs the remaining steps, then resumes the current step. Omitting it stops downstream execution.

TypeScript
const app = new Rhythm()
  .use(async (_ctx, next) => {
    console.log("before");
    await next();
    console.log("after");
  })
  .use(() => console.log("inside"));

await app.callback()();
// before → inside → after

Extend the context#

next() takes no arguments. To add fields to the request context, wrap a function in derive(): it runs your function (sync or async), merges the returned object into the context, and calls next() for you. The added fields are typed on every later step, inferred from what you return.

TypeScript
const app = new Rhythm<{}, { userId: string }>()
  .use(derive((ctx) => ({ user: { id: ctx.userId, name: "Ada" } })))
  .use((ctx) => console.log(ctx.user.name));

await app.callback()({ userId: "u1" });

Derived fields are request-scoped: each call starts from a fresh copy of the startup context. For values that live for the whole process, use register(decorate(...)) instead (see Startup context).

Run conditionally#

A plain middleware decides for itself whether to continue: skip the work and call next().

TypeScript
const app = new Rhythm<{}, { path: string }>().use(async (ctx, next) => {
  if (ctx.path.startsWith("/api")) console.log("api request");
  await next();
});

To run a whole pipeline only for some requests, give mount a condition: mount(plugin, (ctx) => boolean). When it returns false, the plugin is skipped and the call goes straight to next(). For HTTP, pathIs(pattern) from @rhythmjs/router/path builds the condition from the request path (see the router API).

TypeScript
import { mount } from "@rhythmjs/rhythm";
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/**")));

Handle errors#

Register an error-handling wrapper before the handlers it should protect. Wrap await next() in a try/catch to handle downstream failures. Use finally for per-call cleanup. Calling next() more than once in the same middleware dispatch rejects with an error.

TypeScript
const guarded = new Rhythm().use(async (_ctx, next) => {
  try {
    await next();
  } catch (error) {
    console.error("Pipeline failed", error);
    throw error;
  }
});

Errors thrown inside a mounted plugin are wrapped (mounted router "users" failed) with the original available as cause. A wrapper placed around mount() sees the wrapped error; one placed inside the router sees the original.

Strict context#

The context only has what was added. Reading ctx.user before a derive adds it is a compile error, and so is reading a field nothing ever added. Startup fields are visible to request middleware, but request fields are never visible to register.

Use the dispatcher directly#

compose(middleware) creates the standalone onion dispatcher that every pipeline is built on. It knows nothing about the startup context.

TypeScript
import { compose } from "@rhythmjs/rhythm";

const dispatch = compose<{ message: string }>([
  (ctx) => console.log(ctx.message),
]);
await dispatch({ message: "Hello" });