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
- The tRPC Architecture
- Defining Routers and Procedures
- Client-Server Type Inference
- Middleware and Context