Protected procedures
For Admin panel only projects, the login is /, the home page is /dashboard, and other panel pages omit the /admin prefix. Components use @/components and @/components/ui. API endpoints such as /api/admin/users/export keep their paths. Examples below use the combined public website + admin panel layout; generated standalone guides use the app’s actual paths.
Add a protected procedure
Choose the least permissive procedure that fits the operation:
| Helper | What it verifies |
|---|---|
publicProcedure |
No session required |
protectedProcedure |
Valid session and non-banned account |
adminProcedure |
Valid session, non-banned account, and exact admin role |
For example, create a feature router that validates its input and uses the verified session:
// src/trpc/routers/greeting.ts
import "server-only";
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "@/trpc/init";
export const greetingRouter = createTRPCRouter({
message: protectedProcedure
.input(z.object({ topic: z.string().trim().min(1).max(100) }))
.query(({ ctx, input }) => ({
message: `Hello ${ctx.session.user.name}. Let's discuss ${input.topic}.`,
})),
});
Import greetingRouter into src/trpc/routers/app.ts and add it to the existing root router under the greeting key. The typed client then exposes the query:
const greeting = useQuery(
trpc.greeting.message.queryOptions({ topic: "your project" })
);
For database operations, use ctx.getDb(). Validate resource ownership or tenant access inside each procedure, even when the user is signed in or has an admin role.
Keep password, account, and session mutations in Better Auth’s authClient; its management endpoints already implement their auth rules.
File reference
| File | Responsibility |
|---|---|
src/trpc/context.ts |
Lazy database access and request-local session lookup |
src/trpc/init.ts |
Router helpers, authorization, and validated errors |
src/trpc/routers/app.ts |
Root application router |
src/trpc/client.tsx |
Client provider and hooks |
src/trpc/server.tsx |
Direct calls, prefetching, and hydration |
src/trpc/query-client.ts |
QueryClient factory and identity reset |
src/app/api/trpc/[trpc]/route.ts |
HTTP handler |
Browser calls use /api/trpc and its same-origin session cookie. POST requests must send a matching Origin; server-to-server clients need that header too. Server Components should use the direct helpers.
HTTP responses are no-store, and unexpected internal errors are sanitized. Session/role data and private results stay outside shared Next.js caches.
Public procedures avoid auth/database reads unless they request them. Missing session cookies return no session before initialization; present cookies always go through Better Auth. Keep the cookie helper aligned if its name or prefix changes.