What You'll Learn
You'll learn how to pass request-specific information (like user sessions or headers) into tRPC procedures and use that context for authorization checks.
Why Context Matters
When your API needs to know who is making a request, you can't just pass user data as a regular input—that would let anyone claim to be anyone! Instead, tRPC lets you extract authentication info from the underlying request (cookies, JWT tokens, headers) and make it available to every procedure through context.
Think of context as a backstage pass that tRPC automatically hands to every procedure. The pass gets validated at the door (during context creation), then procedures can check it before allowing access.
Creating Context
On your server, you define a createContext function that runs before each request:
export const createContext = async ({ req, res }: CreateContextOptions) => {
// Extract session from cookie/header
const token = req.headers.authorization?.split(' ')[1];
const user = await validateToken(token); // Your auth logic
return { user, req, res };
};
export type Context = inferAsyncReturnType<typeof createContext>;
Using Context in Procedures
Access the context via ctx in your resolver:
export const appRouter = router({
getProfile: publicProcedure.query(({ ctx }) => {
if (!ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return ctx.user.profile;
}),
deleteAccount: publicProcedure.mutation(({ ctx }) => {
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: 'FORBIDDEN' });
}
// Admin-only logic here
}),
});
Every procedure automatically receives the context you created, letting you check ctx.user for authentication and authorization.
Key Takeaway: Context passes request-specific data (like authenticated user sessions) to all tRPC procedures, enabling secure authorization checks without exposing authentication logic to client inputs.