Nuxt Adapter
Use oRPC inside a Nuxt project by mounting a handler in a server route.
Nuxt is a popular Vue.js framework for building server-side applications. Its server engine follows web standards, so oRPC integrates through the Fetch API Adapter.
Server
You set up an oRPC server inside Nuxt using its Server Routes.
import { onError } from '@orpc/server'
import { RPCHandler } from '@orpc/server/fetch'
const handler = new RPCHandler(router, {
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
export default defineEventHandler(async (event) => {
const request = toWebRequest(event)
const { response } = await handler.handle(request, {
prefix: '/rpc',
context: {} // Provide initial context if needed
})
if (response) {
return response
}
setResponseStatus(event, 404, 'Not Found')
return 'Not found'
})export { default } from './[...]'Client
To make the oRPC client compatible with SSR, set it up inside a Nuxt Plugin.
import type { RouterClient } from '@orpc/server'
import { createORPCClient } from '@orpc/client'
import { RPCLink } from '@orpc/client/fetch'
export default defineNuxtPlugin(() => {
const event = useRequestEvent()
const requestURL = useRequestURL()
const link = new RPCLink({
url: '/rpc',
origin: typeof window === 'undefined' ? requestURL.origin : undefined, // defaults to the current origin in the browser
headers: () => event?.headers ?? {},
})
const client: RouterClient<typeof router> = createORPCClient(link)
return {
provide: {
client,
},
}
})
Optimize SSR
To reduce HTTP requests and improve latency during SSR, you can use a server-side client during SSR. Below is a quick setup, see Optimizing SSR for more details.
import type { RouterClient } from '@orpc/server'
import { createORPCClient } from '@orpc/client'
import { RPCLink } from '@orpc/client/fetch'
export default defineNuxtPlugin(() => {
const link = new RPCLink({
url: '/rpc',
})
const client: RouterClient<typeof router> = createORPCClient(link)
return {
provide: {
client,
},
}
})import { createRouterClient } from '@orpc/server'
export default defineNuxtPlugin(() => {
const event = useRequestEvent()
const client = createRouterClient(router, {
context: {
headers: event?.headers, // provide headers if initial context required
},
})
return {
provide: {
client,
},
}
})