Middleware
- Introduction
- Defining middleware
- Registering middleware
- Middleware with settings
- Laravel's default middleware
- Rate limiting
- Cache headers
- Standard middleware
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 signed 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, one middleware might check that the user has a paid subscription, 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 the package of the feature they belong to, such as a billing package for the middleware that checks subscriptions.
Laravel also limits how large each request's body may be and how long each request may take. You set these limits on your routes rather than with middleware. To learn more, check out the routing guide's sections on request limits and timeouts.
Defining middleware
A middleware is a type with a Handle method. Handle receives the request and next, a function that passes the request on to the rest of your application, and it returns the response. Because each middleware lives in its feature's package, a route that uses it reads well, as in billing.Subscribed{}. For example, this middleware sends users without a subscription to the pricing page:
1package billing23import (4 "go.laravel.com/web"56 "app/models"7 "app/store"8)910// Subscribed sends users without an active subscription to the pricing page.11type Subscribed struct{}1213func (Subscribed) Handle(r *web.Request, next web.Next) *web.Response {14 user := r.User[models.User]()1516 subscribed, err := store.HasSubscription(r, user.ID)17 if err != nil {18 return web.Fail(err)19 }20 if !subscribed {21 return web.Redirect("/pricing")22 }2324 return next(r)25}1package billing23import (4 "go.laravel.com/web"56 "app/models"7 "app/store"8)910// Subscribed sends users without an active subscription to the pricing page.11type Subscribed struct{}1213func (Subscribed) Handle(r *web.Request, next web.Next) *web.Response {14 user := r.User[models.User]()1516 subscribed, err := store.HasSubscription(r, user.ID)17 if err != nil {18 return web.Fail(err)19 }20 if !subscribed {21 return web.Redirect("/pricing")22 }2324 return next(r)25}
If the user has no subscription, the middleware answers with a redirect and never calls next, so the handler doesn't run. If the lookup fails, web.Fail(err) turns the error into an error response, as it does in a handler. Otherwise, next(r) passes the request deeper into your application, and the middleware returns the response that comes back.
A middleware reads what it needs from r, as a handler does: headers and input, a route parameter with r.PathValue, the signed-in user with r.User, and your application's services with services.From(r). Keep in mind that Subscribed reads the signed-in user, so it must run on routes behind auth.Authenticate. To hand a value to the handler, such as the account that a subdomain names, put the value in the request's context. To learn how, check out the context guide's section on adding values of your own.
This example only reads the user. Reading body input, such as with r.Bind, reads the request's body, and a global middleware runs before Laravel has read the route's request limits. To learn how to read and transform input safely, check out the requests guide's section on input in middleware.
Some middleware are short enough that a type of their own would be clutter. You may write such a middleware as a function and convert it with web.MiddlewareFunc. For example, this middleware asks search engines not to index a preview page:
1func noIndex(r *web.Request, next web.Next) *web.Response {2 return next(r).WithHeader("X-Robots-Tag", "noindex")3}45route.Get("/preview", preview.Show).Middleware(web.MiddlewareFunc(noIndex))1func noIndex(r *web.Request, next web.Next) *web.Response {2 return next(r).WithHeader("X-Robots-Tag", "noindex")3}45route.Get("/preview", preview.Show).Middleware(web.MiddlewareFunc(noIndex))
Middleware and responses
Some middleware do their work after the handler, such as adding a header to every response. Code before next 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:
1package metrics23import (4 "fmt"5 "time"67 "go.laravel.com/web"8)910// Timing reports how long the application took in the Server-Timing header.11type Timing struct{}1213func (Timing) Handle(r *web.Request, next web.Next) *web.Response {14 start := time.Now()1516 res := next(r)17 res.Header.Set("Server-Timing", fmt.Sprintf("app;dur=%d", time.Since(start).Milliseconds()))1819 return res20}1package metrics23import (4 "fmt"5 "time"67 "go.laravel.com/web"8)910// Timing reports how long the application took in the Server-Timing header.11type Timing struct{}1213func (Timing) Handle(r *web.Request, next web.Next) *web.Response {14 start := time.Now()1516 res := next(r)17 res.Header.Set("Server-Timing", fmt.Sprintf("app;dur=%d", time.Since(start).Milliseconds()))1819 return res20}
next always returns a response, even when the handler fails. By then, Laravel has already turned the handler's error into an error page, so your middleware sees a status such as 404 or 500 in res.Status, and the headers it adds reach error pages too.
To do something after the response has been sent, such as removing a temporary file, register a function with r.OnFinish. To learn more, check out the context guide's section on running work after the response.
Registering middleware
Global middleware
To run a middleware on every HTTP request to your application, such as the metrics.Timing middleware above, append it to the global middleware. Use the Middleware option in bootstrap/app.go, whose function receives Laravel's default middleware:
1package bootstrap23import (4 laravel "go.laravel.com"5 "go.laravel.com/config"67 "app/metrics"8)910func Options() laravel.Options {11 return laravel.Options{12 // ...1314 Middleware: func(m *laravel.Middleware, cfg *config.Config) {15 m.Global.Append(metrics.Timing{})16 },17 }18}1package bootstrap23import (4 laravel "go.laravel.com"5 "go.laravel.com/config"67 "app/metrics"8)910func Options() laravel.Options {11 return laravel.Options{12 // ...1314 Middleware: func(m *laravel.Middleware, cfg *config.Config) {15 m.Global.Append(metrics.Timing{})16 },17 }18}
Append adds the middleware to the end of the global middleware, closest to the handler, and Prepend adds it to the beginning. The function'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:
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 if cfg.App.Debug {3 m.Global.Append(metrics.Timing{})4 }5},1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 if cfg.App.Debug {3 m.Global.Append(metrics.Timing{})4 }5},
Assigning middleware to routes
Most middleware belong on some routes rather than all of them. To assign a middleware to a single route, chain Middleware onto the route's definition in your route file:
1import (2 "go.laravel.com/auth"3 "go.laravel.com/config"4 "go.laravel.com/routing"56 "app/handlers/profile"7)89func Web(route *routing.Router, cfg *config.Config) {10 route.Get("/profile", profile.Show).Middleware(auth.Authenticate{})11}1import (2 "go.laravel.com/auth"3 "go.laravel.com/config"4 "go.laravel.com/routing"56 "app/handlers/profile"7)89func Web(route *routing.Router, cfg *config.Config) {10 route.Get("/profile", profile.Show).Middleware(auth.Authenticate{})11}
To assign a middleware to several routes, call Middleware on the router. It returns a route group whose routes all run the middleware:
1account := route.Middleware(auth.Authenticate{})23account.Get("/profile", profile.Show)4account.Get("/invoices", invoices.Index)1account := route.Middleware(auth.Authenticate{})23account.Get("/profile", profile.Show)4account.Get("/invoices", invoices.Index)
To assign several middleware at once, pass them all to Middleware. Laravel runs them in the order you list them, so in this example, auth.Authenticate makes sure the user is signed in before auth.RequireVerifiedEmail checks their email address:
1route.Get("/billing", subscriptions.Edit).Middleware(auth.Authenticate{}, auth.RequireVerifiedEmail{})1route.Get("/billing", subscriptions.Edit).Middleware(auth.Authenticate{}, auth.RequireVerifiedEmail{})
Middleware groups
When several routes share the same set of middleware, such as reports that need a signed-in, verified subscriber, you may bundle the middleware in a function of your own. A group like this needs no registration. Return the list from the function, and pass it to Middleware:
1func subscribers() []web.Middleware {2 return []web.Middleware{auth.Authenticate{}, auth.RequireVerifiedEmail{}, billing.Subscribed{}}3}45route.Prefix("/reports").Middleware(subscribers()...).Group(func(route *routing.Router) {6 // ...7})1func subscribers() []web.Middleware {2 return []web.Middleware{auth.Authenticate{}, auth.RequireVerifiedEmail{}, billing.Subscribed{}}3}45route.Prefix("/reports").Middleware(subscribers()...).Group(func(route *routing.Router) {6 // ...7})
Laravel also has two middleware groups of its own, one for each route file. Routes in routes/web.go run within the web group, and routes in routes/api.go run within the api group. To add a middleware to either group, append it in the Middleware option of bootstrap/app.go. Here, every web page gets the timing header, and every API request must carry an API key, which an apikeys.Required middleware of your own checks:
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Web.Append(metrics.Timing{})3 m.API.Append(apikeys.Required{})4},1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Web.Append(metrics.Timing{})3 m.API.Append(apikeys.Required{})4},
Excluding middleware
Sometimes a route shouldn't run one of its group's middleware. For example, a user whose subscription has lapsed still needs to reach the billing page to renew it. Chain Without onto that route:
1account := route.Middleware(auth.Authenticate{}, billing.Subscribed{})23account.Get("/invoices", invoices.Index)4account.Get("/billing", subscriptions.Edit).Without(billing.Subscribed{})1account := route.Middleware(auth.Authenticate{}, billing.Subscribed{})23account.Get("/invoices", invoices.Index)4account.Get("/billing", subscriptions.Edit).Without(billing.Subscribed{})
Without also removes middleware from the web and api groups. For example, Stripe can't send a CSRF token with its webhook requests, so your webhook routes need to skip the web group's CSRF protection. If several routes need the same exception, such as all of your webhooks, call Without on the router instead. Every route you register on the router it returns skips the middleware:
1import "go.laravel.com/middleware"23hooks := route.Prefix("/webhooks").Without(middleware.ValidateCSRFToken{})45hooks.Post("/stripe", webhooks.Stripe)6hooks.Post("/github", webhooks.GitHub)1import "go.laravel.com/middleware"23hooks := route.Prefix("/webhooks").Without(middleware.ValidateCSRFToken{})45hooks.Post("/stripe", webhooks.Stripe)6hooks.Post("/github", webhooks.GitHub)
Without matches middleware by type, so Without(billing.Plan{}) excludes a billing.Plan whatever its Name is. To exclude a middleware you wrote as a function, convert the same function again, as in Without(web.MiddlewareFunc(noIndex)).
Without can't exclude a global middleware, because global middleware run before Laravel matches a route. 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 inroutes/web.goorroutes/api.go. Bare routes skip this step. - 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(auth.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 read the current route, the session, or the signed-in user. A middleware that needs any of these belongs on your routes, or in the web group. Middleware on your routes always run after StartSession and auth.Session. If you append a middleware to the web group, append it after the line in bootstrap/app.go that adds auth.Session.
To check the order on your routes, list them with their middleware. Each route's middleware appear under its handler, in the order they run, without the global middleware:
1laravel route:list --middleware1laravel route:list --middleware
Middleware with settings
Some middleware need a value from the route that uses them, such as the plan a user must have to see a page. Hold these settings in the middleware's fields. For example, this middleware answers with a 403 unless the signed-in user's plan is the one in its Name field:
1package billing23import (4 "net/http"56 "go.laravel.com/web"78 "app/models"9 "app/store"10)1112// Plan forbids users whose plan isn't Name.13type Plan struct {14 Name string15}1617func (m Plan) Handle(r *web.Request, next web.Next) *web.Response {18 user := r.User[models.User]()1920 plan, err := store.PlanOf(r, user.ID)21 if err != nil {22 return web.Fail(err)23 }24 if plan != m.Name {25 return web.Abort(http.StatusForbidden)26 }2728 return next(r)29}1package billing23import (4 "net/http"56 "go.laravel.com/web"78 "app/models"9 "app/store"10)1112// Plan forbids users whose plan isn't Name.13type Plan struct {14 Name string15}1617func (m Plan) Handle(r *web.Request, next web.Next) *web.Response {18 user := r.User[models.User]()1920 plan, err := store.PlanOf(r, user.ID)21 if err != nil {22 return web.Fail(err)23 }24 if plan != m.Name {25 return web.Abort(http.StatusForbidden)26 }2728 return next(r)29}
To use Plan on a route, set its Name to the plan the route requires, such as billing.Plan{Name: "team"}. Plan reads the signed-in user, so list it after auth.Authenticate. In this example, users on the team plan may see the team's members, but only users on the enterprise plan may see its audit log:
1import "go.laravel.com/auth"23team := route.Middleware(auth.Authenticate{})45team.Get("/team/members", members.Index).Middleware(billing.Plan{Name: "team"})6team.Get("/team/audit-log", auditlog.Index).Middleware(billing.Plan{Name: "enterprise"})1import "go.laravel.com/auth"23team := route.Middleware(auth.Authenticate{})45team.Get("/team/members", members.Index).Middleware(billing.Plan{Name: "team"})6team.Get("/team/audit-log", auditlog.Index).Middleware(billing.Plan{Name: "enterprise"})
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, and each is a type in the middleware package:
| 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. |
ConvertEmptyStrings |
Global | Turns empty string input into nil, so a blank field reads as missing. |
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. |
ValidateCSRFToken |
web |
Rejects cross-site requests that change state, as CSRF protection explains. |
The api group is empty. New applications also append two middleware to the web group in bootstrap/app.go. auth.Session finds the signed-in user, and inertia.Middleware renders your Inertia pages.
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 user's bio from being trimmed, or keep empty strings as strings. m.Replace swaps in a middleware with other settings, in the original's place, and m.Remove takes one out. Both look through the global middleware and the web and api groups, so you don't need to name the group. If the middleware appears in more than one of them, it's replaced or removed in each:
1import (2 laravel "go.laravel.com"3 "go.laravel.com/config"4 "go.laravel.com/middleware"5)67Middleware: func(m *laravel.Middleware, cfg *config.Config) {8 m.Replace(middleware.ValidateCSRFToken{Except: []string{"webhooks/*"}})9 m.Replace(middleware.TrimStrings{Except: []string{"profile.bio"}})1011 m.Remove(middleware.ConvertEmptyStrings{})12},1import (2 laravel "go.laravel.com"3 "go.laravel.com/config"4 "go.laravel.com/middleware"5)67Middleware: func(m *laravel.Middleware, cfg *config.Config) {8 m.Replace(middleware.ValidateCSRFToken{Except: []string{"webhooks/*"}})9 m.Replace(middleware.TrimStrings{Except: []string{"profile.bio"}})1011 m.Remove(middleware.ConvertEmptyStrings{})12},
TrimStrings and ConvertEmptyStrings take the fields to leave alone in Except. Name a nested field with dots, so profile.bio is the bio field inside profile.
Your Middleware function runs after every package adds its middleware, so you may use m.Replace and m.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 visitor's IP address, and whether they 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, r.IP() returns your load balancer's address, and the URLs your application generates start with http://.
List your load balancer's IP addresses or networks in the Middleware option of bootstrap/app.go:
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Proxies = []string{"10.0.0.0/8"}3},1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Proxies = []string{"10.0.0.0/8"}3},
If you don't know your load balancer's address, such as behind a cloud load balancer whose address changes, you may trust every proxy with "*". The visitor'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 visitor sent. Otherwise, the first address is whatever the visitor claims, and the visitor may choose the address that rate limits count.
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, Laravel doesn't check hosts, so you may develop on any address.
If your application also serves other hosts, replace TrustHosts with one that lists 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:
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Replace(middleware.TrustHosts{3 Hosts: []string{"example.com", "*.example.com", "example.org"},4 })5},1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Replace(middleware.TrustHosts{3 Hosts: []string{"example.com", "*.example.com", "example.org"},4 })5},
Security headers
Laravel adds two security headers to every response, including error pages and the files in your public directory, to protect your visitors against clickjacking and content sniffing:
| Header | What it does |
|---|---|
X-Frame-Options: SAMEORIGIN |
Stops other sites from showing your pages in an <iframe>, while your own pages still may. |
X-Content-Type-Options: nosniff |
Tells browsers to use the Content-Type you send instead of guessing a response's type from its content. |
If a response already sets either header, Laravel keeps your value. If your load balancer or CDN already adds these headers, you may remove the middleware with m.Remove(middleware.SecurityHeaders{}).
Sometimes one page needs to appear on other sites, such as a widget that your customers embed. SecurityHeaders is global middleware, so a route can't skip it with Without. Instead, move SecurityHeaders into the web group in bootstrap/app.go, and into the api group too if you'd like your API's responses to keep the headers:
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Remove(middleware.SecurityHeaders{})34 m.Web.Prepend(middleware.SecurityHeaders{})5 m.API.Prepend(middleware.SecurityHeaders{})6},1Middleware: func(m *laravel.Middleware, cfg *config.Config) {2 m.Remove(middleware.SecurityHeaders{})34 m.Web.Prepend(middleware.SecurityHeaders{})5 m.API.Prepend(middleware.SecurityHeaders{})6},
Then exclude SecurityHeaders from the widget's route in routes/web.go:
1route.Get("/widget", widget.Show).Without(middleware.SecurityHeaders{})1route.Get("/widget", widget.Show).Without(middleware.SecurityHeaders{})
Keep in mind that once SecurityHeaders runs in the web and api groups, the files in public and the 404 pages for paths that match no route no longer carry these headers.
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:
1import "go.laravel.com/middleware"23route.Post("/messages", messages.Store).Middleware(middleware.ThrottlePerMinute(60))1import "go.laravel.com/middleware"23route.Post("/messages", messages.Store).Middleware(middleware.ThrottlePerMinute(60))
To learn more, including how to limit each user separately and how to set several limits on one route, check out the rate limiting documentation.
Cache headers
Some responses look the same to every visitor, such as the list of plans your pricing page shows. To let browsers and CDNs cache a route's responses, add CacheHeaders to the route or a group. CacheHeaders sets the Cache-Control header on successful responses to GET and HEAD requests, so error pages are never cached. For example, this route in routes/api.go lets any cache keep the plans for an hour:
1import (2 "time"34 "go.laravel.com/middleware"5)67route.Get("/plans", plans.Index).Middleware(middleware.CacheHeaders{8 Public: true,9 MaxAge: time.Hour,10 ETag: true,11})1import (2 "time"34 "go.laravel.com/middleware"5)67route.Get("/plans", plans.Index).Middleware(middleware.CacheHeaders{8 Public: true,9 MaxAge: time.Hour,10 ETag: true,11})
Public lets shared caches such as a CDN store the response, and Private lets only the visitor's browser store it. MaxAge is how long the response stays fresh. The other fields, such as NoStore and SharedMaxAge, set the rest of the Cache-Control directives.
With ETag, a browser that already has the current version of a response gets an empty 304 Not Modified instead of the body. Your handler still runs, so an ETag saves bandwidth, but not the work of building the response.
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, and never on a response that shows anything about the signed-in user.
Standard middleware
Much of Go's middleware is written for net/http, as a function that takes an http.Handler and returns another one. To use one of these functions as a Laravel middleware, wrap it with web.WrapMiddleware. You may then use the wrapped middleware anywhere this page uses a middleware. For example, this uses the unrolled/secure package to add Referrer-Policy and Permissions-Policy headers to every response:
1import (2 "github.com/unrolled/secure"34 laravel "go.laravel.com"5 "go.laravel.com/config"6 "go.laravel.com/web"7)89Middleware: func(m *laravel.Middleware, cfg *config.Config) {10 headers := secure.New(secure.Options{11 ReferrerPolicy: "strict-origin-when-cross-origin",12 PermissionsPolicy: "camera=(), microphone=(), geolocation=()",13 })1415 m.Global.Append(web.WrapMiddleware(headers.Handler))16},1import (2 "github.com/unrolled/secure"34 laravel "go.laravel.com"5 "go.laravel.com/config"6 "go.laravel.com/web"7)89Middleware: func(m *laravel.Middleware, cfg *config.Config) {10 headers := secure.New(secure.Options{11 ReferrerPolicy: "strict-origin-when-cross-origin",12 PermissionsPolicy: "camera=(), microphone=(), geolocation=()",13 })1415 m.Global.Append(web.WrapMiddleware(headers.Handler))16},
Laravel tells wrapped middleware apart by the function you wrapped. To exclude or remove a wrapped middleware, wrap the same function again, as in Without(web.WrapMiddleware(headers.Handler)).
A wrapped middleware can change the body of a response that your handler builds in memory, and it can change the headers of a file or streamed response.
If you'd like to serve a standard http.Handler from a route instead, check out the handlers guide's section on standard handlers.