Skip to content

Cookies

The Basics

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 settings
2 
3import "go.laravel.com/web"
4 
5func Show(r *web.Request) *web.Response {
6 theme := "light"
7 if c, err := r.Cookie("theme"); err == nil {
8 theme = c.Value
9 }
10 
11 return web.Text("Your theme is " + theme)
12}
1package settings
2 
3import "go.laravel.com/web"
4 
5func Show(r *web.Request) *web.Response {
6 theme := "light"
7 if c, err := r.Cookie("theme"); err == nil {
8 theme = c.Value
9 }
10 
11 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 settings
2 
3import (
4 "time"
5 
6 "go.laravel.com/cookie"
7 "go.laravel.com/web"
8)
9 
10func Update(r *web.Request) *web.Response {
11 return web.Text("Saved").WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))
12}
1package settings
2 
3import (
4 "time"
5 
6 "go.laravel.com/cookie"
7 "go.laravel.com/web"
8)
9 
10func 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.

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 settings
2 
3import (
4 "net/http"
5 "time"
6 
7 "go.laravel.com/cookie"
8 "go.laravel.com/web"
9)
10 
11func Update(r *web.Request) *web.Response {
12 embed := cookie.Session("embed", "1")
13 embed.SameSite = http.SameSiteNoneMode
14 embed.Secure = true
15 
16 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 settings
2 
3import (
4 "net/http"
5 "time"
6 
7 "go.laravel.com/cookie"
8 "go.laravel.com/web"
9)
10 
11func Update(r *web.Request) *web.Response {
12 embed := cookie.Session("embed", "1")
13 embed.SameSite = http.SameSiteNoneMode
14 embed.Secure = true
15 
16 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, value, lifetime) Max-Age Keeps 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-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"
3 
4return web.Text("Dismissed").WithCookie(tour)
1tour := cookie.Forget("tour")
2tour.Path = "/admin"
3 
4return 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)
6 
7Middleware: 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)
6 
7Middleware: 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 = false
3 
4return web.Text("Saved").WithCookie(theme)
1theme := cookie.Forever("theme", "dark")
2theme.HttpOnly = false
3 
4return 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_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestTheThemeCanBeChanged(t *testing.T) {
10 client := tests.New(t)
11 
12 client.WithCookie("theme", "dark").Get("/").AssertSee("Your theme is dark")
13 
14 client.Post("/theme", nil).AssertCookie("theme", "dark")
15 
16 client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")
17}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestTheThemeCanBeChanged(t *testing.T) {
10 client := tests.New(t)
11 
12 client.WithCookie("theme", "dark").Get("/").AssertSee("Your theme is dark")
13 
14 client.Post("/theme", nil).AssertCookie("theme", "dark")
15 
16 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.