> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Middleware

> Middleware provides a convenient mechanism for filtering and intercepting HTTP requests entering your application. In Apivalk, middleware is executed in an "onion" style, where each middleware can perform actions before and after the subsequent middleware or the final controller.

## The Middleware Interface

Apivalk middleware is [PSR-15](https://www.php-fig.org/psr/psr-15/) middleware. Every middleware implements `Psr\Http\Server\MiddlewareInterface`:

```php theme={null}
public function process(
    ServerRequestInterface $request,
    RequestHandlerInterface $handler
): ResponseInterface;
```

* **`$request`**: The PSR-7 server request.
* **`$handler`**: The rest of the pipeline. Call `$handler->handle($request)` to hand the request on.

Third-party PSR-15 middleware plugs in directly.

### Apivalk context

Middleware in the routed stack reads what Apivalk knows about the request with `ApivalkContext::fromRequest($request)`:

* `getRoute()`: the route as the controller's `getRoute()` declares it.
* `getControllerClass()`: the controller class.
* `getRequest()`: the typed `ApivalkRequestInterface` (`header()`, `query()`, `body()`, `path()`, `getAuthIdentity()`, `setAuthIdentity()`, `getLocale()`, `getIp()`, ...).
* `getApivalkTraceId()`: the id Apivalk gave the request, see [Trace id](https://docs.apivalk.com/configuration.md#trace-id).
* `respond(AbstractApivalkResponse $response)`: turns a typed response into the PSR-7 response to return, e.g. `return $context->respond(new UnauthorizedApivalkResponse());`.

`ApivalkContext::fromRequest()` throws a `LogicException` outside the routed stack. A global middleware still gets the trace id with `ApivalkTraceId::fromRequest($request)`, e.g. for an access log that every response passes, the 404 and the 500 included:

```php theme={null}
use apivalk\apivalk\Http\ApivalkTraceId;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;

final readonly class AccessLogMiddleware implements MiddlewareInterface
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        $this->logger->info('Request handled', [
            'apivalk_trace_id' => ApivalkTraceId::fromRequest($request),
            'method' => $request->getMethod(),
            'path' => $request->getUri()->getPath(),
            'status' => $response->getStatusCode(),
        ]);

        return $response;
    }
}

$configuration->getGlobalMiddlewareStack()->add(new AccessLogMiddleware($logger));
```

Metrics per route, tracing and which stack to use for what: [Observability](https://docs.apivalk.com/core/observability.md).

### What reaches the controller

The typed request is populated before the routed middleware run, so a `withHeader()` or `withAttribute()` there does not change its bags. The controller still sees it: `$request->getServerRequest()` returns the PSR-7 request as the last middleware handed it on, e.g. `$request->getServerRequest()->getAttribute('request_id')`.

The body stream is rewound after population, so a middleware can read the raw body with `$request->getBody()->getContents()`.

## Middleware Stacks

`ApivalkConfiguration` has two `MiddlewareStack`s. Both take middleware with `add()` and run them in the order they were added.

| Stack | Runs | `ApivalkContext` | Use for |
| - | - | - | - |
| `getMiddlewareStack()` | after routing, around the controller | yes | authentication, security, rate limit, validation, anything that needs the route or the typed request |
| `getGlobalMiddlewareStack()` | before routing, for every request incl. 404, 405 and 500 | no | CORS preflight, request id, anything that must see every request |

### Onion Execution Pattern

Each middleware wraps everything added after it.

1. **Request Phase**: The first middleware added sees the request first and runs its logic before calling `$handler->handle($request)`.
2. **Next Call**: This continues until the last middleware hands the request to the controller.
3. **Response Phase**: The controller's response travels back through the middleware in reverse order, so the first middleware added sees the response last and can replace it (PSR-7 responses are immutable, use `withHeader()` and friends).

## Configuration

Middlewares are typically configured via the `ApivalkConfiguration` object during the bootstrapping phase.

```php theme={null}
$configuration = new ApivalkConfiguration($router);
$configuration->getMiddlewareStack()->add(new RequestValidationMiddleware());
$configuration->getGlobalMiddlewareStack()->add(new RequestIdMiddleware()); // your own, see the custom middleware guide
```

See [Write a custom middleware](https://docs.apivalk.com/how-to/custom-middleware.md) for a step-by-step guide, including recommended order.

## Built-in Middlewares

Apivalk comes with several essential middlewares out of the box. `AuthenticationMiddleware`, `SecurityMiddleware` and `RateLimitMiddleware` are `final readonly`, so wrap them in a middleware of your own instead of extending them:

* [Request Validation Middleware](https://docs.apivalk.com/middleware/request-validation.md)
* [Rate Limit Middleware](https://docs.apivalk.com/middleware/rate-limit.md)
* [Authentication Middleware](https://docs.apivalk.com/middleware/authentication.md)
* [Security Middleware](https://docs.apivalk.com/middleware/security.md)

See [Security Responsibilities](https://docs.apivalk.com/middleware/security-responsibilities.md) for what validation cannot catch and what your application is responsible for.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.