Skip to main content
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)

ParameterTypeDescription
requestFastifyRequestThe Fastify request object
replyFastifyReplyThe Fastify reply object
options.contextInitial context typeContext passed to middleware
options.prefixstring (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
StandardHandlerPlugin[]
Plugins to apply to the handler.
strictGetMethodPluginEnabled
boolean
default:"true"
Restricts non-mutation procedures to GET requests.
adapterInterceptors
Interceptor[]
Low-level interceptors around the full request cycle.

Build docs developers (and LLMs) love