Skip to content
rest-rpc
Esc
navigateopen⌘Jpreview
On this page

Fastify

Use rest-rpc with Fastify

Install

pnpm add @rest-rpc/fastify

Usage

import { registerRoutes, router } from "@rest-rpc/fastify";
import Fastify from "fastify";
import { api } from "./contract";

const app = Fastify();

const routes = router(api, {
	todos: {
		list() {
			return listTodos();
		},
		get({ id, context }) {
			const authorization = context.req.headers.authorization;
			return getTodo(id, { authorization });
		},
		create({ title }) {
			return createTodo({ title });
		},
	},
});

registerRoutes(app, routes);

await app.listen({ port: 3000 });

Framework Context

type HttpRouteHandlerContext = {
	req: FastifyRequest;
	signal: AbortSignal;
};

type WebSocketRouteHandlerContext = {
	req: FastifyRequest;
};

Options

type RegisterRoutesOptions = {
	errorHandlers?: ServerErrorHandlers<{
		req: FastifyRequest;
		signal: AbortSignal;
	}>;
	webSocket?: FastifyWebSocketOptions;
};

Error Handlers

registerRoutes(app, routes, {
	errorHandlers: {
		onRequestValidationError: ({ issues }) => ({
			status: 422,
			body: { code: "VALIDATION_ERROR", issues },
		}),
		onUnhandledError: () => ({
			status: 500,
			body: { code: "INTERNAL_SERVER_ERROR" },
		}),
	},
});

WebSocket

import websocket from "@fastify/websocket";

await app.register(websocket);

registerRoutes(app, routes, {
	webSocket: {
		beforeUpgrade: ({ context }) => {
			const authorization = context.req.headers.authorization;
			return authorization ? undefined : { status: 401 };
		},
	},
});

Was this page helpful?