0Pricing
React Academy · Lesson

Integrating tRPC with React Query and Auth

Configure tRPC's React Query integration, add authentication headers, and handle protected procedures.

tRPC Context: Per-Request Data

The tRPC context is an object created fresh for every request by the createTRPCContext function. It can contain the database client, the authenticated session, the request headers, or any per-request data your procedures need.

Context creation runs before any procedure, making it the right place for authentication and database connection setup.

Adding Session to Context via NextAuth

In createTRPCContext, call getServerSession(authOptions) from next-auth/next. Attach the result to the context object: return { session: await getServerSession(authOptions), db }. All procedures now have access to ctx.session.

If session is null, the user is unauthenticated. Procedures can check this to conditionally return data or throw an error.

All lessons in this course

  1. The Problem tRPC Solves
  2. Setting Up tRPC with React and Next.js
  3. Queries, Mutations, and Subscriptions
  4. Integrating tRPC with React Query and Auth
← Back to React Academy