> ## 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

All middlewares must implement the `apivalk\apivalk\Middleware\MiddlewareInterface`. This interface defines a single method:

```php theme={null}
public function process(
    ApivalkRequestInterface $request,
    AbstractApivalkController $controller,
    callable $next
): AbstractApivalkResponse;
```

* **`$request`**: The current request object.
* **`$controller`**: The target controller instance.
* **`$next`**: The next middleware in the stack or the final controller.

## Middleware Stack

The `MiddlewareStack` class manages the execution of middlewares. Middlewares are added to the stack and then processed in the order they were added.

### Onion Execution Pattern

When `MiddlewareStack::handle()` is called, it wraps the controller and all middlewares into a nested closure.

1. **Request Phase**: The first middleware executes its logic before calling `$next($request)`.
2. **Next Call**: This continues until the last middleware calls the actual controller.
3. **Response Phase**: The controller returns a response, which then travels back through the middleware stack in reverse order, allowing each middleware to modify the response if needed.

## 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());
```

See [Write a custom middleware](/how-to/custom-middleware) for a step-by-step guide, including recommended order.

## Built-in Middlewares

Apivalk comes with several essential middlewares out of the box:

* [Request Validation Middleware](/middleware/request-validation)
* [Rate Limit Middleware](/middleware/rate-limit)
* [Authentication Middleware](/middleware/authentication)
* [Security Middleware](/middleware/security)

See [Security Responsibilities](/middleware/security-responsibilities) for what validation cannot catch and what your application is responsible for.
