Runtime Middleware
CopilotKit Runtime provides middleware hooks that allow you to intercept, modify, and monitor HTTP requests and responses. This is essential for authentication, logging, request transformation, and response analysis.Overview
Middleware in CopilotKit operates at two lifecycle stages:- Before Request - Runs before the request reaches the handler (authentication, validation, request modification)
- After Request - Runs after the handler returns a response (logging, analytics, response processing)
Middleware Types
Before Request Middleware
Intercepts requests before they reach the agent runtime. Can modify the request or return early with a custom response.After Request Middleware
Runs after the handler completes. Useful for logging, analytics, and response processing.Common Use Cases
Authentication
Verify user identity before processing requests:Request Logging
Log all incoming requests for debugging and monitoring:Rate Limiting
Implement rate limiting based on user or IP:Request Validation
Validate request body structure before processing:Analytics and Monitoring
Track agent usage, performance, and errors:Error Handling
Catch and log errors consistently:Response Caching
Cache responses for improved performance:SSE Stream Processing
The after middleware provides parsed SSE messages for stream analysis:Middleware Composition
Combine multiple middleware functions for complex workflows:Middleware Parameters
BeforeRequestMiddlewareParameters
AfterRequestMiddlewareParameters
Best Practices
Keep It Fast
Middleware runs on every request - keep operations lightweight and avoid blocking I/O
Handle Errors
Always catch errors in middleware to prevent request failures from uncaught exceptions
Clone Requests
Use
request.clone() if you need to read the request body, as bodies can only be read onceAsync-First
All middleware is async - use
await for database queries, API calls, and other I/O operationsTesting Middleware
Test your middleware in isolation:Related Resources
Shared State
Access and modify agent state in middleware
Multi-Agent
Route requests to specific agents in middleware
