Course contentsShow
← TypeScript
Lesson 1575 of 1,79636. tRPC and End-to-End Type SafetyFree lesson

Context Type Propagation

Understanding how context types flow through procedures and affect procedure signatures.

Context Type Propagation

What you'll learn: How TypeScript automatically flows context types through your tRPC procedures, ensuring type safety from server handlers to client calls without explicit annotations.

The Flow of Context Types

In tRPC, context type propagation refers to how the type of your context object automatically flows through every procedure in your router. When you define a context type once during router creation, TypeScript ensures that every procedure receives the correctly-typed ctx parameter without you having to manually annotate it each time.

Think of context propagation like a river flowing downstream: you establish the water source (context type) at the top, and it naturally reaches every tributary (procedure) below without needing separate pumping stations.

How Context Types Affect Procedure Signatures

When you create a tRPC router with a typed context, that context type becomes part of the procedure's signature. Every procedure's handler function receives ctx as a parameter, and TypeScript infers its type from your router's context definition.

This propagation means:

  • No manual type annotations needed in individual procedures
  • Full autocomplete on ctx properties within any handler
  • Compile-time errors if you access properties that don't exist on the context
  • Type safety across middleware chains where context can be extended or narrowed

Context in Middleware vs Procedures

Context types can be transformed as they flow through middleware. Middleware can extend the context with additional properties (like adding a user after authentication), and these extensions propagate forward to subsequent procedures. TypeScript tracks these transformations, ensuring that procedures receive the enriched context type that reflects all prior middleware modifications.

The type system prevents you from accessing properties that haven't been added yet, while guaranteeing access to properties that middleware has provided.

Key Takeaway: Context type propagation eliminates repetitive type annotations by automatically flowing context types from router definition through all procedures, with TypeScript tracking transformations made by middleware along the way.