跳至正文

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:

go
package billing

import (
	"go.laravel.com/web"

	"app/models"
	"app/store"
)

// Subscribed sends users without an active subscription to the pricing page.
type Subscribed struct{}

func (Subscribed) Handle(r *web.Request, next web.Next) *web.Response {
	user := r.User[models.User]()

	subscribed, err := store.HasSubscription(r, user.ID)
	if err != nil {
		return web.Fail(err)
	}
	if !subscribed {
		return web.Redirect("/pricing")
	}

	return next(r)
}

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:

go
func noIndex(r *web.Request, next web.Next) *web.Response {
	return next(r).WithHeader("X-Robots-Tag", "noindex")
}

route.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:

go
package metrics

import (
	"fmt"
	"time"

	"go.laravel.com/web"
)

// Timing reports how long the application took in the Server-Timing header.
type Timing struct{}

func (Timing) Handle(r *web.Request, next web.Next) *web.Response {
	start := time.Now()

	res := next(r)
	res.Header.Set("Server-Timing", fmt.Sprintf("app;dur=%d", time.Since(start).Milliseconds()))

	return res
}

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:

go
package bootstrap

import (
	laravel "go.laravel.com"
	"go.laravel.com/config"

	"app/metrics"
)

func Options() laravel.Options {
	return laravel.Options{
		// ...

		Middleware: func(m *laravel.Middleware, cfg *config.Config) {
			m.Global.Append(metrics.Timing{})
		},
	}
}

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:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	if cfg.App.Debug {
		m.Global.Append(metrics.Timing{})
	}
},

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:

go
import (
	"go.laravel.com/auth"
	"go.laravel.com/config"
	"go.laravel.com/routing"

	"app/handlers/profile"
)

func Web(route *routing.Router, cfg *config.Config) {
	route.Get("/profile", profile.Show).Middleware(auth.Authenticate{})
}

To assign a middleware to several routes, call Middleware on the router. It returns a route group whose routes all run the middleware:

go
account := route.Middleware(auth.Authenticate{})

account.Get("/profile", profile.Show)
account.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:

go
route.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:

go
func subscribers() []web.Middleware {
	return []web.Middleware{auth.Authenticate{}, auth.RequireVerifiedEmail{}, billing.Subscribed{}}
}

route.Prefix("/reports").Middleware(subscribers()...).Group(func(route *routing.Router) {
	// ...
})

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:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Web.Append(metrics.Timing{})
	m.API.Append(apikeys.Required{})
},

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:

go
account := route.Middleware(auth.Authenticate{}, billing.Subscribed{})

account.Get("/invoices", invoices.Index)
account.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:

go
import "go.laravel.com/middleware"

hooks := route.Prefix("/webhooks").Without(middleware.ValidateCSRFToken{})

hooks.Post("/stripe", webhooks.Stripe)
hooks.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:

  1. The global middleware, which run on every request.
  2. The web or api middleware group, depending on whether the route is defined in routes/web.go or routes/api.go. Bare routes skip this step.
  3. 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.
  4. 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:

shell
laravel 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:

go
package billing

import (
	"net/http"

	"go.laravel.com/web"

	"app/models"
	"app/store"
)

// Plan forbids users whose plan isn't Name.
type Plan struct {
	Name string
}

func (m Plan) Handle(r *web.Request, next web.Next) *web.Response {
	user := r.User[models.User]()

	plan, err := store.PlanOf(r, user.ID)
	if err != nil {
		return web.Fail(err)
	}
	if plan != m.Name {
		return web.Abort(http.StatusForbidden)
	}

	return next(r)
}

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:

go
import "go.laravel.com/auth"

team := route.Middleware(auth.Authenticate{})

team.Get("/team/members", members.Index).Middleware(billing.Plan{Name: "team"})
team.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:

MiddlewareWhereWhat it does
Trusted proxiesBefore all othersRemoves X-Forwarded-* headers unless the request came through a trusted proxy.
SecurityHeadersGlobalAdds security headers to every response.
TrustHostsGlobalRejects requests for hosts your application doesn't serve.
HandleCORSGlobalAnswers cross-origin requests to your API.
SpoofMethodsGlobalLets HTML forms send PUT, PATCH, and DELETE requests.
TrimStringsGlobalTrims whitespace from string input, except passwords.
ConvertEmptyStringsGlobalTurns empty string input into nil, so a blank field reads as missing.
EncryptCookieswebEncrypts the cookies you set, and decrypts them when they come back.
StartSessionwebLoads the session before the request and saves it after.
ValidateCSRFTokenwebRejects 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:

go
import (
	laravel "go.laravel.com"
	"go.laravel.com/config"
	"go.laravel.com/middleware"
)

Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Replace(middleware.ValidateCSRFToken{Except: []string{"webhooks/*"}})
	m.Replace(middleware.TrimStrings{Except: []string{"profile.bio"}})

	m.Remove(middleware.ConvertEmptyStrings{})
},

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:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Proxies = []string{"10.0.0.0/8"}
},

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:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Replace(middleware.TrustHosts{
		Hosts: []string{"example.com", "*.example.com", "example.org"},
	})
},

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:

HeaderWhat it does
X-Frame-Options: SAMEORIGINStops other sites from showing your pages in an <iframe>, while your own pages still may.
X-Content-Type-Options: nosniffTells 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:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Remove(middleware.SecurityHeaders{})

	m.Web.Prepend(middleware.SecurityHeaders{})
	m.API.Prepend(middleware.SecurityHeaders{})
},

Then exclude SecurityHeaders from the widget's route in routes/web.go:

go
route.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:

go
import "go.laravel.com/middleware"

route.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:

go
import (
	"time"

	"go.laravel.com/middleware"
)

route.Get("/plans", plans.Index).Middleware(middleware.CacheHeaders{
	Public: true,
	MaxAge: time.Hour,
	ETag:   true,
})

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:

go
import (
	"github.com/unrolled/secure"

	laravel "go.laravel.com"
	"go.laravel.com/config"
	"go.laravel.com/web"
)

Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	headers := secure.New(secure.Options{
		ReferrerPolicy:    "strict-origin-when-cross-origin",
		PermissionsPolicy: "camera=(), microphone=(), geolocation=()",
	})

	m.Global.Append(web.WrapMiddleware(headers.Handler))
},

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.