0Pricing
TypeScript Academy · Lesson

Middleware and Context

Add auth and shared context to procedures.

What Is Context

Every tRPC request carries a context: shared data available to all procedures, such as the database client, the request, and the current user. You build it once per request with a createContext function.

export async function createContext({ req }: { req: Request }) {
  const token = req.headers.get('authorization');
  const user = await getUserFromToken(token);
  return { user };
}

Typing the Context

tRPC infers the context type from createContext and threads it through every procedure. You initialize the instance with that context type so resolvers see ctx typed correctly.

import { initTRPC } from '@trpc/server';

type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();

All lessons in this course

  1. The tRPC Architecture
  2. Defining Routers and Procedures
  3. Client-Server Type Inference
  4. Middleware and Context
← Back to TypeScript Academy