The Fastify adapter integrates oRPC with Fastify, letting you mount oRPC alongside your existing Fastify routes.
Installation
npm install @orpc/server fastify
Basic usage
import Fastify from 'fastify'
import { RPCHandler } from '@orpc/server/fastify'
import { CORSPlugin } from '@orpc/server/plugins'
import { router } from './router'
const fastify = Fastify()
const handler = new RPCHandler(router, {
plugins: [new CORSPlugin()],
})
fastify.all('/orpc/*', async (request, reply) => {
const result = await handler.handle(request, reply, {
prefix: '/orpc',
context: { headers: request.headers },
})
if (!result.matched) {
reply.status(404).send('No procedure matched')
}
})
fastify.listen({ port: 3000 }, () =>
console.log('Listening on http://localhost:3000'),
)
handle(request, reply, options)
| Parameter | Type | Description |
|---|
request | FastifyRequest | The Fastify request object |
reply | FastifyReply | The Fastify reply object |
options.context | Initial context type | Context passed to middleware |
options.prefix | string (optional) | Strip this prefix before routing |
Returns { matched: true } or { matched: false }.
Fastify plugin
You can also register oRPC as a Fastify plugin:
import Fastify from 'fastify'
import { RPCHandler } from '@orpc/server/fastify'
import { router } from './router'
const fastify = Fastify()
const handler = new RPCHandler(router)
fastify.register(async (instance) => {
instance.all('/*', async (request, reply) => {
const result = await handler.handle(request, reply, {
context: { headers: request.headers },
})
if (!result.matched) {
reply.status(404).send('Not found')
}
})
}, { prefix: '/orpc' })
fastify.listen({ port: 3000 })
Options
Plugins to apply to the handler.
strictGetMethodPluginEnabled
Restricts non-mutation procedures to GET requests.
Low-level interceptors around the full request cycle.