跳至正文

Cookies ​

Introduction ​

Cookies let your application store small pieces of data in a visitor's browser and read them back on later requests, such as their preferred color theme or whether they dismissed a product tour. You read incoming cookies from the request and attach outgoing cookies to the response your handler returns. Each cookie is a standard *http.Cookie, and the cookie package builds one with the attributes most cookies need.

Routes in the web middleware group automatically encrypt and sign cookies so visitors can't read or tamper with them. Routes outside the web group, such as those in routes/api.go, send cookies unencrypted. For data that should stay on your server, use the session instead.

Reading cookies ​

To retrieve a cookie from an incoming request, call Cookie on the request. It returns the *http.Cookie, or http.ErrNoCookie if the browser didn't send that cookie:

go
package settings

import "go.laravel.com/web"

func Show(r *web.Request) *web.Response {
	theme := "light"
	if c, err := r.Cookie("theme"); err == nil {
		theme = c.Value
	}

	return web.Text("Your theme is " + theme)
}

On routes in the web middleware group, c.Value automatically holds the decrypted value. If the client modified a cookie's value and it fails decryption, r.Cookie returns http.ErrNoCookie. To retrieve every cookie the request sent, call r.Cookies.

Sending cookies ​

To attach a cookie to an outgoing response, call WithCookie. Pass cookie.New the cookie's name, value, and lifetime as a time.Duration, such as 30*24*time.Hour:

go
package settings

import (
	"time"

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

func Update(r *web.Request) *web.Response {
	return web.Text("Saved").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))
}

Every response supports WithCookie, including redirects, views, and JSON. For example, a handler that redirects after updating settings may attach the cookie directly to the redirect:

go
func Update(r *web.Request) *web.Response {
	return web.Redirect("/settings").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))
}

Attaching a cookie replaces any cookie already on the response with the same name, path, and domain. Middleware may also attach cookies to the response that next returns.

To keep a cookie only until the visitor closes their browser, build it with cookie.Session, or pass 0 as the lifetime to cookie.New. To keep a cookie for as long as browsers allow, use cookie.Forever. Each cookie function returns a standard *http.Cookie, so you may customize any other attribute by setting its fields:

go
package settings

import (
	"net/http"
	"time"

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

func Update(r *web.Request) *web.Response {
	embed := cookie.Session("embed", "1")
	embed.SameSite = http.SameSiteNoneMode
	embed.Secure = true

	return web.Text("Saved").
		WithCookie(cookie.New("theme", "dark", 30*24*time.Hour)).
		WithCookie(cookie.Forever("cookie_consent", "accepted")).
		WithCookie(embed)
}
Function or fieldAttributeEffect
cookie.New(name, value, lifetime)Max-AgeKeeps the cookie for this long. Pass 0 for a session cookie.
cookie.Session(name, value)Keeps the cookie until the visitor closes their browser.
cookie.Forever(name, value)Max-AgeKeeps the cookie for 400 days, the longest that browsers allow.
ExpiresExpiresKeeps the cookie until a time, such as date.EndOfDay(date.Now(r)).
Path, DomainPath, DomainWhere the browser sends the cookie.
SecureSecureSends the cookie only over HTTPS.
HttpOnlyHttpOnlyHides the cookie from JavaScript. Set it to false to let scripts read it.
SameSiteSameSiteWhether the browser sends the cookie with requests from other sites: http.SameSiteLaxMode, http.SameSiteStrictMode, or http.SameSiteNoneMode.

Unless you set them yourself, cookies inherit the Path, Domain, Secure, and SameSite defaults from your session configuration, and the cookie functions enable HttpOnly. Those defaults are safe for most cookies, so you'll usually only need to choose a lifetime.

Deleting cookies ​

To remove a cookie from the browser, call WithoutCookie on the response. Laravel sends an expired cookie in its place so the browser deletes it:

go
func Dismiss(r *web.Request) *web.Response {
	return web.Text("Dismissed").WithoutCookie("tour")
}

If the cookie was originally set with a custom path or domain, the browser only deletes it when the removal cookie specifies the same path and domain. In that case, build the removal cookie with cookie.Forget, set those fields, and attach it with WithCookie:

go
tour := cookie.Forget("tour")
tour.Path = "/admin"

return web.Text("Dismissed").WithCookie(tour)

Cookies and encryption ​

The EncryptCookies middleware runs first in the web middleware group and encrypts every outgoing cookie using your application's encryption key. When the browser sends those cookies back on later requests, EncryptCookies decrypts them before your handler runs. If a cookie fails decryption because a visitor tampered with it, EncryptCookies discards it, and r.Cookie returns http.ErrNoCookie as if the browser hadn't sent it.

警告

EncryptCookies encrypts only the cookies on responses that pass back through it. A middleware that runs outside the web group, such as a global middleware, sends its cookies unencrypted.

Excluding cookies from encryption ​

Sometimes JavaScript or another application needs to read a cookie, such as a script that applies the visitor's color theme before the page renders. To exclude specific cookies from encryption, replace EncryptCookies in the Middleware option in bootstrap/app.go:

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.EncryptCookies{Except: []string{"theme"}})
},

For JavaScript to read the cookie in the browser, also clear its HttpOnly field when you build it:

go
theme := cookie.Forever("theme", "dark")
theme.HttpOnly = false

return web.Text("Saved").WithCookie(theme)

警告

Only exclude cookies that don't contain sensitive data. Visitors can read and modify an unencrypted cookie, so always treat its value as untrusted input.

Testing ​

In tests, send an incoming cookie with the client's WithCookie, and assert outgoing cookies with AssertCookie and AssertCookieExpired. Both work with plain values, so you don't need to encrypt or decrypt cookies yourself:

go
package feature_test

import (
	"testing"

	"app/tests"
)

func TestTheThemeCanBeChanged(t *testing.T) {
	client := tests.New(t)

	client.WithCookie("theme", "dark").Get("/").AssertSee("Your theme is dark")

	client.Post("/theme", nil).AssertCookie("theme", "dark")

	client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")
}

To learn more about how the test client carries cookies from one response to the next request, check out the testing guide's section on cookies and sessions.