Context Typing for Procedures in tRPC
What you'll learn: How to type the context object that gets passed to every tRPC procedure, including authentication data, database connections, and request metadata.
What Is Procedure Context?
In tRPC, every procedure receives a context object alongside its input. This context carries shared state and services that your procedures need—things like the current user's authentication info, database connections, logger instances, or request headers.
Without proper typing, you'd lose all type safety when accessing context properties. TypeScript wouldn't know what's in ctx, forcing you to use type assertions or guessing.
Think of It Like a Backpack
Imagine every procedure is a function that gets handed a backpack (ctx). That backpack contains tools: your database connection, the user's ID, access tokens. By typing the backpack's contents, TypeScript ensures you never reach for a tool that isn't there—or misspell the pocket where it's stored.
Defining Your Context Type
You define context when creating your tRPC instance. The type flows through to every procedure automatically:
import { initTRPC } from '@trpc/server';
interface Context {
user: { id: string; email: string } | null;
db: DatabaseConnection;
requestId: string;
}
const t = initTRPC.context<Context>().create();
Now every procedure knows ctx has user, db, and requestId properties—fully typed.
Using Context in Procedures
Once defined, your procedures access context with full autocomplete and safety:
const getUserProfile = t.procedure
.query(({ ctx }) => {
// TypeScript knows ctx.user exists
if (!ctx.user) {
throw new Error('Not authenticated');
}
// ctx.user.id is string
return ctx.db.getProfile(ctx.user.id);
});
Common Context Patterns
Authentication state: Include user: User | null to represent logged-in vs anonymous requests.
Database connections: Pass your ORM client or connection pool so procedures can query data.
Request metadata: Store request IDs, IP addresses, or headers for logging and tracing.
Why This Matters
Typing context prevents runtime surprises. If you forget to initialize the database in context, TypeScript catches it at compile time—not when your production API crashes. It also documents what resources every procedure expects, making onboarding and refactoring safer.
Key Takeaway: Context typing in tRPC transforms the ctx parameter from an opaque object into a fully typed, documented contract—giving you autocomplete for auth data, database clients, and request metadata throughout your procedures.