tRPC-Nuxt
End-to-end typesafe APIs with tRPC.io in Nuxt applications.
The client above is not importing any code from the server, only its type declarations.
Install
npm i trpc-nuxt
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
modules: ['trpc-nuxt'],
trpc: {
baseURL: 'http://localhost:3000',
endpoint: '/trpc',
},
typescript: {
strict: true
}
})
Usage
Expose your tRPC routes under ~/server/trpc/index.ts
:
import type { inferAsyncReturnType } from '@trpc/server'
import * as trpc from '@trpc/server'
import { z } from 'zod'
export const router = trpc.router()
.query('getUsers', {
async resolve(req) {
return await UserModel.all()
},
})
.mutation('createUser', {
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
return await UserModel.create({
data: req.input,
})
},
})
Use the client like so:
const client = useClient()
const users = await client.query('getUsers')
const newUser = await client.mutation('createUser', {
name: 'wagmi'
})
useAsyncQuery
A thin wrapper around useAsyncData
and client.query()
.
The first argument is a [path, input]
-tuple - if the input
is optional, you can omit the, input
-part.
You'll notice that you get autocompletion on the path
and automatic typesafety on the input
.
const {
data,
pending,
error,
refresh
} = await useAsyncQuery(['getUser', { id: 69 }], {
lazy: false
})
A composable that lets you add additional properties to pass to the tRPC Client. It uses useStorage
from @vueuse/core.
const headers = useClientHeaders()
const { data: token } = await useAsyncQuery(['auth.login', { username, password }])
headers.value.Authorization = `Bearer ${token}`
Options
trpc-nuxt accepts the following options exposed under ~/server/trpc/index.ts
:
import * as trpc from '@trpc/server'
import type { inferAsyncReturnType } from '@trpc/server'
import type { CompatibilityEvent } from 'h3'
import type { OnErrorPayload } from 'trpc-nuxt/api'
export const router = trpc.router<inferAsyncReturnType<typeof createContext>>()
export const createContext = (event: CompatibilityEvent) => {
return {
}
}
export const responseMeta = () => {
return {
}
}
export const onError = (payload: OnErrorPayload<typeof router>) => {
}
Recipes
Learn more about tRPC.io here.
Recommended IDE Setup
License
MIT