Introduction
Middleware provides a convenient mechanism to filter and process HTTP requests entering your application. Lyger’s middleware system is inspired by Laravel and allows you to chain multiple middleware handlers together.Middleware Concept
Middleware acts as a bridge between a request and a response. Each middleware can:- Inspect the incoming request
- Modify the request
- Pass control to the next middleware
- Return a response early (short-circuit)
- Modify the response after the handler executes
Creating Middleware
All middleware must extend theMiddleware base class and implement the handle method:
The
$next callable represents the next middleware in the chain or the final route handler.Built-in Middleware
Lyger includes several built-in middleware classes for common use cases:CORS Middleware
Handle Cross-Origin Resource Sharing (CORS) headers:allowed_origins: Array of allowed origins or['*']for allallowed_methods: HTTP methods to allowallowed_headers: Request headers to allowexposed_headers: Response headers to exposemax_age: Preflight cache duration in secondssupports_credentials: Whether to support credentials
- Allow All Origins
- Specific Origins
- With Credentials
Rate Limiting Middleware
Prevent abuse by limiting the number of requests:X-RateLimit-Limit: Maximum attempts allowedX-RateLimit-Remaining: Remaining attemptsX-RateLimit-Reset: Unix timestamp when the limit resetsRetry-After: Seconds until retry (when limit exceeded)
The rate limiter uses IP address and URI as the signature for tracking requests.
Authentication Middleware
Simple token-based authentication:Authorization header (or custom header):
JSON Parser Middleware
Automatically parse JSON request bodies:- Detects
application/jsoncontent type - Parses the JSON body
- Makes data available via
$request->input()
Logging Middleware
Log all HTTP requests and responses:Chaining Middleware
Middleware can be chained together using thesetNext() method:
Creating Custom Middleware
Here are some practical examples of custom middleware:Short-Circuiting
Middleware can return a response early without calling the next middleware:Conditional Middleware
Apply middleware based on conditions:Middleware Best Practices
Keep middleware focused: Each middleware should handle one specific concern (authentication, logging, etc.)
Order matters: Chain middleware in logical order. For example, rate limiting should come before authentication to protect auth endpoints.
Performance: Avoid heavy operations in middleware that runs on every request. Consider caching when possible.
Common Middleware Stack
A typical production middleware stack might look like:Next Steps
Basic Routing
Learn about defining routes
Route Parameters
Capture dynamic URL segments