Middleware in Laravel Rust, for Laravel developers
Writing middleware as async functions, route and group middleware, parameters, skipping CSRF for webhooks, rate limits, body limits, timeouts and trusted proxies, shown on a food delivery app.
- middleware
- routing
- security
On this page
- A middleware is a function
- Asking for things, like a handler does
- Changing the response on the way out
- Registering: global, web and api
- On routes and groups
- Parameters, like role:manager
- The order things run in
- Webhooks: skipping CSRF
- The defaults you get for free
- The embeddable tracking widget
- Limits: body size, uploads, timeouts and throttling
- Behind a load balancer
- Tower layers, for free
- Quick reference
Middleware in Laravel Rust does the job it does in Laravel PHP: it sits between the request and your handler, and it can stop the request, change it, or change the response on the way out. If you’ve written a handle(Request $request, Closure $next) method, the shape will feel familiar. The class goes away, though. A middleware is an async function with an attribute on it.
The app in this guide is a food delivery platform. Couriers use a phone app that talks to an API, restaurants manage menus in a dashboard, the payment provider posts webhooks, and customers can track an order from a widget that partner sites embed. Each of those needs different middleware, which makes it a good tour.
A middleware is a function
The courier app sends a device token with each request. Here’s the check in Laravel PHP:
class EnsureCourierDevice
{
public function handle(Request $request, Closure $next): Response
{
if (! Device::isActive($request->header('X-Device-Token'))) {
abort(403);
}
return $next($request);
}
}
And in Laravel Rust:
// src/http/middleware/courier_device.rs
use laravel::http::{Next, Request, Response, middleware};
use crate::models::Device;
#[middleware]
pub async fn ensure_courier_device(request: Request, next: Next) -> laravel::Result<Response> {
let token = request.header("x-device-token").unwrap_or_default();
let active = Device::query()
.filter(Device::token.eq(token) & Device::revoked_at.is_null())
.count()
.await?;
laravel::abort_unless(active > 0, 403)?;
Ok(next.run(request).await)
}
next.run(request) is $next($request). Everything before it runs on the way in, and anything after it sees the response on the way out. Middleware live in src/http/middleware/ by convention, the way they live in app/Http/Middleware today.
Tip: the body isn’t read yet. Laravel Rust doesn’t read a request body until something asks for it. A middleware that only looks at headers, like this one, costs nothing extra. One that needs form or JSON input has to load the body first; the requests docs cover how.
Asking for things, like a handler does
In PHP you’d call auth()->user() or resolve a service from the container inside handle. In Laravel Rust, a middleware lists what it needs as arguments before request, exactly like a handler does, and Laravel passes them in. The support team wants every dashboard request tagged with the restaurant user who made it:
use laravel::auth::Auth;
use laravel::http::{Next, Request, Response, middleware};
use crate::models::User;
#[middleware]
pub async fn tag_restaurant_user(
auth: Auth<User>,
request: Request,
next: Next,
) -> laravel::Result<Response> {
if let Some(user) = auth.user().await? {
tracing::info!(user.id = user.id, path = request.path(), "dashboard request");
}
Ok(next.run(request).await)
}
There’s a catch that also exists in Laravel PHP, but it’s easier to hit here: global middleware run before the session starts. This one needs the logged-in user, so it belongs on routes or in the web group, never in the global list.
Changing the response on the way out
The platform team wants to see how long each request spent in the app. Code after next.run works on the response:
use std::time::Instant;
use laravel::http::{Next, Request, Response, middleware};
#[middleware]
pub async fn server_timing(request: Request, next: Next) -> Response {
let started = Instant::now();
let response = next.run(request).await;
response.with_header("server-timing", format!("app;dur={}", started.elapsed().as_millis()))
}
It returns Response, not laravel::Result<Response>, because it can’t fail. Rust makes you say so.
Registering: global, web and api
Laravel 11 moved middleware registration into bootstrap/app.php. Laravel Rust follows the same idea in src/app.rs:
// src/app.rs
use crate::http::middleware::{ensure_courier_device, server_timing, tag_restaurant_user};
Application::configure()
.with_middleware(|middleware, config| {
if config.app.debug {
middleware.append(server_timing);
}
middleware.web(|web| {
web.append(tag_restaurant_user);
});
middleware.api(|api| {
api.prepend(ensure_courier_device);
});
})
Routes in src/routes/web.rs run in the web group, routes in src/routes/api.rs in the api group, like routes/web.php and routes/api.php. The closure’s second argument is your configuration, so “only in debug” is a plain if.
On routes and groups
Most middleware belong on some routes. ->middleware('auth') becomes .middleware(Authenticate), using the type instead of a string alias:
use laravel::auth::{Authenticate, RequireVerifiedEmail};
route.get("/orders", orders::index).middleware(Authenticate);
route
.prefix("/payouts")
.middleware((Authenticate, RequireVerifiedEmail))
.group(|route| {
route.get("/", payouts::index);
route.post("/withdraw", payouts::withdraw);
});
A tuple runs the middleware in the order you wrote them. No aliases to register, and a misspelled middleware is a build error.
When the same set shows up in many route files, bundle it in a function, the counterpart of a named middleware group:
use laravel::auth::{Authenticate, RequireVerifiedEmail};
use laravel::http::MiddlewareGroup;
pub fn restaurant_staff() -> MiddlewareGroup {
MiddlewareGroup::new().with(Authenticate).with(RequireVerifiedEmail)
}
Parameters, like role:manager
Laravel PHP passes parameters as strings: ->middleware('role:manager'), which arrive as extra string $role arguments. In Laravel Rust, parameters go after next and can be any type that implements Clone, so an enum works:
use laravel::auth::Auth;
use laravel::http::{Next, Request, Response, middleware};
use crate::models::User;
#[derive(Clone, Copy, PartialEq)]
pub enum StaffRole {
Cook,
Manager,
}
#[middleware]
pub async fn require_role(
auth: Auth<User>,
request: Request,
next: Next,
role: StaffRole,
) -> laravel::Result<Response> {
let user = auth.user().await?;
laravel::abort_unless(user.is_some_and(|user| user.role == role), 403)?;
Ok(next.run(request).await)
}
You call it with only the parameter, and Laravel supplies the rest:
route.put("/menu/{item}", menu::update).middleware(require_role(StaffRole::Cook));
route.delete("/menu/{item}", menu::destroy).middleware(require_role(StaffRole::Manager));
role:manger in PHP is a silent 403 for everyone. StaffRole::Manger doesn’t compile.
The order things run in
When a request matches a route, middleware run in this order:
- Global middleware, on every request, even ones that match no route.
- The
weborapigroup. - Middleware on the route groups around the route, outer group first.
- Middleware on the route itself.
Within each step, they run in the order you added them, and the response comes back out in reverse. Global middleware run before the router has matched anything and before the session starts, which is why anything that needs the user or the session goes in step 2 or later.
Webhooks: skipping CSRF
The payment provider can’t send a CSRF token. In Laravel PHP you’d add the path to validateCsrfTokens(except: [...]). Laravel Rust lets you remove a middleware from one route or a whole group:
use laravel::http::middleware::PreventRequestForgery;
route
.prefix("/webhooks")
.without_middleware::<PreventRequestForgery>()
.group(|route| {
route.post("/payments", webhooks::payments);
route.post("/couriers", webhooks::couriers);
});
Or set the exception once, globally, by replacing the default:
.with_middleware(|middleware, _| {
middleware.replace(PreventRequestForgery::new().except(["webhooks/*"]));
})
Skipping CSRF means the webhook handler must verify the provider’s signature itself. That part is the same in every framework.
without_middleware can’t remove a global middleware, because those run before the route is known. Use replace or remove in src/app.rs for those.
The defaults you get for free
A new app already registers the middleware a Laravel developer would expect, plus a couple of security ones:
| Middleware | Where | What it does |
|---|---|---|
SecurityHeaders |
global | X-Frame-Options: SAMEORIGIN and X-Content-Type-Options: nosniff |
TrustHosts |
global | rejects hosts your app doesn’t serve, in production |
HandleCors |
global | answers cross-origin API requests |
TrimStrings, ConvertEmptyStringsToNull |
global | the input clean-up you know |
EncryptCookies, StartSession, PreventRequestForgery |
web |
cookies, session and CSRF |
TrimStrings skips passwords already. To keep another field untouched, such as an API secret a restaurant pastes in, replace it: middleware.replace(TrimStrings::except(["secret"])).
The embeddable tracking widget
Partner sites embed /track/{order} in an iframe, but SecurityHeaders sends X-Frame-Options: SAMEORIGIN on every response. Because it’s global, a single route can’t skip it. Move it into the groups, then exclude it on the widget route:
// src/app.rs
use laravel::http::middleware::SecurityHeaders;
.with_middleware(|middleware, _| {
middleware
.remove::<SecurityHeaders>()
.web(|web| {
web.prepend(SecurityHeaders);
})
.api(|api| {
api.prepend(SecurityHeaders);
});
})
// src/routes/web.rs
route.get("/track/{order}", tracking::widget).without_middleware::<SecurityHeaders>();
The trade-off: files in public/ and 404s for unknown routes no longer get those headers. If a CDN in front of the app adds them, that’s fine.
Limits: body size, uploads, timeouts and throttling
These are things you’d set in php.ini, nginx or a package in the PHP world. In Laravel Rust each one is a middleware, so it can be global, per group or per route, and the setting nearest the route wins.
Restaurants upload menu photos in bulk, and the monthly payout export is slow:
use laravel::http::middleware::{LimitUploads, Throttle, Timeout};
use laravel::time::ToSpan;
route.post("/menu/photos", menu::upload).middleware(LimitUploads::megabytes(100));
route.get("/payouts/export", payouts::export).middleware(Timeout::after(2.minutes()));
route.post("/support/messages", support::store).middleware(Throttle::per_minute(10));
The defaults are worth knowing before they bite: 2 MB for JSON and form bodies, 16 MB for multipart uploads, 30 seconds per request. Over the size limit, the client gets a 413 before your middleware or handler runs. Over time, a 503.
Behind a load balancer
Behind a load balancer that ends TLS, request.ip() is the balancer’s address and URLs start with http:// until you trust it. This is trustProxies in Laravel PHP:
.with_middleware(|middleware, _| {
middleware.trust_proxies(["10.0.0.0/8"]);
})
On Laravel Cloud you don’t need this; the platform’s proxy is trusted unless you list your own.
Tower layers, for free
Laravel Rust runs on Axum, so the whole Tower ecosystem is available. Response compression, for example, is one line with tower-http:
use laravel::http::layer;
use tower_http::compression::CompressionLayer;
.with_middleware(|middleware, _| {
middleware.append(layer(CompressionLayer::new()));
})
Quick reference
| Laravel PHP | Laravel Rust |
|---|---|
handle(Request $request, Closure $next) |
#[middleware] async fn(request: Request, next: Next) |
return $next($request); |
Ok(next.run(request).await) |
->middleware('auth') |
.middleware(Authenticate) |
->middleware('role:manager') |
.middleware(require_role(StaffRole::Manager)) |
->withoutMiddleware(...) |
.without_middleware::<T>() |
$middleware->web(append: ...) |
middleware.web(|web| { web.append(...); }) |
validateCsrfTokens(except: ...) |
PreventRequestForgery::new().except([...]) |
trustProxies(at: ...) |
middleware.trust_proxies([...]) |
throttle:10,1 |
Throttle::per_minute(10) |
Where do I register middleware in Laravel Rust?
In src/app.rs, inside Application::configure().with_middleware(...). Use append or prepend for global middleware, and middleware.web(...) or middleware.api(...) for the two route groups, the same split as bootstrap/app.php in Laravel 11 and later.
How do I exclude a webhook route from CSRF in Laravel Rust?
Call .without_middleware::<PreventRequestForgery>() on the route or on a group, or replace the default with PreventRequestForgery::new().except(["webhooks/*"]) in src/app.rs.
Can Laravel Rust use Tower or Axum middleware?
Yes. Laravel Rust is built on Axum, so any Tower layer can be wrapped with laravel::http::layer(...) and appended like any other middleware.