Skip to content

H3 server adapter

trpc-vue-query project includes a trpc server adapter for h3, the web framework that powers nitro and nuxt.

For nuxt, a complete example is available at example-nuxt directory, including both client and server integration.

WARNING

Subscriptions/Websocket is not supported

WARNING

trpc-vue-query is designed for trpc v11. See support matrix in overview for details

Step 1: Install required packages

Assuming you already got h3/nitro/nuxt setup already.

bash
npm i -S @trpc-vue-query/h3-adapter @trpc/server@next
bash
pnpm add @trpc-vue-query/h3-adapter @trpc/server@next
bash
yarn add @trpc-vue-query/h3-adapter @trpc/server@next

Step 2: Initialize trpc and create router

Basically following the backend guide from trpc. You might want to place trpc-related code into server/ in nuxt context.

ts
import { initTRPC } from "@trpc/server";

const t = initTRPC.create();

export const router = t.router;
export const publicProcedure = t.procedure;
ts
import { publicProcedure, router } from "./trpc";

const appRouter = router({
  greeting: publicProcedure.query(() => "hello tRPC v11!"),
});

export type AppRouter = typeof appRouter;

Note that the type AppRouter will be available in trpc/app.ts for this case. You might need to adjust that path in your framework.

Step 3: Install router handler

TRPC will be available on "/trpc" for httpBatchLink input.

ts
import { createApp, createRouter, defineEventHandler } from "h3";
import { h3RequestHandler } from "@trpc-vue-query/h3-adapter";
import { router } from "./trpc/trpc";

const app = createApp();
const r = createRouter();

r.use(
  "/trpc/:trpc",
  h3RequestHandler({
    router, // <-- This router is trpc's router, not h3 router
  }),
);

app.use(r);

To change the route parameter name, pass the name into h3RequestHandler as routeParam if you must:

ts
// This is possible, but not recommended. Stick with `:trpc` for parameter name unless
// there is good reason to change.

r.use(
  "/trpc/:something", 
  h3RequestHandler({
    router,
    routeParam: "something", 
  }),
);