Middleware
php-via runs PSR-15 middleware for cross-cutting concerns such as authentication,
CORS, logging and rate limiting. Middleware runs on page loads, actions and plain routes; implement
SseAwareMiddleware to run on SSE connects too.
How it works
Middleware follows the PSR-15
onion model. Each middleware gets a PSR-7 ServerRequestInterface and either answers
itself or passes the request on with $handler->handle(). php-via converts the
OpenSwoole request to PSR-7 only when middleware is registered, so an app without middleware pays
nothing.
On a page load and an action, php-via writes the status and the body itself once the request reaches it.
A response the middleware returns without calling $handler->handle(), such as a redirect
to a login page, goes out as it is. The response that $handler->handle() returns has an
empty body, and the headers a middleware adds to it go out with php-via's response, such as
Content-Security-Policy, Strict-Transport-Security or
X-Frame-Options. php-via keeps its own headers: it writes Content-Type,
Content-Length, Content-Encoding, Transfer-Encoding and
Connection, and the session cookie, a cookie it set and a header it set win over the
middleware's. A Vary or Content-Security-Policy header of both goes out with
both values, so a browser enforces both policies. Dev mode logs a warning once for each header of the
middleware it leaves out. See Content Security Policy for a policy
with a nonce. On a plain route the handler's response goes out as it is,
with what middleware added.
| Request | Global middleware | Route middleware |
|---|---|---|
| Page load | yes | yes |
| Rebuilding a tab that was away (revival) | as for the action or connect that rebuilds it | yes, on a GET of the page's URL |
| Action | yes | no |
| SSE connect | SseAwareMiddleware only | no |
route() | yes | yes |
Global middleware
Register global middleware with $app->middleware() before $app->start():
use Tuupola\Middleware\CorsMiddleware;
$app->middleware(new CorsMiddleware([
'origin' => ['https://example.com'],
'methods' => ['GET', 'POST'],
'headers.allow' => ['Content-Type', 'Authorization'],
'credentials' => true,
]));Per-route middleware
Attach middleware to one route with the RouteDefinition that page(),
mount() and route() return, or to several with group():
$app->page('/admin', fn (Context $c) => $c->view('admin.html.twig'))
->middleware(new AuthMiddleware($app));
$app->page('/reports', fn (Context $c) => $c->view('reports.html.twig'))
->middleware(new AuthMiddleware($app), new AuditMiddleware());
$app->group('/account', function (Via $app): void {
$app->page('/', fn (Context $c) => $c->view('account.html.twig'));
$app->page('/billing', fn (Context $c) => $c->view('billing.html.twig'));
})->middleware(new AuthMiddleware($app));Route middleware runs after the global middleware: global, then route, then the page handler.
Writing middleware
Implement Psr\Http\Server\MiddlewareInterface. Every request carries the visitor's session
id in the via.session attribute, the id $c->getSessionId() returns, so
middleware never reads the session cookie, whose name withSecureCookie() changes. A request
without the cookie gets the id of the session the page then starts. Pass data on with
$request->withAttribute(): the page handler reads it with
$c->getRequestAttribute().
use Mbolli\PhpVia\Via;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class AuthMiddleware implements MiddlewareInterface {
public function __construct(private Via $app) {}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
$user = $this->app->getSessionData($request->getAttribute('via.session'), 'user');
if ($user === null) {
return new Response(302, ['Location' => '/login']);
}
// Available in the page handler as $c->getRequestAttribute('user')
return $handler->handle($request->withAttribute('user', $user));
}
}$request->withAttribute().
SSE-aware middleware
Global middleware skips the SSE connect unless it implements the SseAwareMiddleware
marker interface. Implement it when the stream needs the same gate as the page, such as an auth check:
use Mbolli\PhpVia\Http\Middleware\SseAwareMiddleware;
final class AuthMiddleware implements SseAwareMiddleware {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
// runs on page loads, actions and SSE connects
return $handler->handle($request);
}
}
$app->middleware(new AuthMiddleware());The marker counts only for global middleware. Route middleware never runs on an SSE connect, so a tab that was open before a logout keeps its stream until it reloads or its context expires.
Request attributes in handlers and actions
The attributes middleware sets reach the Context:
$app->page('/dashboard', function (Context $c): void {
$user = $c->getRequestAttribute('user');
$c->view('dashboard.html.twig', ['name' => $user['name']]);
})->middleware(new AuthMiddleware($app));
In an action, getRequestAttribute() returns what the global middleware set on that action's
request; each action has its own, also when two run at once. Route middleware does not run on actions,
so an attribute it sets is there in the page handler only: read it there and pass it into the action's
closure, or register the middleware globally. Outside a request, such as in a timer, the attributes are
those of the page request.
When a tab comes back after its context was destroyed, php-via rebuilds the context and runs the page handler again behind the route's middleware, on a GET of the page's URL with the cookies of the request that rebuilds it. An auth gate therefore applies again, and its attributes reach the handler. When the middleware answers itself, such as with a redirect to the login page, the tab reloads and the page load gets the middleware's answer. See Lifecycle → Revival.
Plain routes
$app->route() serves a PSR-15 handler with no context, shell or template, for JSON,
webhooks or an MCP server, behind the global and the route's middleware. The request carries the path
parameters and via.session as attributes, and the handler's response goes out with what the
middleware added. php-via checks no Origin header on these routes, so add CSRF or auth
middleware where a route changes state.
$app->route(['GET', 'OPTIONS'], '/api/items/{id}', new ItemHandler())
->middleware(new ApiKeyMiddleware());See route() for methods, HEAD and uploads.
Live example: auth middleware
The Login Flow example protects /examples/login/dashboard
with an AuthMiddleware. Visitors who are not logged in go to the login form; logged-in
visitors see a dashboard with their session data. Its login and logout call
regenerateSession().
Built-in security
php-via has these protections without any middleware:
CSRF protection
Actions check the Origin header. Configure the allowed origins with
withTrustedOrigins():
$config = (new Config())
->withTrustedOrigins(['https://myapp.com', 'https://staging.myapp.com']);null(default): the origin's host must match theHostheader[]: refuse every request that carries an origin['https://example.com']: only these origins
Outside dev mode an action without an Origin header gets 403 in every case, unless
withAllowMissingOrigin() lets non-browser clients through. Plain routes are not checked.
Session cookies
php-via accepts only session ids in the form it issues, 32 lowercase hex characters; any other cookie
value starts a new session. Turn on withSecureCookie() for a site served over HTTPS: the
cookie gets the __Host- prefix, which requires HTTPS, Path=/ and no
Domain, and the plain cookie is then ignored.
$config = (new Config())
->withSecureCookie(true); // __Host-via_session_id; Secure; SameSite=LaxSession rotation
A login should give the session a new cookie, so a cookie someone planted or read before it no longer
reaches the account. In an action, call $c->regenerateSession(); in middleware or a
route() handler, $app->regenerateSession($request), before
$handler->handle(). The session keeps its id, so via.session, session data
and the session's tabs stay as they are. The session rotates at the call: from then on the old cookie
opens no page. For 2 more seconds it reaches the actions and streams of tabs that exist, and then the
streams opened with it end. Call it at logout too, with
clearSessionData(). See regenerateSession().
Action rate limiting
A per-IP sliding-window limit for actions, which answers 429 past it:
$config = (new Config())
->withActionRateLimit(100, 60); // at most 100 actions per 60 seconds per IPNext steps
- Actions: server-side event handlers
- Lifecycle: connect, disconnect, revival and cleanup
- Deployment: production configuration