Middleware
- Introduction
- Defining middleware
- Registering middleware
- Middleware parameters
- Laravel's default middleware
- Limits
- Rate limiting
- Cache headers
- Tower layers
Introduction
Middleware let you inspect and filter the HTTP requests that enter your application. For example, Laravel includes a middleware that checks whether the user is logged in. If they aren't, the middleware redirects them to your application's login page. If they are, the middleware lets the request continue on to your handler.
You may write middleware of your own for all kinds of tasks besides authentication. For example, a logging middleware might record every request your application receives, and another might add a header to every response. Laravel includes several middleware of its own, such as the ones that start the session and protect your forms from cross-site request forgery. Your own middleware usually live in your application's src/http/middleware directory.
Defining middleware
A middleware is an async function marked with #[middleware]. It receives the request and next, which passes the request on to the rest of your application, and it returns the response. You may keep your middleware in src/http/middleware. For example, this middleware only lets a request through when it carries the right API token:
1use laravel::http::{Next, Request, Response, middleware};23#[middleware]4pub async fn ensure_token_is_valid(request: Request, next: Next) -> laravel::Result<Response> {5 if request.header("x-api-token") != Some("my-secret-token") {6 laravel::abort!(403);7 }89 Ok(next.run(request).await)10}1use laravel::http::{Next, Request, Response, middleware};23#[middleware]4pub async fn ensure_token_is_valid(request: Request, next: Next) -> laravel::Result<Response> {5 if request.header("x-api-token") != Some("my-secret-token") {6 laravel::abort!(403);7 }89 Ok(next.run(request).await)10}
If the token doesn't match, the middleware stops the request with a 403 error page. Otherwise, next.run(request) passes the request deeper into your application, and the middleware returns the response that comes back. A middleware that never fails may return Response instead of laravel::Result<Response>.
This example only reads a header. Laravel doesn't read a request's body until something asks for it, so a middleware that needs form or JSON input has to load the body first. To learn more, check out the requests guide's section on input in middleware.
Middleware arguments
A middleware may ask for the same arguments a handler does, such as a service, a configuration section, a route parameter, or the logged-in user. Put these arguments before request. For example, this middleware logs which user made each request:
1use laravel::auth::Auth;2use laravel::http::{Next, Request, Response, middleware};34#[middleware]5pub async fn log_user(6 auth: Auth<User>,7 request: Request,8 next: Next,9) -> laravel::Result<Response> {10 if let Some(user) = auth.user().await? {11 tracing::info!(user.id = user.id, path = request.path(), "Handling request");12 }1314 Ok(next.run(request).await)15}1use laravel::auth::Auth;2use laravel::http::{Next, Request, Response, middleware};34#[middleware]5pub async fn log_user(6 auth: Auth<User>,7 request: Request,8 next: Next,9) -> laravel::Result<Response> {10 if let Some(user) = auth.user().await? {11 tracing::info!(user.id = user.id, path = request.path(), "Handling request");12 }1314 Ok(next.run(request).await)15}
Keep in mind that log_user can only find the logged-in user after the session has started, and global middleware run before that happens. So instead of registering a middleware like this globally, attach it to your routes or add it to the web middleware group.
Middleware and responses
Some middleware do their work after the handler, such as adding a header to every response. Code before next.run runs before your handler, and code after it runs once the response is ready. For example, this middleware measures how long the request took, and adds a Server-Timing header to the response:
1use std::time::Instant;23use laravel::http::{Next, Request, Response, middleware};45#[middleware]6pub async fn add_server_timing(request: Request, next: Next) -> Response {7 let started = Instant::now();89 let response = next.run(request).await;1011 response.with_header("server-timing", format!("app;dur={}", started.elapsed().as_millis()))12}1use std::time::Instant;23use laravel::http::{Next, Request, Response, middleware};45#[middleware]6pub async fn add_server_timing(request: Request, next: Next) -> Response {7 let started = Instant::now();89 let response = next.run(request).await;1011 response.with_header("server-timing", format!("app;dur={}", started.elapsed().as_millis()))12}
Registering middleware
Global middleware
To run a middleware on every HTTP request to your application, such as the add_server_timing middleware above, append it to the global middleware in src/app.rs:
1use crate::http::middleware::add_server_timing;23Application::configure()4 .with_middleware(|middleware, _| {5 middleware.append(add_server_timing);6 })1use crate::http::middleware::add_server_timing;23Application::configure()4 .with_middleware(|middleware, _| {5 middleware.append(add_server_timing);6 })
append adds the middleware to the end of the global middleware, and prepend adds it to the beginning. The closure's second argument is your application's configuration, so you may add a middleware only in some environments. For example, this adds the timing header only while debug mode is on:
1.with_middleware(|middleware, config| {2 if config.app.debug {3 middleware.append(add_server_timing);4 }5})1.with_middleware(|middleware, config| {2 if config.app.debug {3 middleware.append(add_server_timing);4 }5})
Assigning middleware to routes
Most middleware belong on some routes rather than all of them. To assign middleware to a route or a route group, call middleware in your route file:
1use laravel::auth::Authenticate;23route.get("/profile", profile::show).middleware(Authenticate);45route.middleware(Authenticate).group(|route| {6 route.get("/settings", settings::show);7});1use laravel::auth::Authenticate;23route.get("/profile", profile::show).middleware(Authenticate);45route.middleware(Authenticate).group(|route| {6 route.get("/settings", settings::show);7});
To assign several middleware at once, pass a tuple. Laravel runs them in the order you list them, so in this example, Authenticate makes sure the user is logged in before RequireVerifiedEmail checks their email address:
1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.get("/billing", billing::show).middleware((Authenticate, RequireVerifiedEmail));1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.get("/billing", billing::show).middleware((Authenticate, RequireVerifiedEmail));
Middleware groups
When several routes share the same set of middleware, such as billing pages that need a logged-in user with a verified email address, you may bundle the middleware into a MiddlewareGroup. Build the group in a function, then attach it to your routes as you would a single middleware:
1use laravel::auth::{Authenticate, RequireVerifiedEmail};2use laravel::http::MiddlewareGroup;34pub fn verified() -> MiddlewareGroup {5 MiddlewareGroup::new().with(Authenticate).with(RequireVerifiedEmail)6}78pub fn routes(route: &mut Router) {9 route.prefix("/billing").middleware(verified()).group(|route| {10 // ...11 });12}1use laravel::auth::{Authenticate, RequireVerifiedEmail};2use laravel::http::MiddlewareGroup;34pub fn verified() -> MiddlewareGroup {5 MiddlewareGroup::new().with(Authenticate).with(RequireVerifiedEmail)6}78pub fn routes(route: &mut Router) {9 route.prefix("/billing").middleware(verified()).group(|route| {10 // ...11 });12}
Laravel also has two groups of its own. Routes in src/routes/web.rs run within the web group, and routes in src/routes/api.rs run within the api group. To add a middleware to either group, call web or api in src/app.rs. Here, every web page gets the timing header, and every API request must carry a valid token:
1.with_middleware(|middleware, _| {2 middleware.web(|web| {3 web.append(add_server_timing);4 });56 middleware.api(|api| {7 api.prepend(ensure_token_is_valid);8 });9})1.with_middleware(|middleware, _| {2 middleware.web(|web| {3 web.append(add_server_timing);4 });56 middleware.api(|api| {7 api.prepend(ensure_token_is_valid);8 });9})
Excluding middleware
Sometimes a route shouldn't run one of its group's middleware. For example, Stripe can't send a CSRF token with its webhook requests, so your webhook route needs to skip the web group's CSRF protection. Call without_middleware with the middleware's type:
1use laravel::http::middleware::PreventRequestForgery;23route4 .post("/webhooks/stripe", webhooks::stripe)5 .without_middleware::<PreventRequestForgery>();1use laravel::http::middleware::PreventRequestForgery;23route4 .post("/webhooks/stripe", webhooks::stripe)5 .without_middleware::<PreventRequestForgery>();
If several routes need the same exception, such as all of your webhooks, call without_middleware before group instead. The routes in nested groups skip the middleware too:
1route.prefix("/webhooks").without_middleware::<PreventRequestForgery>().group(|route| {2 route.post("/stripe", webhooks::stripe);3 route.post("/github", webhooks::github);4});1route.prefix("/webhooks").without_middleware::<PreventRequestForgery>().group(|route| {2 route.post("/stripe", webhooks::stripe);3 route.post("/github", webhooks::github);4});
To exclude a middleware you wrote with #[middleware], name its function, as in without_middleware::<ensure_token_is_valid>().
without_middleware can't exclude a global middleware, because global middleware run before Laravel knows which route matched. To change a global middleware, replace or remove it.
Ordering
When a request reaches a route, its middleware run in this order:
- The global middleware, which run on every request.
- The
weborapimiddleware group, depending on whether the route is defined insrc/routes/web.rsorsrc/routes/api.rs. - Any middleware you assigned to a route group that contains the route. When groups are nested, the outer group's middleware run before the inner group's.
- Any middleware attached directly to the route's definition, such as
route.get(..).middleware(Authenticate).
Within each step, middleware run in the order you added them. On the way out, they see the response in the reverse order.
Global middleware run before Laravel matches a route, so they also run for requests that match no route. They also run before the web group starts the session, so they can't see the session or the logged-in user. A middleware that needs either one belongs on your routes, or in the web group, where it runs after StartSession.
Middleware parameters
Some middleware need a value from the route that uses them, such as the role a user must have to see a page. Put these parameters after next. For example, say each User has a role, and some routes are only for editors or admins:
1use laravel::auth::Auth;2use laravel::http::{Next, Request, Response, middleware};34#[derive(Clone, Copy, PartialEq)]5pub enum Role {6 Editor,7 Admin,8}910#[middleware]11pub async fn ensure_role(12 auth: Auth<User>,13 request: Request,14 next: Next,15 role: Role,16) -> laravel::Result<Response> {17 let user = auth.user().await?;1819 laravel::abort_unless(user.is_some_and(|user| user.role == role), 403)?;2021 Ok(next.run(request).await)22}1use laravel::auth::Auth;2use laravel::http::{Next, Request, Response, middleware};34#[derive(Clone, Copy, PartialEq)]5pub enum Role {6 Editor,7 Admin,8}910#[middleware]11pub async fn ensure_role(12 auth: Auth<User>,13 request: Request,14 next: Next,15 role: Role,16) -> laravel::Result<Response> {17 let user = auth.user().await?;1819 laravel::abort_unless(user.is_some_and(|user| user.role == role), 403)?;2021 Ok(next.run(request).await)22}
To use ensure_role on a route, call it with the role the route requires, such as ensure_role(Role::Admin). You don't pass auth, request, or next yourself, because Laravel provides those when the request comes in. In this example, editors may update posts, but only admins may delete them:
1route.put("/posts/{post}", posts::update).middleware(ensure_role(Role::Editor));2route.delete("/posts/{post}", posts::destroy).middleware(ensure_role(Role::Admin));1route.put("/posts/{post}", posts::update).middleware(ensure_role(Role::Editor));2route.delete("/posts/{post}", posts::destroy).middleware(ensure_role(Role::Admin));
Laravel clones the parameters for each request, so their types must implement Clone.
Laravel's default middleware
A new Laravel application comes with several middleware already registered. Some run on every request, such as the ones that trim whitespace from form input and answer cross-origin requests to your API. Others run only for routes in the web group, where they start the session, encrypt your cookies, and protect your forms from cross-site request forgery. You don't need to set any of them up yourself, but it helps to know what each one does. They run in the order listed:
| Middleware | Where | What it does |
|---|---|---|
| Trusted proxies | Before all others | Removes X-Forwarded-* headers unless the request came through a trusted proxy. |
SecurityHeaders |
Global | Adds security headers to every response. |
TrustHosts |
Global | Rejects requests for hosts your application doesn't serve. |
HandleCors |
Global | Answers cross-origin requests to your API. |
SpoofMethods |
Global | Lets HTML forms send PUT, PATCH, and DELETE requests. |
TrimStrings |
Global | Trims whitespace from string input, except passwords. |
ConvertEmptyStringsToNull |
Global | Turns empty string input into null. |
EncryptCookies |
web |
Encrypts the cookies you set, and decrypts them when they come back. |
StartSession |
web |
Loads the session before the request and saves it after. |
PreventRequestForgery |
web |
Rejects cross-site requests that change state, as CSRF protection explains. |
Customizing the defaults
Sometimes a default middleware needs a different setting, or isn't needed at all. For example, you may want CSRF protection everywhere except your webhooks, keep a secret field from being trimmed, or keep empty strings as strings. replace swaps in a middleware configured differently, in the original's place, and remove takes one out. Both look through the global middleware and the web and api groups. If the middleware appears in more than one of them, such as in both the web and api groups, it's replaced or removed in each:
1use laravel::http::middleware::{ConvertEmptyStringsToNull, PreventRequestForgery, TrimStrings};23.with_middleware(|middleware, _| {4 middleware.replace(PreventRequestForgery::new().except(["webhooks/*"]));5 middleware.replace(TrimStrings::except(["secret"]));6 middleware.remove::<ConvertEmptyStringsToNull>();7})1use laravel::http::middleware::{ConvertEmptyStringsToNull, PreventRequestForgery, TrimStrings};23.with_middleware(|middleware, _| {4 middleware.replace(PreventRequestForgery::new().except(["webhooks/*"]));5 middleware.replace(TrimStrings::except(["secret"]));6 middleware.remove::<ConvertEmptyStringsToNull>();7})
Your with_middleware closure runs after every package adds its middleware, so you may use replace and remove on a package's middleware too.
Trusting proxies
When your application runs behind a load balancer that terminates TLS, the load balancer describes the original request in X-Forwarded-* headers: the client's IP address, and whether it used HTTPS. Any client can send those headers, so Laravel ignores them unless the request came through a proxy you trust. Without a trusted proxy, request.ip() is your load balancer's address, and URLs start with http://.
List your load balancer's IP addresses or networks in src/app.rs:
1.with_middleware(|middleware, _| {2 middleware.trust_proxies(["10.0.0.0/8"]);3})1.with_middleware(|middleware, _| {2 middleware.trust_proxies(["10.0.0.0/8"]);3})
If you don't know your load balancer's address, you may trust every proxy with "*". The client's IP address is then the first one in X-Forwarded-For.
On Laravel Cloud, you don't need to configure anything. Unless you list proxies yourself, Laravel trusts every proxy there.
Trust "*" only when your load balancer replaces any X-Forwarded-For header the client sent. Otherwise, the first address is whatever the client claims.
Trusting hosts
Laravel builds absolute URLs, such as password reset links, from the request's host, so a forged Host header could point those links at another site. In production, Laravel answers only requests for the host in your APP_URL and its subdomains, and other hosts get a 400 Bad Request. In the local and testing environments, it doesn't check hosts.
If your application also serves other hosts, list them. The list replaces the default, so include your APP_URL's host too. *.example.com means every subdomain of example.com, but not example.com itself:
1.with_middleware(|middleware, _| {2 middleware.trust_hosts(["example.com", "*.example.com", "example.org"]);3})1.with_middleware(|middleware, _| {2 middleware.trust_hosts(["example.com", "*.example.com", "example.org"]);3})
Security headers
Laravel automatically adds two security headers to every response, including error pages and static files in public/, to protect your users against clickjacking and MIME-type sniffing:
| Header | What it does |
|---|---|
X-Frame-Options: SAMEORIGIN |
Prevents other sites from embedding your pages in an <iframe>, while still allowing framing from your own origin. |
X-Content-Type-Options: nosniff |
Tells browsers to honor the Content-Type header you send instead of guessing a response's type from its content. |
If a response already sets either header, Laravel keeps the value you provided. If your reverse proxy or CDN already manages security headers for you, you may disable SecurityHeaders globally with middleware.remove::<SecurityHeaders>().
Sometimes a specific page needs to be embedded on other sites, such as a public widget. Because SecurityHeaders is global middleware, an individual route can't skip it with without_middleware. Instead, move SecurityHeaders from the global stack into the web group (and api if you'd like API responses to keep the headers) in src/app.rs:
1// src/app.rs2use laravel::http::middleware::SecurityHeaders;34.with_middleware(|middleware, _| {5 middleware6 .remove::<SecurityHeaders>()7 .web(|web| {8 web.prepend(SecurityHeaders);9 })10 .api(|api| {11 api.prepend(SecurityHeaders);12 });13})1// src/app.rs2use laravel::http::middleware::SecurityHeaders;34.with_middleware(|middleware, _| {5 middleware6 .remove::<SecurityHeaders>()7 .web(|web| {8 web.prepend(SecurityHeaders);9 })10 .api(|api| {11 api.prepend(SecurityHeaders);12 });13})
Then exclude SecurityHeaders from the embeddable route in src/routes/web.rs:
1// src/routes/web.rs2route.get("/widget", widget::show).without_middleware::<SecurityHeaders>();1// src/routes/web.rs2route.get("/widget", widget::show).without_middleware::<SecurityHeaders>();
Keep in mind that moving SecurityHeaders out of global middleware means static files from public/ and 404 responses for unmatched routes will no longer include these headers.
Limits
Every route limits how large a request's body may be, and how long handling the request may take. The defaults suit most routes, but some may need more room, such as a video upload or a large export. Each limit is a middleware, so you may set it globally, on a group, or on a single route. When you set the same limit in more than one place, Laravel uses the setting closest to the route.
Body size
A body read into memory, such as JSON or a form, may be up to 2 MB. A multipart form, whose files stream to disk, may be up to 16 MB. A larger body gets a 413 Content Too Large response before the route's middleware and handler run, even when nothing reads it. A form may also have at most 1,000 fields and upload at most 20 files, which you may raise with the SERVER_MAX_INPUT_VARS and SERVER_MAX_FILE_UPLOADS environment variables.
LimitBody sets the limit for bodies read into memory, and LimitUploads sets the limit for multipart forms:
1use laravel::http::middleware::{LimitBody, LimitUploads};23route.post("/videos", videos::store).middleware(LimitUploads::megabytes(500));4route.post("/imports", imports::store).middleware(LimitBody::megabytes(10));1use laravel::http::middleware::{LimitBody, LimitUploads};23route.post("/videos", videos::store).middleware(LimitUploads::megabytes(500));4route.post("/imports", imports::store).middleware(LimitBody::megabytes(10));
Both have bytes(..) for an exact size, and none() to remove the limit, such as for a route that streams its body itself. To change the limits for every route, append them to the global middleware in src/app.rs:
1.with_middleware(|middleware, _| {2 middleware3 .append(LimitBody::megabytes(8))4 .append(LimitUploads::megabytes(64));5})1.with_middleware(|middleware, _| {2 middleware3 .append(LimitBody::megabytes(8))4 .append(LimitUploads::megabytes(64));5})
Timeouts
Handling a request may take up to 30 seconds. A slower request gets a 503 Service Unavailable response. To give a route more time, set a Timeout:
1use laravel::http::middleware::Timeout;23route.get("/reports/export", reports::export).middleware(Timeout::after(2.minutes()));1use laravel::http::middleware::Timeout;23route.get("/reports/export", reports::export).middleware(Timeout::after(2.minutes()));
Timeout::none() removes the limit, such as for a long poll. The timeout stops once your handler returns, so a streamed response may keep streaming past it.
Rate limiting
Some routes are easy to abuse, such as a contact form that sends you an email or an API endpoint that does expensive work. To protect them, you may limit how many requests each client can make by adding a Throttle middleware to the route. Once a client goes over the limit, Laravel responds with a 429 Too Many Requests until enough time has passed. For example, this route accepts up to 60 messages a minute from each client:
1use laravel::http::middleware::Throttle;23route.post("/messages", messages::store).middleware(Throttle::per_minute(60));1use laravel::http::middleware::Throttle;23route.post("/messages", messages::store).middleware(Throttle::per_minute(60));
To learn more, including how to limit each user separately and how to choose a limit for each request, check out the rate limiting documentation.
Cache headers
Some pages look the same to every visitor, such as a pricing page. To let browsers and CDNs cache a route's responses, add CacheHeaders to the route or a group. Its methods are the Cache-Control directives: public, private, no_cache, no_store, must_revalidate, immutable, max_age, and s_maxage. With etag, a browser that already has a response's contents gets a 304 Not Modified without the body:
1use laravel::http::middleware::CacheHeaders;23route4 .get("/pricing", pages::pricing)5 .middleware(CacheHeaders::new().public().max_age(5.minutes()).etag());1use laravel::http::middleware::CacheHeaders;23route4 .get("/pricing", pages::pricing)5 .middleware(CacheHeaders::new().public().max_age(5.minutes()).etag());
CacheHeaders changes only successful responses to GET and HEAD requests, so error pages are never cached.
The web group sets cookies, such as the session cookie, on its responses, and shared caches shouldn't keep a response that sets cookies. Use public only on routes outside the web group, such as your API's.
Tower layers
Laravel is built on Axum, so any Tower layer may be a middleware. Add the layer's crate to your Cargo.toml, such as tower-http with its compression-gzip feature, and wrap the layer with layer:
1use laravel::http::layer;2use tower_http::compression::CompressionLayer;34.with_middleware(|middleware, _| {5 middleware.append(layer(CompressionLayer::new()));6})1use laravel::http::layer;2use tower_http::compression::CompressionLayer;34.with_middleware(|middleware, _| {5 middleware.append(layer(CompressionLayer::new()));6})
To remove a layer you added this way, name the layer's type, as in middleware.remove::<CompressionLayer>().