Server Side Calls

You may need to call your procedure(s) directly from the server, createCaller() function returns you an instance of RouterCaller able to execute queries and mutations.

Input query example

We create the router with a input query and then we call the asynchronous greeting procedure to get the result.

server/trpc/trpc.ts
import { initTRPC } from '@trpc/server'import { z } from 'zod' const t = initTRPC.create() export const router = t.router({  // Create procedure at path 'greeting'  greeting: t.procedure    .input(z.object({ name: z.string() }))    .query(({ input }) => `Hello ${input.name}`),})
server/api/greeting.ts
import { router } from '@/server/trpc/trpc'export default eventHandler(async (event) => {  const { name } = getQuery(event)  const caller = router.createCaller({})  const greeting = await caller.greeting({ name })  return {    greeting  }})

Mutation example

We create the router with a mutation and then we call the asynchronous post procedure to get the result.

server/trpc/trpc.ts
import { initTRPC } from '@trpc/server'import { z } from 'zod' const posts = ['One', 'Two', 'Three'] const t = initTRPC.create()export const router = t.router({  post: t.router({    add: t.procedure.input(z.string()).mutation(({ input }) => {      posts.push(input)      return posts    }),  }),})
server/api/post.ts
import { router } from '@/server/trpc/trpc'export default eventHandler(async (event) => {  const body = await getBody(event)  const caller = router.createCaller({})  const post = await caller.post.add(body.post)  return {    post  }})