Middleware Pipeline
Middleware Concept
┌─────────────────────────────────────────────────────────────┐
│ Middleware Pipeline │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Auth │ │ Rate Limit │ │ Logging │ │
│ │ Middleware │ │ Middleware │ │ Middleware │ │
│ │ ┌───────┼──┼─────────────┼──┼─────────────┼───────┐ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ ┌───┼──┼─────────────┼──┼─────────────┼────┐ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ ┌───────────┼────┼──┼─┤
│ │ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ Handler │ │ │ │
│ │ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ └───────────┼────┼──┼─┤
│ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ │ │ └──┼─────────────┼──┼─────────────┼────┘ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ └──────┼─────────────┼──┼─────────────┼───────┘ │
│ │ │ │ │ │ │ │
│ └─────┼──────────┼─────────────┼──┼─────────────┼─────────┘
│ │ │ │ │ │
│ Request Request Request Request
│ ────────▶ ────────▶ ────────▶ ────────▶
│ │ │ │ │ │
│ Response Response Response Response
│ ◀──────── ◀──────── ◀──────── ◀────────
└─────────────────────────────────────────────────────────────┘Creating Middleware
Basic Middleware Structure
Middleware with Configuration
Middleware Registration
Route-Level Middleware
Group-Level Middleware
Combined Middleware
Built-in Middleware Examples
Authentication Middleware
Request ID Middleware
Validation Middleware
Middleware Execution Order
Chain Processing
Early Termination
Context Manipulation
Adding Data to Context
Modifying Payload
Error Handling in Middleware
Graceful Error Handling
Error Recovery
Dependency Injection in Middleware
Access to Shared Resources
Performance Considerations
Async Operations
Memory Efficiency
Testing Middleware
Unit Testing
Integration Testing
Best Practices
Middleware Design
Performance Guidelines
Security Considerations
Next Steps
Last updated