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.
All middleware must extend the Middleware base class and implement the handle method:
Copy
namespace App\Middleware;use Lyger\Middleware\Middleware;use Lyger\Http\Request;use Lyger\Http\Response;class CustomMiddleware extends Middleware{ public function handle(Request $request, callable $next): Response { // Do something before the request is handled $response = $next($request); // Do something after the response is created return $response; }}
The $next callable represents the next middleware in the chain or the final route handler.
use Lyger\Middleware\RateLimitMiddleware;// Allow 60 requests per 60 seconds$rateLimiter = new RateLimitMiddleware(60, 60);// Allow 100 requests per 5 minutes$rateLimiter = new RateLimitMiddleware(100, 300);
The rate limiter automatically adds headers to responses:
X-RateLimit-Limit: Maximum attempts allowed
X-RateLimit-Remaining: Remaining attempts
X-RateLimit-Reset: Unix timestamp when the limit resets
Retry-After: Seconds until retry (when limit exceeded)
When the limit is exceeded, it returns a 429 response:
Copy
{ "error": "Too Many Requests", "message": "Rate limit exceeded. Try again later.", "retry_after": 45}
The rate limiter uses IP address and URI as the signature for tracking requests.
use Lyger\Middleware\AuthMiddleware;// Check if Authorization header exists$auth = new AuthMiddleware();// Validate against a specific token$auth = new AuthMiddleware('your-secret-token-here');// Custom header name$auth = new AuthMiddleware('token', 'X-API-Key');
The middleware expects the token in the Authorization header (or custom header):
Copy
# Bearer token formatAuthorization: Bearer your-secret-token-here# Or direct tokenAuthorization: your-secret-token-here
Middleware can be chained together using the setNext() method:
Copy
use Lyger\Middleware\CorsMiddleware;use Lyger\Middleware\RateLimitMiddleware;use Lyger\Middleware\AuthMiddleware;use Lyger\Middleware\LoggingMiddleware;$cors = new CorsMiddleware(['allowed_origins' => ['*']]);$rateLimit = new RateLimitMiddleware(100, 60);$auth = new AuthMiddleware('secret-token');$logger = new LoggingMiddleware();// Chain them together$cors->setNext($rateLimit) ->setNext($auth) ->setNext($logger);// Process a request through the chain$response = $cors->process($request, function ($req) use ($router) { return $router->dispatch($req);});