Simple Usage
1. Create a tRPC router
Initialize your tRPC backend using the initTRPC
function and create your first router.
server/trpc/trpc.ts
/** * This is your entry point to setup the root configuration for tRPC on the server. * - `initTRPC` should only be used once per app. * - We export only the functionality that we use so we can enforce which base procedures should be used * * Learn how to create protected base procedures and other things below: * @see https://trpc.io/docs/v10/router * @see https://trpc.io/docs/v10/procedures */import { initTRPC } from '@trpc/server'const t = initTRPC.create()/** * Unprotected procedure **/export const publicProcedure = t.procedure;export const router = t.router;export const middleware = t.middleware;
2. Create Vue Query and tRPC client plugin
Create a strongly-typed plugin using your API's type signature.
plugins/1.vue-query.ts
import type { DehydratedState, VueQueryPluginOptions } from "@tanstack/vue-query"import { VueQueryPlugin, QueryClient, hydrate, dehydrate } from "@tanstack/vue-query"// Nuxt 3 app aliasesimport { useState } from "#app"export default defineNuxtPlugin((nuxt) => { const vueQueryState = useState<DehydratedState | null>("vue-query") // Modify your Vue Query global settings here const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5000 } }, }); const options: VueQueryPluginOptions = { queryClient } nuxt.vueApp.use(VueQueryPlugin, options) if (process.server) { nuxt.hooks.hook("app:rendered", () => { vueQueryState.value = dehydrate(queryClient) }); } if (process.client) { nuxt.hooks.hook("app:created", () => { hydrate(queryClient, vueQueryState.value) }); }})
3. Make an API request
pages/index.vue
<script setup lang="ts">const { $client } = useNuxtApp()const { isLoading, isError, data, error } = $client.hello.useQuery({ text: 'client' })const { mutateAsync, isLoading, isError, data, error } = $client.login.useMutation()const handleLogin = async () => { const person = await mutateAsync({ name: "John Doe" })}</script><template> <div> <p>{{ hello.data?.greeting }}</p> <p><button @click="handleLogin">Login</button></p> </div></template>