End-to-end typesafe APIs with tRPC.io in SvelteKit applications.
No code generation, run-time bloat, or build pipeline.
β
Works with @sveltejs/adapter-node
, @sveltejs/adapter-vercel
& @sveltejs/adapter-netlify
β
Works with SvelteKit's load()
function for SSR
Add this in your SvelteKit app hooks:
// src/hooks.server.ts or src/hooks.ts on older SvelteKit versions
import { createTRPCHandle } from 'trpc-sveltekit';
// create your tRPC router...
export const handle = async ({ event, resolve }) => {
const response = await createTRPCHandle({ // π add this handle
url: '/trpc',
router,
event,
resolve
});
return response;
};
- Install this package
npm install trpc-sveltekit
/yarn add trpc-sveltekit
// $lib/trpcServer.ts
import type { inferAsyncReturnType } from '@trpc/server';
import * as trpc from '@trpc/server';
// optional
export const createContext = () => {
// ...
return {
/** context data */
};
};
// optional
export const responseMeta = () => {
// ...
return {
// { headers: ... }
};
};
export const router = trpc
.router<inferAsyncReturnType<typeof createContext>>()
// queries and mutations...
.query('hello', {
resolve: () => 'world',
});
export type Router = typeof router;
- Add this handle to your application hooks (
src/hooks.server.ts
orsrc/hooks.ts
on older SvelteKit versions):
// src/hooks.server.ts or src/hooks.ts on older SvelteKit versions
import type { Handle } from '@sveltejs/kit';
import { createContext, responseMeta, router } from '$lib/trpcServer';
import { createTRPCHandle } from 'trpc-sveltekit';
export const handle: Handle = async ({ event, resolve }) => {
const response = await createTRPCHandle({
url: '/trpc', // optional; defaults to '/trpc'
router,
createContext, // optional
responseMeta, // optional
event,
resolve
});
return response;
};
Learn more about SvelteKit hooks here.
- Create a tRPC client:
// $lib/trpcClient.ts
import type { Router } from '$lib/trpcServer'; // π only the types are imported from the server
import * as trpc from '@trpc/client';
export default trpc.createTRPCClient<Router>({ url: '/trpc' });
Note: You also need to install the trpc client package with npm install @trpc/client
/yarn add @trpc/client
.
- Use the client like so:
// page.svelte
import trpcClient from '$lib/trpcClient';
const greeting = await trpcClient.query('hello');
console.log(greeting); // => π world
When you're building your SvelteKit app for production, you must instantiate your Prisma client like this: βοΈ
// $lib/prismaClient.ts
import pkg from '@prisma/client';
const { PrismaClient } = pkg;
const prismaClient = new PrismaClient();
export default prismaClient;
This will not work: β
// $lib/prismaClient.ts
import { PrismaClient } from '@prisma/client';
const prismaClient = new PrismaClient();
export default prismaClient;
Configure with superjson & Decimal.js / Prisma.Decimal
β If you don't know why you'd want to use superjson, learn more about tRPC data transformers here.
Install trpc-transformer
:
Then, configure your tRPC router like so:
// $lib/trpcServer.ts
import trpcTransformer from 'trpc-transformer';
import * as trpc from '@trpc/server';
export const router = trpc
.router()
// .merge, .query, .mutation, etc.
.transformer(trpcTransformer); // π
export type Router = typeof router;
...and don't forget to configure your tRPC client:
// $lib/trpcClient.ts
import type { Router } from '$lib/trpcServer';
import transformer from 'trpc-transformer';
import * as trpc from '@trpc/client';
export default trpc.createTRPCClient<Router>({
url: '/trpc',
transformer, // π
});
It is often useful to wrap the functionality of your @trpc/client
api within other functions. For this purpose, it's necessary to be able to infer input types, output types, and api paths generated by your @trpc/server router. Using tRPC's inference helpers, you could do something like:
// $lib/trpcClient.ts
import type { Router } from '$lib/trpcServer';
import trpcTransformer from '$lib/trpcTransformer';
import * as trpc from '@trpc/client';
import type { inferProcedureInput, inferProcedureOutput } from '@trpc/server';
export default trpc.createTRPCClient<Router>({
url: '/trpc',
transformer: trpcTransformer,
});
type Query = keyof Router['_def']['queries'];
type Mutation = keyof Router['_def']['mutations'];
// Useful types πππ
export type InferQueryOutput<RouteKey extends Query> = inferProcedureOutput<Router['_def']['queries'][RouteKey]>;
export type InferQueryInput<RouteKey extends Query> = inferProcedureInput<Router['_def']['queries'][RouteKey]>;
export type InferMutationOutput<RouteKey extends Mutation> = inferProcedureOutput<
Router['_def']['mutations'][RouteKey]
>;
export type InferMutationInput<RouteKey extends Mutation> = inferProcedureInput<Router['_def']['mutations'][RouteKey]>;
Then, you could use the inferred types like so:
// authors.svelte
<script lang="ts">
let authors: InferQueryOutput<'authors:browse'> = [];
const loadAuthors = async () => {
authors = await trpc.query('authors:browse', { genre: 'fantasy' });
};
</script>
If you need to use the tRPC client in SvelteKit's load()
function for SSR, make sure to initialize it like so:
// $lib/trpcClient.ts
import { browser } from '$app/env';
import type { Router } from '$lib/trpcServer';
import * as trpc from '@trpc/client';
import type { LoadEvent } from "@sveltejs/kit";
const url = browser ? '/trpc' : 'http://localhost:3000/trpc';
export default (loadFetch?: LoadEvent['fetch']) =>
trpc.createTRPCClient<Router>({
url: loadFetch ? '/trpc' : url,
transformer: trpcTransformer,
...(loadFetch && { fetch: loadFetch as typeof fetch })
});
Then use it like so:
// index.svelte
import trpcClient from '$lib/trpcClient';
import type { Load } from '@sveltejs/kit';
export const load: Load = async ({ fetch }) => { // π make sure to pass in this fetch, not the global fetch
const authors = await trpcClient(fetch).query('authors:browse', {
genre: 'fantasy',
});
return { props: { authors } };
};
Your server responses must satisfy some criteria in order for them to be cached Verced Edge Network, and here's where tRPC's responseMeta()
comes in handy. You could initialize your handle in src/hooks.server.ts
like so:
// src/hooks.server.ts or src/hooks.ts on older SvelteKit versions
import { router } from '$lib/trpcServer';
import { createTRPCHandle } from 'trpc-sveltekit';
export const handle = async ({ event, resolve }) => {
const response = await createTRPCHandle({
url: '/trpc',
event,
resolve,
responseMeta({ type, errors }) {
if (type === 'query' && errors.length === 0) {
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`
}
};
}
return {};
}
});
return response;
};
See an example with Prisma & superjson: β¨
On 24th of February 2022 Russia unlawfully invaded Ukraine. This is an unjustified, unprovoked attack on the sovereignty of a neighboring country, but also an open affront to international peace and stability that has the potential to degenerate into a nuclear event threatening the very existence of humanity. I am an EU (Romanian) citizen, but I am doing everything in my power to stop this madness. I stand with Ukraine. The entire Svelte community β€οΈπΊπ¦. Here's how you can show your support.
The ISC License.