HTTP middleware
suggest changeHTTP middleware is software that sits between an incoming HTTP request and the core application handler that produces the response. Operating as an "onion" pipeline, middleware can inspect, modify, or reject requests before they reach your controller, and transform the response before it returns to the client. Common use cases include authentication, logging, CORS, rate limiting, and security header injection.
The PSR-15 Standard
In the PHP ecosystem, HTTP middleware is standardized by PSR-15 (psr/http-server-middleware), which operates on PSR-7 HTTP message interfaces (psr/http-message).
Install the PSR-15 and PSR-7 interfaces via Composer, plus a PSR-7 implementation such as nyholm/psr7 (used in Example 2):
composer require psr/http-server-middleware psr/http-message nyholm/psr7
The core contract consists of two interfaces:
MiddlewareInterface: Implemented by each middleware component.RequestHandlerInterface: Represents the next stage in the pipeline.
namespace Psr\Http\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
interface MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface;
}
Example 1: Execution Time Tracking Middleware
This middleware records the execution time of downstream handlers and adds an X-Response-Time header to the outgoing response:
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class ResponseTimeMiddleware implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
$startTime = hrtime(true);
// Delegate to the next middleware or application controller
$response = $handler->handle($request);
$durationMs = (hrtime(true) - $startTime) / 1_000_000;
// PSR-7 responses are immutable; withHeader returns a cloned response
return $response->withHeader('X-Response-Time', sprintf('%.2fms', $durationMs));
}
}
Example 2: Authentication and Short-Circuiting
Middleware can reject unauthorized requests immediately, terminating the pipeline early without calling $handler->handle():
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class AuthTokenMiddleware implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
$authHeader = $request->getHeaderLine('Authorization');
if (!str_starts_with($authHeader, 'Bearer secret-token-123')) {
// Short-circuit: Return HTTP 401 Unauthorized immediately
return new Response(401, ['Content-Type' => 'application/json'], json_encode([
'error' => 'Unauthorized: Invalid or missing token'
]));
}
// Attach parsed user data to the request attributes for downstream controllers
$authenticatedRequest = $request->withAttribute('user_id', 42);
return $handler->handle($authenticatedRequest);
}
}
How Middleware Pipeline Dispatching Works
A middleware runner executes components in sequence by wrapping each step in a RequestHandlerInterface:
class RelayQueueHandler implements RequestHandlerInterface
{
private array $queue;
private $fallbackHandler;
public function __construct(array $queue, callable $fallbackHandler)
{
$this->queue = $queue;
$this->fallbackHandler = $fallbackHandler;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
if (empty($this->queue)) {
return ($this->fallbackHandler)($request);
}
// Dequeue next middleware
$middleware = array_shift($this->queue);
return $middleware->process($request, $this);
}
}
Framework Integration
Popular PHP frameworks integrate middleware natively:
- Slim Framework:
$app->add(new ResponseTimeMiddleware()); $app->add(new AuthTokenMiddleware()); - Laravel:
class EnsureTokenIsValid { public function handle(Request $request, Closure $next): Response { if ($request->input('token') !== 'my-secret-token') { return redirect('home'); } return $next($request); } }