tRPC-SvelteKit v3.6.1

End-to-end typesafe APIs for your SvelteKit applications

Getting started

1 Install the trpc-sveltekit package and its dependencies with:

yarn add trpc-sveltekit @trpc/server @trpc/client

2 Create your tRPC router:

import type { Context } from '$lib/trpc/context';
import { initTRPC } from '@trpc/server';
import delay from 'delay';

export const t = initTRPC.context<Context>().create();

export const router = t.router({
  greeting: t.procedure.query(async () => {
    await delay(500); // 👈 simulate an expensive operation
    return `Hello tRPC v11 @ ${new Date().toLocaleTimeString()}`;

export const createCaller = t.createCallerFactory(router);

export type Router = typeof router;

3 Create a tRPC context:

import type { RequestEvent } from '@sveltejs/kit';

export async function createContext(event: RequestEvent) {
  return {
    event // 👈 `event` is now available in your context

export type Context = Awaited<ReturnType<typeof createContext>>;

4 Add this handle to your SvelteKit app hooks:

import { createContext } from '$lib/trpc/context';
import { router } from '$lib/trpc/router';
import type { Handle } from '@sveltejs/kit';
import { createTRPCHandle } from 'trpc-sveltekit';

export const handle: Handle = createTRPCHandle({ router, createContext });

If you have your own logic to place in the server hook, have a look at the sequence helper function in the SvelteKit docs.

5 Define a helper function to easily use the tRPC client in your pages:

import type { Router } from '$lib/trpc/router';
import { createTRPCClient, type TRPCClientInit } from 'trpc-sveltekit';

let browserClient: ReturnType<typeof createTRPCClient<Router>>;

export function trpc(init?: TRPCClientInit) {
  const isBrowser = typeof window !== 'undefined';
  if (isBrowser && browserClient) return browserClient;
  const client = createTRPCClient<Router>({ init });
  if (isBrowser) browserClient = client;
  return client;

6 Call the tRPC procedures in your pages:

<script lang="ts">
  import { page } from '$app/stores';
  import { trpc } from '$lib/trpc/client';

  let greeting = 'press the button to load data';
  let loading = false;

  const loadData = async () => {
    loading = true;
    greeting = await trpc($page).greeting.query();
    loading = false;

<h6>Loading data in<br /><code>+page.svelte</code></h6>



The trpc-sveltekit package exports two functions: createTRPCHandle and createTRPCClient.
The former is used in your SvelteKit app hooks, the latter is used in your pages.