Course contentsShow
← TypeScript
Lesson 1546 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Middleware and Meta Types

Creating typed middleware that transforms context and using meta types for procedure configuration and authorization.

Creating Typed Middleware That Transforms Context and Using Meta Types for Procedure Configuration and Authorization

What you'll learn: How to build strongly-typed tRPC middleware that transforms request context and use meta types to enforce authorization rules and procedure configuration at compile time.


In tRPC, middleware acts as a bridge between incoming requests and your procedures, transforming or enriching the context. Meta types let you attach compile-time metadata to procedures for configuration, feature flags, or authorization requirements—all with full type safety.

Middleware That Transforms Context

Think of middleware like a factory assembly line where each station adds something to a product. Your context starts minimal (maybe just a request object) and middleware layers enrich it with user data, database connections, or permissions.

The key is that each middleware's return type becomes the input type for the next layer. When middleware returns an extended context using .ctx(), TypeScript tracks those additions through the chain.

For example, a basic middleware might add a userId to context after authentication. The type system ensures downstream procedures can safely access ctx.userId because TypeScript knows the authentication middleware ran first.

Meta Types for Configuration

Meta types are compile-time labels you attach to procedures. You might mark a procedure as { requiresAuth: true } or { role: "admin" }. Middleware can then read these meta types and enforce rules—denying access if requirements aren't met.

The beauty is that these checks happen both at compile time (TypeScript yells if you access properties that don't exist) and runtime (middleware enforces the rules). You're essentially building a type-safe permission system directly into your API schema.

This pattern shines in authorization: define meta properties like roles or scopes, then create middleware that checks the authenticated user's permissions against the procedure's meta requirements.

Key Takeaway: Typed middleware transforms context with full type inference flowing through the chain, while meta types enable compile-time procedure configuration and authorization rules enforced by that middleware.