Middleware
Middleware wraps your route handlers. Each layer receives the request, can stop it early (for example, to reject a missing API key), or pass it on and then change the response that comes back (for example, to add a header). Authentication, CORS, rate limiting, security headers and request timing are all middleware in a Nimbus application.
Because PAM workers stay in memory, Nimbus builds the middleware pipeline once, when the application boots, and reuses it for every request. Writing middleware for PAM is the same as anywhere else, with one extra rule: keep request data out of middleware properties.
Defining Middleware
Section titled “Defining Middleware”A middleware class implements Pam\Contracts\Http\MiddlewareInterface. Its process() method receives the request, the response being built and the next handler in the chain:
<?php
declare(strict_types=1);
namespace App\Middleware;
use Nimbus\Http\HttpException;use Nimbus\Http\ProblemCode;use Pam\Contracts\Http\MiddlewareInterface;use Pam\Contracts\Http\RequestHandlerInterface;use Pam\Http\Request;use Pam\Http\Response;
final readonly class EnsureApiKey implements MiddlewareInterface{ public function process(Request $request, Response $response, RequestHandlerInterface $next): Response { if ($request->getHeader('x-api-key') !== getenv('API_KEY')) { throw new HttpException(401, ProblemCode::Unauthenticated, 'A valid API key is required.'); }
return $next->handle($request, $response); }}To let the request through, call $next->handle($request, $response) and return its result. To stop it, return a response or throw an HttpException, which Nimbus renders as a Problem Details response:
$ curl http://127.0.0.1:3000/api/admin/stats{"type":"https:\/\/pam.dev\/problems\/2","title":"A valid API key is required.","status":401,"code":2}$ curl -H 'x-api-key: secret' http://127.0.0.1:3000/api/admin/stats{"users":42}PAM has no generator for middleware; create the class in any autoloaded directory, such as app/Middleware.
Closure Middleware
Section titled “Closure Middleware”Small middleware can be a closure with the same three parameters:
use Pam\Contracts\Http\RequestHandlerInterface;use Pam\Http\Request;use Pam\Http\Response;
$app->middleware(function (Request $request, Response $response, RequestHandlerInterface $next): Response { $started = hrtime(true); $response = $next->handle($request, $response);
return $response->header('x-response-time-ms', (string) round((hrtime(true) - $started) / 1e6, 2));});Every middleware must return a Pam\Http\Response; returning anything else throws UnexpectedValueException.
Before and After Middleware
Section titled “Before and After Middleware”Code placed before $next->handle() runs before the handler; code placed after it runs on the way out. The timing middleware above is an “after” middleware. A “before” middleware does its work first:
final readonly class RejectMaintenance implements MiddlewareInterface{ public function process(Request $request, Response $response, RequestHandlerInterface $next): Response { if (is_file('/run/acme/maintenance')) { return $response->header('retry-after', '60')->json(['message' => 'Back soon.'], 503); }
return $next->handle($request, $response); }}Registering Middleware
Section titled “Registering Middleware”Global Middleware
Section titled “Global Middleware”Middleware registered on the application runs for every request, in registration order, before routing. That means it also runs for 404 and 405 responses, and it may change the request before a route is chosen:
use App\Middleware\ResolveTenant;use Nimbus\App;use Nimbus\Middleware\CorsMiddleware;use Nimbus\Middleware\SecurityHeadersMiddleware;
$app = new App();
$app->middleware(new CorsMiddleware(origins: ['https://app.example.com']));$app->middleware(new SecurityHeadersMiddleware(hsts: false));$app->middleware(ResolveTenant::class);
$app->routes(dirname(__DIR__) . '/routes.php');
return $app;Route Middleware
Section titled “Route Middleware”Attach middleware to a single route with middleware(). It accepts an instance, a class name, a callable, or a throttle: alias:
use App\Middleware\EnsureApiKey;
$router->get('/reports', [ReportController::class, 'index']) ->middleware(EnsureApiKey::class) ->middleware('throttle:30,1');Middleware Groups
Section titled “Middleware Groups”Middleware added to a registrar applies to every route registered through it. Pass a list to add several at once:
use Nimbus\RouteRegistrar;
$router->prefix('api/admin') ->middleware([EnsureApiKey::class, 'throttle:60,1']) ->group(function (RouteRegistrar $router): void { $router->get('stats', [StatsController::class, 'index']); $router->delete('cache', [CacheController::class, 'destroy']); });The order is: global middleware, then group middleware from the outermost group inwards, then route middleware, then the handler.
Shortcuts
Section titled “Shortcuts”Common middleware has a dedicated method on routes and registrars:
$router->get('/me', [ProfileController::class, 'show'])->auth();$router->put('/products/{product}', [ProductController::class, 'update'])->can('update', 'product');$router->post('/login', [LoginController::class, 'store'])->throttle(5);$router->get('/downloads/{file}', [DownloadController::class, 'show'])->signed();| Shortcut | Middleware |
|---|---|
auth() |
AuthenticateMiddleware with the Nimbus\Auth\Authenticator bound in the container. |
can($ability, $subject) |
AuthorizeMiddleware through the application’s Gate; implies auth(). |
throttle($max, $minutes) / rateLimit($name) |
ThrottleRequestsMiddleware; see Rate Limiting. |
signed() |
ValidateSignatureMiddleware with the UrlSigner (uses APP_KEY). |
Dependency Injection
Section titled “Dependency Injection”When you register middleware by class name, Nimbus resolves it from the container for each request, so its constructor can ask for services and for request-scoped values:
<?php
declare(strict_types=1);
namespace App\Middleware;
use Nimbus\Http\RequestContext;use Pam\Contracts\Http\MiddlewareInterface;use Pam\Contracts\Http\RequestHandlerInterface;use Pam\Http\Request;use Pam\Http\Response;
final readonly class ResolveTenant implements MiddlewareInterface{ public function __construct(private RequestContext $context) { }
public function process(Request $request, Response $response, RequestHandlerInterface $next): Response { $this->context->set('tenant', $request->getHeader('x-tenant', 'public'));
return $next->handle($request, $response); }}Middleware you register as an instance (new CorsMiddleware(...)) is created once and shared by every request of the worker.
Passing Data to Handlers
Section titled “Passing Data to Handlers”Nimbus\Http\RequestContext carries values from middleware to the handler of the same request, like Laravel’s $request->attributes. There is one context per request, and it is discarded when the request ends.
set($key, $value)andget($key, $default)store values by key.put($object)stores an object by its class; handler parameters of that type then receive it.
use Nimbus\Http\RequestContext;
$router->get('/whoami', fn (RequestContext $context) => ['tenant' => $context->get('tenant')]);$ curl -H 'x-tenant: acme' http://127.0.0.1:3000/whoami{"tenant":"acme"}With put(), a handler can type-hint the object directly. A typed value in the context wins over a route segment with the same name:
// In middleware$context->put($account);
// In the controllerpublic function show(Account $account): array{ return ['id' => $account->id];}Changing the Request
Section titled “Changing the Request”Pam\Http\Request is immutable. To change what the next layers see, build a new request and pass it to $next. This is how the built-in MethodOverrideMiddleware lets HTML forms send PUT, PATCH and DELETE:
return $next->handle(new Request( 'PUT', $request->path, $request->query(), $request->headers(), $request->body(), $request->routeParameters(),), $response);Request-changing middleware must be global, because routing happens after global middleware and before route middleware.
Built-in Middleware
Section titled “Built-in Middleware”Nimbus ships middleware in the Nimbus\Middleware namespace. The most common ones:
| Middleware | Purpose |
|---|---|
CorsMiddleware(origins, methods, headers, credentials, maxAge) |
Adds CORS headers for allowed origins. |
SecurityHeadersMiddleware(hsts, trustedProxies, contentSecurityPolicy, trustForwardedProto) |
Adds x-frame-options, x-content-type-options, referrer-policy, permissions-policy and, over HTTPS, strict-transport-security. |
RateLimitMiddleware(requestsPerSecond, burst, maxBuckets, idleTtlSeconds, store, keyResolver) |
Token-bucket limit with 429 Problem Details. |
ThrottleRequestsMiddleware |
Laravel-style throttle limits (created by throttle() and rateLimit()). |
DeadlineMiddleware(container, seconds) |
Answers 504 when the handler finishes after the deadline. |
MethodOverrideMiddleware |
Routes POST with _method or X-HTTP-Method-Override as PUT, PATCH or DELETE. |
AuthenticateMiddleware, AuthorizeMiddleware |
Authentication and authorization (see auth() and can()). |
ValidateSignatureMiddleware |
Signed URLs. |
IdempotencyMiddleware(store, ttlSeconds, required) |
Replays the stored response for a repeated Idempotency-Key. |
ResponseCacheMiddleware(store, ttlSeconds, keyResolver) |
Caches responses in a ResponseCacheStore. |
TransactionalMiddleware(transactions) |
Runs the handler inside a database transaction. |
QueryBudgetMiddleware(monitor, budget, failOnViolation) |
Caps query count and time per request. |
ObserveRequestMiddleware(observer) |
Reports request observations to a RequestObserver. |
EncryptCookiesMiddleware, StartSessionMiddleware, VerifyCsrfTokenMiddleware |
Cookies, sessions and CSRF for server-rendered pages. |
$ curl -i -H 'origin: https://app.example.com' http://127.0.0.1:3000/whoamiHTTP/1.1 200 OKaccess-control-allow-origin: https://app.example.comx-frame-options: DENYcontent-type: application/json; charset=utf-8x-response-time-ms: 1.02permissions-policy: camera=(), microphone=(), geolocation=()referrer-policy: no-referrerx-content-type-options: nosniffvary: origin
{"tenant":"public"}Request Lifecycle Observers
Section titled “Request Lifecycle Observers”For cross-cutting work that must see every request, including failures, register a Nimbus\Lifecycle\RequestLifecycleObserver. Observers start in registration order, finish in reverse order, receive the exception when the request failed, and run before the request scope is destroyed:
use Nimbus\Lifecycle\RequestLifecycleObserver;use Pam\Http\Request;use Pam\Http\Response;
$app->observe(new class implements RequestLifecycleObserver { public function starting(Request $request): void { }
public function finished(Request $request, Response $response, ?\Throwable $failure): void { if ($failure !== null) { \Pam\Observability\Telemetry::log('warning', 'Request failed', ['path' => $request->path]); } }});A failing observer is logged and never prevents other observers or the container cleanup from running.
Middleware and Persistent Workers
Section titled “Middleware and Persistent Workers”A middleware instance can serve many requests, some of them at the same time while others wait on I/O. Treat it as shared:
- Do not store the request, the user, the tenant or any other per-request value in a property of a middleware instance or in a static property. Use
RequestContextor a scoped container binding. - Keep caches and counters bounded. A middleware that appends to an array on every request leaks memory until the worker is recycled.
- Prefer
readonlyclasses; they make accidental state impossible.
See Memory & State for the full set of rules.
Next Steps
Section titled “Next Steps”- Controllers
- Error Handling
- HTTP Server for transport-level limits