Overview
Context in Express Zod API is the mechanism for passing data from middlewares to endpoint handlers. It enables dependency injection, authentication state sharing, and access to shared resources like database connections. Context is type-safe and accumulated through the middleware chain.How Context Works
Context flows through your application in this order:- Middlewares execute in the order they were added to the factory
- Each middleware returns an object that becomes part of the context
- Context accumulates by merging all middleware returns
- Endpoint handler receives the complete context object
Providing Context via Middleware
The most common way to provide context is through middleware:Request-Independent Context
For context that doesn’t depend on the request, useaddContext():
Type-Safe Context
TypeScript automatically infers the context type from your middlewares:Context Accumulation
Context from multiple middlewares is merged:Accessing Previous Context
Middlewares can access context from previously executed middlewares:Context is accumulated in order. Later middlewares can access context from earlier ones, but not vice versa.
Shared Resources
Database Connections
For persistent database connections, use a singleton pattern instead of creating connections per request:Configuration
For static configuration, use imports instead of context:Resource Cleanup
Clean up resources in a custom Result Handler:Common Patterns
Authentication Context
Request Metadata
Feature Flags
Tenant Isolation
Context in Result Handlers
Result handlers receive context but it may be partial if middleware execution was interrupted:Best Practices
Performance Considerations
❌ Anti-pattern: Creating connections per request
✅ Better: Use a singleton
✅ Better: Use a connection pool
See Also
- Middleware - Create and chain middlewares
- Endpoints - Use context in endpoint handlers
- Result Handlers - Clean up resources