Skip to content

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.

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:

app/Middleware/EnsureApiKey.php
<?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:

Terminal window
$ 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.

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.

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);
}
}

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:

bootstrap/app.php
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;

Attach middleware to a single route with middleware(). It accepts an instance, a class name, a callable, or a throttle: alias:

routes.php
use App\Middleware\EnsureApiKey;
$router->get('/reports', [ReportController::class, 'index'])
->middleware(EnsureApiKey::class)
->middleware('throttle:30,1');

Middleware added to a registrar applies to every route registered through it. Pass a list to add several at once:

routes.php
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.

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).

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:

app/Middleware/ResolveTenant.php
<?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.

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) and get($key, $default) store values by key.
  • put($object) stores an object by its class; handler parameters of that type then receive it.
routes.php
use Nimbus\Http\RequestContext;
$router->get('/whoami', fn (RequestContext $context) => ['tenant' => $context->get('tenant')]);
Terminal window
$ 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 controller
public function show(Account $account): array
{
return ['id' => $account->id];
}

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.

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.
Terminal window
$ curl -i -H 'origin: https://app.example.com' http://127.0.0.1:3000/whoami
HTTP/1.1 200 OK
access-control-allow-origin: https://app.example.com
x-frame-options: DENY
content-type: application/json; charset=utf-8
x-response-time-ms: 1.02
permissions-policy: camera=(), microphone=(), geolocation=()
referrer-policy: no-referrer
x-content-type-options: nosniff
vary: origin
{"tenant":"public"}

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.

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 RequestContext or 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 readonly classes; they make accidental state impossible.

See Memory & State for the full set of rules.