tRPC-SvelteKit v4.1.0

End-to-end typesafe APIs for your SvelteKit applications

Using with Svelte Query

tRPC-SvelteKit works great with TanStack Svelte Query. Its createTRPCQueryOptions function turns your tRPC client into typed query and mutation options, so you don't have to write query keys or query functions yourself.

Install Svelte Query:

pnpm
npm
yarn
bun
pnpm add @tanstack/svelte-query

Setup

Define a helper next to your trpc() client helper (see Getting started):

lib/trpc/query.ts
import { trpc } from '#lib/trpc/client.ts';
import { createTRPCQueryOptions, type TRPCClientInit } from 'trpc-sveltekit';

// 👇 TanStack Query options for every procedure, built on the `trpc()` client helper
export const api = (init?: TRPCClientInit) => createTRPCQueryOptions(trpc(init));

Create a QueryClient in a layout load function and provide it to your pages. Queries only run in the browser; the data needed for server-side rendering is prefetched in load functions:

routes/svelte-query/+layout.ts
import { browser } from '$app/env';
import { QueryClient } from '@tanstack/svelte-query';
import type { LayoutLoad } from './$types';

export const load: LayoutLoad = () => ({
  // 👇 queries only run in the browser; data needed for SSR is prefetched in `load` functions
  queryClient: new QueryClient({ defaultOptions: { queries: { enabled: browser } } })
});
routes/svelte-query/+layout.svelte
<script lang="ts">
  import { QueryClientProvider } from '@tanstack/svelte-query';

  let { data, children } = $props();
</script>

<QueryClientProvider client={data.queryClient}>
  {@render children()}
</QueryClientProvider>

Queries

Prefetch your queries in load functions, so that pages are rendered with data on the server. The browser then reuses the server response while hydrating instead of fetching again:

routes/svelte-query/+page.ts
import { api } from '#lib/trpc/query.ts';
import type { PageLoad } from './$types';

export const load: PageLoad = async (event) => {
  const { queryClient } = await event.parent();
  // 👇 prefetch the query, so that the page is rendered with data on the server
  await queryClient.prefetchQuery(api(event).greeting.queryOptions());
};

And use the same options in your pages. queryOptions(input, options) accepts any createQuery option, such as staleTime, and adds the queryKey and queryFn:

routes/svelte-query/+page.svelte
<script lang="ts">
  import { page } from '$app/state';
  import { api } from '#lib/trpc/query.ts';
  import { createQuery, useQueryClient } from '@tanstack/svelte-query';

  const queryClient = useQueryClient();

  const greeting = createQuery(() =>
    api(page).greeting.queryOptions(undefined, { staleTime: 10_000 })
  );

  const refresh = (e: MouseEvent) => {
    e.preventDefault();
    // 👇 `pathKey()` matches the procedure's queries for every input
    queryClient.invalidateQueries({ queryKey: api(page).greeting.pathKey() });
  };
</script>

<h6>Loading data with<br /><code>@tanstack/svelte-query</code></h6>

<a href="#refresh" role="button" class="secondary" aria-busy={greeting.isFetching} onclick={refresh}
  >Refresh</a
>
<p>{greeting.data}</p>

Mutations and invalidation

mutationOptions(options) does the same for createMutation. To refetch queries after a mutation, invalidate them with a key: queryKey(input) matches a single query, pathKey() matches every query of a procedure (for any input), or of a whole router:

authors/+page.svelte
<script lang="ts">
  import { page } from '$app/state';
  import { api } from '#lib/trpc/query.ts';
  import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';

  const queryClient = useQueryClient();

  let search = $state('');

  // 👇 the input is part of the query key, so changing `search` loads (and caches) new results
  const authors = createQuery(() => api(page).authors.list.queryOptions(search));

  const save = createMutation(() =>
    api(page).authors.save.mutationOptions({
      // 👇 refetch every `authors` query (for any input) once the mutation succeeds
      onSuccess: () => queryClient.invalidateQueries({ queryKey: api(page).authors.pathKey() })
    })
  );
</script>

<input type="search" bind:value={search} />
<ul>
  {#each authors.data ?? [] as author (author.id)}
    <li>{author.firstName} {author.lastName}</li>
  {/each}
</ul>
<button
  aria-busy={save.isPending}
  onclick={() => save.mutate({ id: null, firstName: 'Jane', lastName: 'Doe', bio: null })}
>
  Add author
</button>

The query keys have the same format as the ones of tRPC's own TanStack Query integration, e.g. [['authors', 'list'], { input: 'smith', type: 'query' }]. Subscriptions aren't supported, since TanStack Query doesn't handle them.

See the complete Svelte Query example in the repository.

Third-party adapters for older versions

At the time of writing, the community-maintained tRPC Svelte Query Adapter only supports tRPC v10 and Svelte Query v5, so it requires trpc-sveltekit v3. If you're using SvelteKit 2 and Svelte Query v5, trpc-svelte-query supports tRPC v11, with its own SvelteKit integration.