Skip to content
Antares

Middleware & Pipeline

Middleware wraps the Dispatcher in layers. Each middleware receives the request, can modify it or short-circuit the pipeline, calls $next, and can modify the response on the way out.

Antares middleware uses its own small interface, handle(ServerRequestInterface $request, callable $next): ResponseInterface. It is not PSR-15.

Generate a class with the CLI:

Terminal window
php vendor/bin/antares make:middleware CorsMiddleware

This creates app/Middleware/CorsMiddleware.php, implementing Antares\Middleware\MiddlewareInterface. The example below is a CORS middleware you write yourself; Antares doesn’t ship one. CorsConfig is your own class, injected through the constructor (see Dependency Injection):

<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Config\CorsConfig;
use Antares\Middleware\MiddlewareInterface;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class CorsMiddleware implements MiddlewareInterface
{
public function __construct(private CorsConfig $config) {}
public function handle(ServerRequestInterface $request, callable $next): ResponseInterface
{
$headers = [
'Access-Control-Allow-Origin' => $this->config->origin,
'Access-Control-Allow-Methods' => $this->config->methods,
'Access-Control-Allow-Headers' => $this->config->headers,
'Access-Control-Allow-Credentials' => $this->config->credentials ? 'true' : 'false',
];
if ($request->getMethod() === 'OPTIONS') {
return new Response(204, $headers + [
'Access-Control-Max-Age' => (string) $this->config->maxAge,
]);
}
$response = $next($request)
->withHeader('Access-Control-Expose-Headers', $this->config->exposedHeaders);
foreach ($headers as $name => $value) {
$response = $response->withHeader($name, $value);
}
return $response;
}
}

Middleware is resolved through the container, the same way as controllers and guards, so constructor dependencies are injected automatically. Class-typed parameters are autowired; values that need primitives (like settings from .env) are registered as a singleton in a service provider:

use App\Config\CorsConfig;
use Antares\ServiceProvider;
use Antares\Container\Container;
class AppServiceProvider implements ServiceProvider
{
public function register(Container $container): void
{
$container->singleton(CorsConfig::class, fn() => new CorsConfig(
origin: $_ENV['CORS_ORIGIN'] ?? '*',
methods: 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
headers: 'Content-Type, Authorization',
exposedHeaders: '',
maxAge: 86400,
credentials: false,
));
}
}

A new middleware instance is built for every request. To reuse one instance, register the middleware itself as a singleton(). In worker mode (Swoole, FrankenPHP) a singleton lives across requests, so it must not keep per-request state; use scoped() for that. See Bindings & Singletons.

Pass middleware classes to ->middleware([...]) on the application. They run in the order given — the first item is the outermost layer:

Application::create(__DIR__ . '/..')
->middleware([
CorsMiddleware::class,
RateLimitMiddleware::class,
LogMiddleware::class,
])
->run();

The Pipeline wraps middleware around the Dispatcher using a recursive closure. The Dispatcher is always the innermost destination.

Every layer of the pipeline turns an exception into an error response on the spot, so error responses pass back through your middleware like any other response. That covers errors from routing, guards, DTOs and controllers, and also exceptions thrown by a middleware: the middleware outside it still see the resulting response. A CORS middleware listed first, for example, adds its headers to a 404, a 422, or a 429 thrown by a rate-limit middleware further in, so browser clients can read the error.

Middleware runs for every request, before the route is matched, including requests for routes that don’t exist.

Request → CorsMiddleware → RateLimitMiddleware → LogMiddleware → Dispatcher
↕
Response ← CorsMiddleware ← RateLimitMiddleware ← LogMiddleware ← Dispatcher