Nuxt client
The magic of tRPC is making strongly typed API calls without relying on code generation. With full-stack TypeScript projects, you can directly import types from the server into the client! This is a vital part of how tRPC works.
Initialize a tRPC client
Create a typesafe client via a Nuxt plugin with the createTRPCNuxtClient
method from trpc-nuxt/client
, and add a links
array with a terminating link. If you want to learn more about tRPC links, check out the docs here:
createTRPCNuxtClient
extends createTRPCProxyClient and adds a useQuery
method built on top of useAsyncData.plugins/client.ts
import { createTRPCNuxtClient, httpBatchLink } from 'trpc-nuxt/client'
import type { AppRouter } from '~/server/trpc/routers'
export default defineNuxtPlugin(() => {
const client = createTRPCNuxtClient<AppRouter>({
links: [
httpBatchLink({
url: '/api/trpc',
}),
],
})
return {
provide: {
client,
},
}
})
As you can see, we passed AppRouter
as a type argument of createTRPCNuxtClient
. This returns a strongly typed client
instance, a proxy that mirrors the structure of your AppRouter
on the client:
pages/index.vue
<script setup lang="ts">
const { $client } = useNuxtApp()
// With composables
const getUser = await $client.getUser.useQuery('id_bilbo');
// => { data: { id: 'id_bilbo', name: 'Bilbo' }, pending: false, error: false };
const createUser = await $client.createUser.useMutation();
await createUser.mutate({ name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
// With vanilla
const bilbo = await $client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
const frodo = await $client.createUser.mutate({ name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
</script>