Skip to content
Projetos

Sobre

APIs com tipagem de ponta a ponta usando tRPC.io para suas aplicações SvelteKit.

Desenvolvimento web e de aplicativos

Como estes números são medidos

O que você pode fazer

  • 🔒 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

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

tRPC-SvelteKit

CI
NPM version License Stars Last commit Closed issues Downloads Language Sponsor the author

Documentation available at icflorescu.github.io/trpc-sveltekit.

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 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
  • 🌊 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 $lib with the #lib subpath 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:

🤖 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.

Explore projetos relacionados

Carregando…