icflorescu/trpc-sveltekit
关于
使用 tRPC.io 为 SvelteKit 应用构建端到端类型安全的 API。
网站与应用开发可以做什么
- 🔒 End-to-end typesafe APIs for SvelteKit, powered by tRPC
- 🧩 A single SvelteKit handle hook, compatible with every adapter (Node, Bun, Vercel, Netlify, Cloudflare, …)
- 🔁 Typed TanStack Svelte Query options and query keys with createTRPCQueryOptions
- 🍪 Procedures can set cookies and headers through the SvelteKit request event
实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文tRPC-SvelteKit
Documentation available at icflorescu.github.io/trpc-sveltekit.
Move fast and break nothing.
End-to-end typesafe APIs for your
SvelteKit applications.
Features
- 🔒 End-to-end typesafe APIs for SvelteKit, powered by tRPC
- 🧩 A single SvelteKit
handlehook, compatible with every adapter (Node, Bun, Vercel, Netlify, Cloudflare, …) - 🔁 Typed TanStack Svelte Query options and query keys with
createTRPCQueryOptions - 🍪 Procedures can set cookies and headers through the SvelteKit request event
- 🌊 Streaming responses and subscriptions over server-sent events
- 🧪 Experimental WebSocket support for
@sveltejs/adapter-node
Compatibility
| tRPC-SvelteKit | tRPC | SvelteKit |
|---|---|---|
| v4.x.x | v11 | v2, v3 |
| v3.x.x | v10 | v1, v2 |
| v2.x.x | v9 | v1 |
Upgrading from v3? Have a look at the upgrade guide. See the changelog for the notable changes in each version.
Quickstart
pnpm add trpc-sveltekit @trpc/server @trpc/client
Create your tRPC router:
// src/lib/trpc/router.ts
import type { Context } from '#lib/trpc/context.ts';
import { initTRPC } from '@trpc/server';
import { setTimeout as delay } from 'node:timers/promises';
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;
Add the handle to your SvelteKit server hooks:
// src/hooks.server.ts
import { createContext } from '#lib/trpc/context.ts';
import { router } from '#lib/trpc/router.ts';
import { createTRPCHandle } from 'trpc-sveltekit';
export const handle = createTRPCHandle({ router, createContext });
Call your procedures in your pages:
<!-- src/routes/+page.svelte -->
<script lang="ts">
import { page } from '$app/state';
import { trpc } from '#lib/trpc/client.ts';
let greeting = $state('press the button to load data');
let loading = $state(false);
const loadData = async (e: MouseEvent) => {
e.preventDefault();
loading = true;
greeting = await trpc(page).greeting.query();
loading = false;
};
</script>
<h6>Loading data in<br /><code>+page.svelte</code></h6>
<a href="#load" role="button" class="secondary" aria-busy={loading} onclick={loadData}>Load</a>
<p>{greeting}</p>
The getting started guide walks you through the whole setup, including the
tRPC context and the trpc() client helper used above.
The examples use SvelteKit 3, which replaced
$libwith the#libsubpath import. With SvelteKit 2, import from$lib/...instead.
TanStack Svelte Query
createTRPCQueryOptions turns your tRPC client into typed TanStack Svelte Query options and query keys, so you don't have to write query keys or query functions yourself:
// src/lib/trpc/query.ts
import { trpc } from '#lib/trpc/client.ts';
import { createTRPCQueryOptions, type TRPCClientInit } from 'trpc-sveltekit';
export const api = (init?: TRPCClientInit) => createTRPCQueryOptions(trpc(init));
<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();
const authors = createQuery(() => api(page).authors.list.queryOptions('smith'));
const save = createMutation(() =>
api(page).authors.save.mutationOptions({
// 👇 refetch every `authors` query once the mutation succeeds
onSuccess: () => queryClient.invalidateQueries({ queryKey: api(page).authors.pathKey() })
})
);
</script>
The Svelte Query guide shows how to set it up, including prefetching queries on the server in load functions.
Documentation
The documentation website covers everything else:
- loading data in
+page.tsand+page.server.tsfiles - using it with TanStack Svelte Query: queries, mutations, invalidation and server-side prefetching
- authentication and error handling
- recipes: client options, custom links, subscriptions, response caching, data transformers
- experimental WebSocket support
🤖 Using an AI assistant or coding agent? Point it to llms.txt or llms-full.txt for LLM-friendly documentation (see how to use them).
Examples
- simple — the basics, and TanStack Svelte Query
- bookstall — authentication, CRUD, Prisma
- websocket — subscriptions over WebSockets
Contributing
Contributions are welcome! See CONTRIBUTING.md.
Acknowledgements
Huge thanks to Alex / KATT, the creator of tRPC, for being the first sponsor of this project! 🎉 Read more on the acknowledgements page.
About the author
tRPC-SvelteKit is built and maintained by Ionut-Cristian Florescu, a hands-on fractional CTO, product builder and open-source author from Bucharest, Romania, building for the web since 1998. He's also the author of Mantine DataTable and Mantine ContextMenu, a contributor to tRPC and Mantine, and the founder of swapp.ro, an invoicing and accounting product for Romanian freelancers.
Want to work together? Have a look at the hire the author page. If you find tRPC-SvelteKit useful, please consider sponsoring its development. 🙏
Stand with Ukraine
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.
License
The ISC License.
探索相关项目
加载中…
