Skip to content
You are reading the v2 docs, currently in beta.V1 docs
oRPC
Esc
navigateopen⌘Jpreview
On this page

SvelteKit Adapter

Use oRPC inside a SvelteKit project by mounting a handler in an endpoint.

SvelteKit is a framework for rapidly developing robust, performant web applications using Svelte. Its endpoints follow the Fetch API, so oRPC integrates through the Fetch API Adapter.

Server

import type { RequestHandler } from './$types'
import { onError } from '@orpc/server'
import { RPCHandler } from '@orpc/server/fetch'

const handler = new RPCHandler(router, {
  interceptors: [
    onError((error) => {
      console.error(error)
    }),
  ],
})

const handle: RequestHandler = async ({ request }) => {
  const { response } = await handler.handle(request, {
    prefix: '/rpc',
    context: {} // Provide initial context if needed
  })

  return response ?? new Response('Not found', { status: 404 })
}

export const GET = handle
export const POST = handle
export const PUT = handle
export const PATCH = handle
export const DELETE = handle

Optimize SSR

To reduce HTTP requests and improve latency during SSR, you can utilize Svelte’s special fetch 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 type { RouterClient } from '@orpc/server'
import { getRequestEvent } from '$app/server'
import { createORPCClient } from '@orpc/client'
import { RPCLink } from '@orpc/client/fetch'

if (typeof window !== 'undefined') {
  throw new Error('This file should only be imported on the server')
}

const link = new RPCLink({
  url: '/rpc',
  origin: () => getRequestEvent().url.origin,
  fetch: (url, init) => getRequestEvent().fetch(url, init),
})

const serverClient: RouterClient<typeof router> = createORPCClient(link)
globalThis.$client = serverClient

Last updated on August 25, 2026

Was this page helpful?