Skip to content
rest-rpc
Esc
↑↓navigate↵open⌘Jpreview
On this page

Framework Integration

Serve routes from Hono, Express or another framework.

Import from @rest-rpc/server for frameworks built on Fetch Request, such as Hono, and from @rest-rpc/server/node for ones built on Node’s IncomingMessage, such as Express and Fastify.

Route Handlers

createRouteHandlers() returns one handler per route, to register on the framework’s router. Use it when the framework should see each route, such as to apply its middleware per route:

import { Hono } from "hono";
import { createRouteHandlers } from "@rest-rpc/server";
import { router } from "./router.ts";

const app = new Hono();

for (const route of createRouteHandlers(router)) {
	app.on(route.method, route.path, (c) =>
		route.handle(c.req.raw, { context: { user: c.var.user } }),
	);
}
import express from "express";
import { createRouteHandlers } from "@rest-rpc/server/node";
import { router } from "./router.ts";

const app = express();

for (const route of createRouteHandlers(router)) {
	const method = route.method.toLowerCase() as
		"get" | "post" | "put" | "patch" | "delete";
	app[method](route.path, (req, res, next) => {
		route.handle(req, res).catch(next);
	});
}
type RouteHandler = {
	method: HttpMethod;
	/** The full path, with params as `:name`. */
	path: string;
	/** On Node: `(req, res, options?) => Promise<void>`, writing to `res`. */
	handle: (request: Request, options?: HandleOptions) => Promise<Response>;
	/** For `.static()` routes, the same response every time. */
	staticResponse?: Response;
};
  • Routes come with static segments first, so routers that match in order, such as Express, match /posts/latest before /posts/:id.
  • Rewrite :name params for a router that uses another syntax.

Catch-All Handler

createCatchAllHandler() handles every request under one framework route, and leaves the ones it doesn’t match to the framework:

import { Hono } from "hono";
import { createCatchAllHandler } from "@rest-rpc/server";
import { router } from "./router.ts";

const app = new Hono();
const handler = createCatchAllHandler(router);

app.all("/api/*", async (c) => {
	const result = await handler(c.req.raw, {
		mountPath: "/api",
		context: { user: c.var.user },
	});
	return result.matched ? result.response : c.notFound();
});
import express from "express";
import { createCatchAllHandler } from "@rest-rpc/server/node";
import { router } from "./router.ts";

const app = express();
const handler = createCatchAllHandler(router);

app.use("/api", (req, res, next) => {
	handler(req, res, { mountPath: "/api" }).then(
		({ matched }) => matched || next(),
		next,
	);
});
  • Pass the full mountPath the handler is mounted under. On Node it’s read from req.originalUrl, which Express keeps.
  • The Fetch handler resolves to { matched: true, response } or { matched: false }. The Node one writes to res and resolves to { matched }.

Handle Options

Both take these per request:

type HandleOptions = {
	/** The initial context the routes require, such as the framework's user. */
	context?: TContext;
	/** Only for the catch-all handler: the path it's mounted under. */
	mountPath?: `/${string}`;
	/**
	 * Path params, for when the URL doesn't contain the route path, such as
	 * after a rewrite. By default they're read from the framework, such as
	 * `req.params`, or the URL.
	 */
	params?: Record<string, string>;
	/**
	 * A body the framework already parsed, such as with `express.json()`. It's
	 * still validated.
	 */
	body?: unknown;
};

When created, both take the same interceptors, bodyCodecs, validation and sse options as createApp.

Errors and Interceptors

  • Route errors are sent as error responses.
  • Anything else thrown rejects handle or the handler, so pass it to the framework, as the Express examples do with next.
  • Framework middleware only sees the error response, not the error. To log errors, add interceptors, which run around each matched route:
const handlers = createRouteHandlers(router, {
	interceptors: [onError((error) => logger.error(error))],
});

Was this page helpful?