Middleware
Middleware wraps your handlers to inspect or change requests and responses: authenticate a caller, enforce a rate limit, replay an idempotent payment or add security headers. PAM HTTP compiles the global pipeline once per worker, in registration order, when the application first handles work.
Defining Middleware
Section titled “Defining Middleware”Closures
Section titled “Closures”A middleware callable receives the request, the response and the next handler, and must return a
Pam\Http\Response:
use Pam\Contracts\Http\RequestHandlerInterface;use Pam\Http\Request;use Pam\Http\Response;
$app->middleware(static function (Request $request, Response $response, RequestHandlerInterface $next): Response { $started = hrtime(true); $response = $next->handle($request, $response);
return $response->header('server-timing', 'app;dur=' . (hrtime(true) - $started) / 1e6);});Middleware Classes
Section titled “Middleware Classes”Implement Pam\Contracts\Http\MiddlewareInterface:
namespace App\Http\Middleware;
use Pam\Api\Http\HttpException;use Pam\Api\Http\ProblemCode;use Pam\Contracts\Http\MiddlewareInterface;use Pam\Contracts\Http\RequestHandlerInterface;use Pam\Http\Request;use Pam\Http\Response;
final readonly class RequireJson implements MiddlewareInterface{ public function process(Request $request, Response $response, RequestHandlerInterface $next): Response { $type = $request->getHeader('content-type', '');
if ($request->body() !== '' && !str_starts_with($type, 'application/json')) { throw new HttpException(422, ProblemCode::ValidationFailed, 'Send a JSON body.'); }
return $next->handle($request, $response); }}Register an instance, or the class name. A class name is resolved from the container on every request, so the middleware can receive constructor dependencies (including scoped ones):
$app->middleware(new RequireJson());$app->middleware(RequireJson::class);Registering Middleware
Section titled “Registering Middleware”| Scope | How | Runs |
|---|---|---|
| Global | $app->middleware($middleware) |
For every request, including 404 and 405. |
| Group | $app->prefix('/api')->middleware([...])->group(...) |
For each route in the group. |
| Route | $app->get(...)->middleware($middleware) |
For that route only, after global middleware. |
$app->middleware(new SecurityHeadersMiddleware());
$app->prefix('/admin') ->middleware([AuthenticateAdmin::class, new RateLimitMiddleware(requestsPerSecond: 5)]) ->group(function (RouteRegistrar $routes): void { $routes->delete('/users/{id}', [UserController::class, 'destroy']) ->middleware(new AuthorizeMiddleware($app->container(), 'users.delete')); });Built-in Middleware
Section titled “Built-in Middleware”All built-in middleware lives in Pam\Api\Middleware.
| Middleware | Purpose |
|---|---|
CorsMiddleware |
Cross-origin headers and preflight answers. |
RateLimitMiddleware |
Token-bucket rate limiting with pluggable stores. |
SecurityHeadersMiddleware |
Conservative browser security headers and HSTS. |
IdempotencyMiddleware |
Replay retried requests that carry an Idempotency-Key. |
ResponseCacheMiddleware |
Cache successful GET/HEAD responses. |
DeadlineMiddleware |
Give the request a time budget. |
TransactionalMiddleware |
Run the request inside a database transaction. |
AuthenticateMiddleware, AuthorizeMiddleware |
See Authentication & Tenancy. |
ResolveTenantMiddleware |
See Tenancy. |
QueryBudgetMiddleware, ArcanoLifecycleMiddleware |
See Database. |
ObserveRequestMiddleware |
See Observability. |
use Pam\Api\Middleware\CorsMiddleware;
$app->middleware(new CorsMiddleware( origins: ['https://app.example.com'], methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], // default headers: ['content-type', 'authorization'], // default credentials: true, maxAge: 600, // default));Requests from listed origins get access-control-allow-origin and vary: origin. A valid preflight (OPTIONS
with an allowed access-control-request-method and headers) is answered with 204; a disallowed method or
header gets 403. Requests without an Origin header, or from other origins, pass through untouched.
'*' allows every origin. Combined with credentials: true, the middleware echoes the caller’s origin instead of
*, which is rarely what you want for an authenticated API.
Rate Limiting
Section titled “Rate Limiting”RateLimitMiddleware is a token bucket. Each key refills at requestsPerSecond and holds up to burst tokens
(requestsPerSecond when burst is 0):
use Pam\Api\Middleware\RateLimitMiddleware;
$app->middleware(new RateLimitMiddleware( requestsPerSecond: 20, burst: 40,));Every response carries x-ratelimit-limit and x-ratelimit-remaining. A rejected request gets 429, a
retry-after header and Problem Details code 6.
By default the key is REMOTE_ADDR and buckets live in a bounded in-memory store (maxBuckets: 65_536,
idle buckets evicted after idleTtlSeconds: 300). Memory buckets are per worker. For limits shared by all
workers and nodes, pass a store backed by Redis or another atomic system, and choose the key:
use Pam\Api\RateLimit\RateLimitDecision;use Pam\Api\RateLimit\RateLimitStore;
final readonly class RedisRateLimitStore implements RateLimitStore{ public function consume(string $key, int $requestsPerSecond, int $capacity, float $now): RateLimitDecision { // Atomically refill and take a token (for example with a Lua script). }}
$app->middleware(new RateLimitMiddleware( requestsPerSecond: 20, burst: 40, store: new RedisRateLimitStore($redis), keyResolver: static fn (Request $request): string => 'token:' . hash('sha256', $request->getHeader('authorization', 'anonymous')),));Behind a reverse proxy, use Pam\Api\Http\ClientIpResolver in the key resolver. It trusts x-forwarded-for only
when REMOTE_ADDR is one of the proxies you list:
use Pam\Api\Http\ClientIpResolver;
$ips = new ClientIpResolver(trustedProxies: ['10.0.0.5']);
$app->middleware(new RateLimitMiddleware( requestsPerSecond: 20, keyResolver: static fn (Request $request): string => 'ip:' . $ips->resolve($request),));Security Headers
Section titled “Security Headers”$app->middleware(new SecurityHeadersMiddleware(hsts: true));Adds x-content-type-options: nosniff, x-frame-options: DENY, referrer-policy: no-referrer and
permissions-policy: camera=(), microphone=(), geolocation=(). When hsts is true (the default) and the request
arrived over HTTPS, it also sets strict-transport-security: max-age=31536000; includeSubDomains.
Idempotency Keys
Section titled “Idempotency Keys”Clients retry. IdempotencyMiddleware makes unsafe operations such as payments safe to repeat:
use Pam\Api\Idempotency\MemoryIdempotencyStore;use Pam\Api\Middleware\IdempotencyMiddleware;
$app->post('/payments', [PaymentController::class, 'store']) ->middleware(new IdempotencyMiddleware(new MemoryIdempotencyStore(), ttlSeconds: 86_400, required: true));- The first request with an
Idempotency-Keyruns normally and its response is stored. - A retry with the same key and the same method, path and body gets the stored response plus
idempotency-replayed: true, without running the handler. - The same key with a different payload gets
409(code5). - A missing key gets
422whenrequiredistrue; keys longer than 255 bytes or with non-printable characters are rejected.
Response Cache
Section titled “Response Cache”use Pam\Api\Cache\MemoryResponseCacheStore;use Pam\Api\Middleware\ResponseCacheMiddleware;
$app->get('/api/catalog', [CatalogController::class, 'index']) ->middleware(new ResponseCacheMiddleware(new MemoryResponseCacheStore(), ttlSeconds: 60));Only GET and HEAD are cached, and only 2xx responses are stored. Responses carry x-cache: MISS or
x-cache: HIT. The default key hashes the method, path and query; pass keyResolver to vary by something else,
such as the tenant. Never cache user-specific responses under a shared key.
Deadlines
Section titled “Deadlines”DeadlineMiddleware publishes a Pam\Api\Runtime\Deadline for the request. Long-running code checks it and stops
early:
$app->middleware(new DeadlineMiddleware($app->container(), seconds: 2.0));use Pam\Api\Runtime\Deadline;
public function index(Deadline $deadline, Response $response): Response{ foreach ($this->reports->batches() as $batch) { $deadline->throwIfExpired(); // 504 Problem Details, code 7 $this->reports->render($batch); }
return $response->json(['status' => 'done']);}The middleware also checks the deadline after the handler returns. Deadlines are cooperative: they do not
interrupt blocking calls. The listener’s requestTimeoutMs remains the hard limit.
Transactions
Section titled “Transactions”TransactionalMiddleware runs the rest of the pipeline inside TransactionManager::transaction(). With the
Arcano integration, ArcanoManager is the transaction manager:
$app->post('/orders', [OrderController::class, 'store']) ->middleware(new TransactionalMiddleware($app->container()->get(TransactionManager::class)));Stores and Multiple Workers
Section titled “Stores and Multiple Workers”The memory stores (MemoryRateLimitStore, MemoryIdempotencyStore, MemoryResponseCacheStore,
MemoryTokenRevocationStore) are bounded and hold at most 10,000 records by default (65,536 buckets for rate
limiting). They are meant for development, tests and single-worker deployments. Each worker has its own copy, so
in a cluster implement the store interfaces (RateLimitStore, IdempotencyStore, ResponseCacheStore,
TokenRevocationStore) on shared, atomic storage.