Astro Adapter
Use oRPC inside an Astro project by mounting a handler in an API route.
Astro is a JavaScript web framework optimized for building fast, content-driven websites. Its endpoints follow the Fetch API, so oRPC integrates through the Fetch API Adapter.
Basic
import type { APIRoute } from 'astro'
import { onError } from '@orpc/server'
import { RPCHandler } from '@orpc/server/fetch'
const handler = new RPCHandler(router, {
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
export const prerender = false
export const ALL: APIRoute = async ({ request }) => {
const { response } = await handler.handle(request, {
prefix: '/rpc',
context: {} // Provide initial context if needed
})
return response ?? new Response('Not found', { status: 404 })
}
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'
if (import.meta.env.SSR) {
await import('./orpc.server')
}
declare global {
var $client: RouterClient<typeof router> | undefined
}
const link = new RPCLink({
url: '/rpc',
origin: () => {
if (typeof window === 'undefined') {
throw new Error('This link is not allowed on the server side.')
}
return window.location.origin
},
})
/**
* Fall back to a browser client when no SSR client is registered.
*/
export const client: RouterClient<typeof router> = globalThis.$client ?? createORPCClient(link)import { createRouterClient } from '@orpc/server'
globalThis.$client = createRouterClient(router, {
context: {} // Provide initial context if needed
})