rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

RhythmRouter#

new RhythmRouter<I, D>(options?)#
Create an HTTP router. It is a Pipeline, like Rhythm, with request-time middleware and routes but no startup phase. I is the context the router needs from its host (checked when mounted) and D is what its own derive() calls add; both are usually inferred. Options are name, which labels failures (mounted router "name" failed), and type (default "router"). There is no prefix option.
get / post / put / patch / delete(path, ...handlers)#
Add one or more handlers for a method and a full path; multiple handlers compose left to right. The first handler may be a derive() that widens the context for the handlers after it; a route takes at most one. Matched parameters are in ctx.params, typed from the path. A path that does not start with / throws a TypeError.
use(middleware)#
Add router-level middleware. It wraps every route of this router, wherever it was added, and runs only when one of the router's routes matches the method and path. In use() middleware ctx.params is an untyped Record<string, string>, since several routes may match. A derive() widens the context type for all routes.
callback()#
The router as a (ctx) => ctx | Promise<ctx> function, used by mount() and toFetchHandler().
sources / parent / options#
Inherited from Pipeline.

A router mounts into a host with mount(router) from @rhythmjs/rhythm, optionally with a condition such as pathIs("/api/**"). After the router runs, the host's later middleware still runs. A router that matches nothing leaves the context untouched.

Response helpers#

From @rhythmjs/router/response.

json(ctx, data, status?)#
Serialize data as the body with an application/json; charset=utf-8 content type; status is optional.
text(ctx, body, status?) / html(ctx, body, status?)#
Set a body with text/plain; charset=utf-8 or text/html; charset=utf-8.
error(ctx, status, message?)#
Set the status and a text/plain; charset=utf-8 message, defaulting the message from the status code.
redirect(ctx, url, status?)#
Set the location header with a 302 default and no body. The status must be 301, 302, 303, 307 or 308, otherwise it throws a RangeError.
ctx.server#
Bun's server, or undefined when the handler was called without one. Set when toFetchHandler(app) is passed straight to Bun.serve as fetch.

The helpers are plain functions over ctx.response, exported from @rhythmjs/router/response. Context exports (RhythmHttpContext, RhythmResponse, RhythmResponseBody, createHttpContext, and toResponse) live at @rhythmjs/router/context.

URL helpers#

From @rhythmjs/router/url. Cheap reads from request.url that avoid new URL on the hot path.

pathnameOf(url)#
The path of a request URL. Falls back to the URL parser when the path needs normalising, so the result always matches it.
searchParam(url, name)#
The first value of a query parameter, or null, like new URL(url).searchParams.get(name). It scans the string and falls back to URLSearchParams when the query contains %, + or control characters.

Fetch exports#

From @rhythmjs/router/fetch.

toFetchHandler(app)#
Takes a Rhythm app (or a router) and returns (request: Request, server?) => Response | Promise<Response>, the raw primitive for composing and testing without a listener. Pass it as fetch to Bun.serve so ctx.server is set. A response nothing touched becomes 404 Not Found. It answers with a plain Response when every handler is synchronous (Bun accepts both), and errors always reject. It rejects at compile time an app that requires any input other than the HTTP context.
errorToResponse(error)#
Maps a thrown error to a Response: the error's own status/statusCode when it is an integer from 400 to 599 (looking through the cause chain; the message is the body unless the error sets expose: false), else a logged, masked 500. Call it in your own try/catch around the fetch handler.
fromFetch(handler)#
Wrap a (request) => Response handler (Better Auth, tRPC, a webhook SDK) as a mountable. The returned Response becomes the response: status, headers, body stream, and every Set-Cookie.

Path conditions#

From @rhythmjs/router/path.

pathIs(pattern)#
A condition for mount(plugin, condition) that is true when the request path matches pattern, using the same rou3 patterns as routes. The HTTP method is not part of the match. A pattern without a leading / throws a TypeError.
TypeScript
app.use(mount(fromFetch((request) => auth.handler(request)), pathIs("/api/auth/**")));
app.use(mount(adminRouter, pathIs("/admin/**")));

Subpath exports: @rhythmjs/router, ./context, ./fetch and ./path. The package is coupled to Bun on purpose; there are no runtime adapters. RhythmRouter wraps rou3, whose pattern rules are described in HTTP router.