Router@rhythmjs/router
Router API reference
Route methods, response helpers, and fetch exports for @rhythmjs/router.
RhythmRouter#
new RhythmRouter<I, D>(options?)#- Create an HTTP router. It is a
Pipeline, likeRhythm, with request-time middleware and routes but no startup phase.Iis the context the router needs from its host (checked when mounted) andDis what its ownderive()calls add; both are usually inferred. Options arename, which labels failures (mounted router "name" failed), andtype(default"router"). There is noprefixoption. 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 inctx.params, typed from the path. A path that does not start with/throws aTypeError. 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()middlewarectx.paramsis an untypedRecord<string, string>, since several routes may match. Aderive()widens the context type for all routes. callback()#- The router as a
(ctx) => ctx | Promise<ctx>function, used bymount()andtoFetchHandler(). 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-8content type; status is optional. text(ctx, body, status?) / html(ctx, body, status?)#- Set a body with
text/plain; charset=utf-8ortext/html; charset=utf-8. error(ctx, status, message?)#- Set the status and a
text/plain; charset=utf-8message, 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
undefinedwhen the handler was called without one. Set whentoFetchHandler(app)is passed straight toBun.serveasfetch.
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
URLparser when the path needs normalising, so the result always matches it. searchParam(url, name)#- The first value of a query parameter, or
null, likenew URL(url).searchParams.get(name). It scans the string and falls back toURLSearchParamswhen 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 asfetchtoBun.servesoctx.serveris set. A response nothing touched becomes404 Not Found. It answers with a plainResponsewhen 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/statusCodewhen it is an integer from 400 to 599 (looking through thecausechain; the message is the body unless the error setsexpose: false), else a logged, masked500. Call it in your owntry/catcharound the fetch handler. fromFetch(handler)#- Wrap a
(request) => Responsehandler (Better Auth, tRPC, a webhook SDK) as a mountable. The returnedResponsebecomes the response: status, headers, body stream, and everySet-Cookie.
Path conditions#
From @rhythmjs/router/path.
pathIs(pattern)#- A condition for
mount(plugin, condition)that is true when the request path matchespattern, using the same rou3 patterns as routes. The HTTP method is not part of the match. A pattern without a leading/throws aTypeError.
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.