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:
1package settings23import "go.laravel.com/web"45func Show(r *web.Request) *web.Response {6 theme := "light"7 if c, err := r.Cookie("theme"); err == nil {8 theme = c.Value9 }1011 return web.Text("Your theme is " + theme)12}1package settings23import "go.laravel.com/web"45func Show(r *web.Request) *web.Response {6 theme := "light"7 if c, err := r.Cookie("theme"); err == nil {8 theme = c.Value9 }1011 return web.Text("Your theme is " + theme)12}
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:
1package settings23import (4 "time"56 "go.laravel.com/cookie"7 "go.laravel.com/web"8)910func Update(r *web.Request) *web.Response {11 return web.Text("Saved").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))12}1package settings23import (4 "time"56 "go.laravel.com/cookie"7 "go.laravel.com/web"8)910func Update(r *web.Request) *web.Response {11 return web.Text("Saved").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))12}
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:
1func Update(r *web.Request) *web.Response {2 return web.Redirect("/settings").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))3}1func Update(r *web.Request) *web.Response {2 return web.Redirect("/settings").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))3}
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.
Cookie attributes
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:
1package settings23import (4 "net/http"5 "time"67 "go.laravel.com/cookie"8 "go.laravel.com/web"9)1011func Update(r *web.Request) *web.Response {12 embed := cookie.Session("embed", "1")13 embed.SameSite = http.SameSiteNoneMode14 embed.Secure = true1516 return web.Text("Saved").17 WithCookie(cookie.New("theme", "dark", 30*24*time.Hour)).18 WithCookie(cookie.Forever("cookie_consent", "accepted")).19 WithCookie(embed)20}1package settings23import (4 "net/http"5 "time"67 "go.laravel.com/cookie"8 "go.laravel.com/web"9)1011func Update(r *web.Request) *web.Response {12 embed := cookie.Session("embed", "1")13 embed.SameSite = http.SameSiteNoneMode14 embed.Secure = true1516 return web.Text("Saved").17 WithCookie(cookie.New("theme", "dark", 30*24*time.Hour)).18 WithCookie(cookie.Forever("cookie_consent", "accepted")).19 WithCookie(embed)20}
| Function or field | Attribute | Effect |
|---|---|---|
cookie.New(name, |
Max-Age |
Keeps the cookie for this long. Pass 0 for a session cookie. |
cookie.Session(name, |
Keeps the cookie until the visitor closes their browser. | |
cookie.Forever(name, |
Max-Age |
Keeps the cookie for 400 days, the longest that browsers allow. |
Expires |
Expires |
Keeps the cookie until a time, such as date.EndOfDay(date.Now(r)). |
Path, Domain |
Path, Domain |
Where the browser sends the cookie. |
Secure |
Secure |
Sends the cookie only over HTTPS. |
HttpOnly |
HttpOnly |
Hides the cookie from JavaScript. Set it to false to let scripts read it. |
SameSite |
SameSite |
Whether 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:
1func Dismiss(r *web.Request) *web.Response {2 return web.Text("Dismissed").WithoutCookie("tour")3}1func Dismiss(r *web.Request) *web.Response {2 return web.Text("Dismissed").WithoutCookie("tour")3}
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:
1tour := cookie.Forget("tour")2tour.Path = "/admin"34return web.Text("Dismissed").WithCookie(tour)1tour := cookie.Forget("tour")2tour.Path = "/admin"34return 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:
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.EncryptCookies{Except: []string{"theme"}})9},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.EncryptCookies{Except: []string{"theme"}})9},
For JavaScript to read the cookie in the browser, also clear its HttpOnly field when you build it:
1theme := cookie.Forever("theme", "dark")2theme.HttpOnly = false34return web.Text("Saved").WithCookie(theme)1theme := cookie.Forever("theme", "dark")2theme.HttpOnly = false34return 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:
1package feature_test23import (4 "testing"56 "app/tests"7)89func TestTheThemeCanBeChanged(t *testing.T) {10 client := tests.New(t)1112 client.WithCookie("theme", "dark").Get("/").AssertSee("Your theme is dark")1314 client.Post("/theme", nil).AssertCookie("theme", "dark")1516 client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")17}1package feature_test23import (4 "testing"56 "app/tests"7)89func TestTheThemeCanBeChanged(t *testing.T) {10 client := tests.New(t)1112 client.WithCookie("theme", "dark").Get("/").AssertSee("Your theme is dark")1314 client.Post("/theme", nil).AssertCookie("theme", "dark")1516 client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")17}
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.