Cookies

suggest change

A cookie is a small name/value pair that a server asks the browser to store and send back on later requests. The server sends a Set-Cookie response header, and the browser replies with a Cookie request header. HTTP itself is stateless, so cookies are how websites remember sessions, preferences and shopping carts.

Everything you need is in net/http:

The http.Cookie struct

The most commonly used fields:

Field Meaning
Name, Value the cookie itself
Path URL path prefix the cookie is sent for. Defaults to the directory of the request URL, so you almost always want "/"
Domain host the cookie is sent to. Empty means only the exact host that set it. example.com also covers subdomains
Expires absolute expiration time
MaxAge lifetime in seconds. 0 means "not set", a negative value means "delete now"
Secure only send over HTTPS
HttpOnly not readable from JavaScript (document.cookie)
SameSite http.SameSiteLaxMode, http.SameSiteStrictMode or http.SameSiteNoneMode
Partitioned third-party cookie partitioned per top-level site (CHIPS)

When neither Expires nor MaxAge is set, you get a session cookie that the browser drops when it's closed. If both are set, browsers use Max-Age.

Call http.SetCookie before writing the response body, because cookies are headers. I'm using httptest.NewRecorder as the http.ResponseWriter so we can print what would be sent:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"
)

func main() {
	rec := httptest.NewRecorder()

	http.SetCookie(rec, &http.Cookie{
		Name:  "theme",
		Value: "dark",
	})

	http.SetCookie(rec, &http.Cookie{
		Name:     "session",
		Value:    "abc123",
		Path:     "/",
		Expires:  time.Date(2030, 1, 2, 15, 4, 5, 0, time.UTC),
		MaxAge:   3600,
		Secure:   true,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})

	for _, h := range rec.Header()["Set-Cookie"] {
		fmt.Println(h)
	}
}
theme=dark
session=abc123; Path=/; Expires=Wed, 02 Jan 2030 15:04:05 GMT; Max-Age=3600; HttpOnly; Secure; SameSite=Lax

Each call adds a separate Set-Cookie header. Don't combine several cookies into one header with commas.

Reading cookies in a handler

r.Cookie(name) returns the first cookie with that name. It returns http.ErrNoCookie if there's none:

package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
)

func handler(w http.ResponseWriter, r *http.Request) {
	c, err := r.Cookie("theme")
	if errors.Is(err, http.ErrNoCookie) {
		fmt.Fprintln(w, "no theme cookie, using default")
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "theme: %s\n", c.Value)
}

func main() {
	// request without cookies
	r := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()
	handler(w, r)
	fmt.Print(w.Body.String())

	// request with a Cookie header, the way a browser sends it
	r = httptest.NewRequest("GET", "/", nil)
	r.Header.Set("Cookie", "theme=dark; lang=en; tag=a; tag=b")
	w = httptest.NewRecorder()
	handler(w, r)
	fmt.Print(w.Body.String())

	fmt.Println("all cookies:")
	for _, c := range r.Cookies() {
		fmt.Printf("  %s = %s\n", c.Name, c.Value)
	}

	fmt.Println("named tag:")
	for _, c := range r.CookiesNamed("tag") {
		fmt.Printf("  %s = %s\n", c.Name, c.Value)
	}

	// r.Cookie returns the first one when a name repeats
	c, _ := r.Cookie("tag")
	fmt.Println("first tag:", c.Value)
}
no theme cookie, using default
theme: dark
all cookies:
  theme = dark
  lang = en
  tag = a
  tag = b
named tag:
  tag = a
  tag = b
first tag: a

The browser sends only name=value pairs. A cookie read from a request has just Name and Value set. You can't find out its Path, Expires or HttpOnly flag on the server.

The same name can show up more than once, for example when cookies with different Path or Domain values match the request. r.CookiesNamed (Go 1.23+) returns all of them.

You can't delete a cookie directly. Instead you overwrite it with one that has already expired. Set MaxAge to a negative number:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func logout(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:   "session",
		Value:  "",
		Path:   "/", // must match the Path used when setting it
		MaxAge: -1,  // delete now
	})
	fmt.Fprintln(w, "logged out")
}

func main() {
	w := httptest.NewRecorder()
	logout(w, httptest.NewRequest("POST", "/logout", nil))
	fmt.Println(w.Header().Get("Set-Cookie"))
}
session=; Path=/; Max-Age=0

The browser identifies a cookie by name, Domain and Path. If you set a cookie with Path: "/" and try to delete it with no Path, you get a second cookie, and the original stays.

Parsing and validating cookies

Go 1.23 added http.ParseCookie, which parses a Cookie header, and http.ParseSetCookie, which parses a Set-Cookie header. Cookie.Valid() reports whether a cookie can be serialized:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	cookies, err := http.ParseCookie("theme=dark; lang=en")
	if err != nil {
		panic(err)
	}
	for _, c := range cookies {
		fmt.Printf("%s=%s\n", c.Name, c.Value)
	}

	sc, err := http.ParseSetCookie(
		"session=abc123; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Strict")
	if err != nil {
		panic(err)
	}
	fmt.Printf("name=%s value=%s path=%s maxAge=%d httpOnly=%v secure=%v sameSite=%v\n",
		sc.Name, sc.Value, sc.Path, sc.MaxAge, sc.HttpOnly, sc.Secure,
		sc.SameSite == http.SameSiteStrictMode)

	_, err = http.ParseCookie("bad name=x")
	fmt.Println("error:", err)

	c := &http.Cookie{Name: "user id", Value: "42"}
	fmt.Println("valid:", c.Valid())
	fmt.Printf("String(): %q\n", c.String())

	c = &http.Cookie{Name: "user_id", Value: "42", Path: "/"}
	fmt.Println("valid:", c.Valid())
	fmt.Printf("String(): %q\n", c.String())
}
theme=dark
lang=en
name=session value=abc123 path=/ maxAge=3600 httpOnly=true secure=true sameSite=true
error: http: invalid cookie name
valid: http: invalid Cookie.Name
String(): ""
valid: <nil>
String(): "user_id=42; Path=/"

A cookie with an invalid name serializes to an empty string, and http.SetCookie silently drops it. If a cookie mysteriously doesn't show up in the browser, check c.Valid().

Cookie values are limited to a subset of ASCII. Double quotes, semicolons, backslashes, control characters and non-ASCII bytes aren't allowed. Go drops the invalid bytes and logs a warning. Values with spaces or commas are allowed, but Go wraps them in double quotes:

package main

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	rec := httptest.NewRecorder()

	// Characters like ; " \ and non-ASCII are not allowed in values.
	http.SetCookie(rec, &http.Cookie{Name: "bad", Value: `say "hi"; ok`})
	// Spaces and commas are allowed, but Go quotes the value.
	http.SetCookie(rec, &http.Cookie{Name: "spaced", Value: "hello world"})

	val := `{"name":"Zoë","items":[1,2]}`
	enc := base64.URLEncoding.EncodeToString([]byte(val))
	http.SetCookie(rec, &http.Cookie{Name: "prefs", Value: enc})

	for _, h := range rec.Header()["Set-Cookie"] {
		fmt.Println(h)
	}

	// read it back
	req := &http.Request{Header: http.Header{"Cookie": {"prefs=" + enc}}}
	c, _ := req.Cookie("prefs")
	dec, err := base64.URLEncoding.DecodeString(c.Value)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(dec))
}
2026/10/17 20:32:16 net/http: invalid byte '"' in Cookie.Value; dropping invalid bytes
bad="say hi ok"
spaced="hello world"
prefs=eyJuYW1lIjoiWm_DqyIsIml0ZW1zIjpbMSwyXX0=
{"name":"Zoë","items":[1,2]}

To store arbitrary data such as JSON, encode it with base64.URLEncoding or base64.RawURLEncoding. Their alphabets (A-Z a-z 0-9 - _ =) are all valid in cookie values. Browsers limit a cookie to about 4096 bytes, including the name and attributes, so keep cookies small. Store large data on the server and keep only an ID in the cookie.

Security attributes

A cookie that holds a session ID is as valuable as a password. For such cookies:

Browsers also enforce special name prefixes. A cookie named __Host-... is accepted only if it has Secure, Path=/ and no Domain. That stops a subdomain or an HTTP page from overwriting it. __Secure-... only requires Secure.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	rec := httptest.NewRecorder()

	// __Host- prefix: browser only accepts it with Secure, Path=/ and no Domain
	http.SetCookie(rec, &http.Cookie{
		Name:     "__Host-session",
		Value:    "abc123",
		Path:     "/",
		Secure:   true,
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	})

	// a cookie shared with subdomains
	http.SetCookie(rec, &http.Cookie{
		Name:   "lang",
		Value:  "en",
		Domain: "example.com",
		Path:   "/",
	})

	// a third-party cookie in an embedded widget (CHIPS)
	http.SetCookie(rec, &http.Cookie{
		Name:        "widget",
		Value:       "1",
		Path:        "/",
		Secure:      true,
		SameSite:    http.SameSiteNoneMode,
		Partitioned: true,
	})

	for _, h := range rec.Header()["Set-Cookie"] {
		fmt.Println(h)
	}
}
__Host-session=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
lang=en; Path=/; Domain=example.com
widget=1; Path=/; Secure; SameSite=None; Partitioned

SameSite=None requires Secure, otherwise browsers reject the cookie. During local development over http://localhost most browsers do accept Secure cookies, so you usually don't need a separate configuration.

Signed cookies

The user controls their cookies and can edit them freely. Never trust a cookie value like user=alice or role=admin. If you need to store data on the client, sign it with HMAC so you can detect changes:

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

var ErrInvalidCookie = errors.New("invalid cookie value")

// secret must be long and random; load it from config, don't hardcode it.
var secret = []byte("0123456789abcdef0123456789abcdef")

func sign(name, value string) string {
	mac := hmac.New(sha256.New, secret)
	// include the name so a value can't be copied into another cookie
	mac.Write([]byte(name + "=" + value))
	return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}

func SetSigned(w http.ResponseWriter, c *http.Cookie) {
	v := base64.RawURLEncoding.EncodeToString([]byte(c.Value))
	c.Value = v + "." + sign(c.Name, v)
	http.SetCookie(w, c)
}

func GetSigned(r *http.Request, name string) (string, error) {
	c, err := r.Cookie(name)
	if err != nil {
		return "", err
	}
	v, sig, ok := strings.Cut(c.Value, ".")
	if !ok {
		return "", ErrInvalidCookie
	}
	if !hmac.Equal([]byte(sig), []byte(sign(name, v))) {
		return "", ErrInvalidCookie
	}
	b, err := base64.RawURLEncoding.DecodeString(v)
	if err != nil {
		return "", ErrInvalidCookie
	}
	return string(b), nil
}

func main() {
	w := httptest.NewRecorder()
	SetSigned(w, &http.Cookie{Name: "user", Value: "alice", HttpOnly: true})
	setCookie := w.Header().Get("Set-Cookie")
	fmt.Println(setCookie)

	// the browser sends back name=value
	nameValue, _, _ := strings.Cut(setCookie, ";")

	r := &http.Request{Header: http.Header{"Cookie": {nameValue}}}
	user, err := GetSigned(r, "user")
	fmt.Printf("user=%q err=%v\n", user, err)

	// attacker changes the value to "admin" but can't compute the signature
	_, sig, _ := strings.Cut(nameValue, ".")
	forged := "user=" + base64.RawURLEncoding.EncodeToString([]byte("admin")) + "." + sig
	r = &http.Request{Header: http.Header{"Cookie": {forged}}}
	user, err = GetSigned(r, "user")
	fmt.Printf("user=%q err=%v\n", user, err)
}
user=YWxpY2U.Bj7dj2mTPqlwDyzUGunXnXwEBcCdY7IDMtrC-9ekHAc; HttpOnly
user="alice" err=<nil>
user="" err=invalid cookie value

Things to note:

Encrypted cookies

To hide the value as well, encrypt it with AES-GCM. GCM is an authenticated cipher: it detects tampering, so you don't need a separate HMAC. See Encryption and decryption with AES GCM for more about the cipher.

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
)

var ErrInvalidCookie = errors.New("invalid cookie value")

type CookieCipher struct{ aead cipher.AEAD }

// NewCookieCipher takes a 32-byte key (AES-256).
func NewCookieCipher(key []byte) (*CookieCipher, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	return &CookieCipher{aead}, nil
}

func (cc *CookieCipher) Encrypt(name, value string) string {
	nonce := make([]byte, cc.aead.NonceSize())
	rand.Read(nonce)
	// the cookie name is additional data: authenticated, not encrypted
	out := cc.aead.Seal(nonce, nonce, []byte(value), []byte(name))
	return base64.RawURLEncoding.EncodeToString(out)
}

func (cc *CookieCipher) Decrypt(name, value string) (string, error) {
	b, err := base64.RawURLEncoding.DecodeString(value)
	if err != nil || len(b) < cc.aead.NonceSize() {
		return "", ErrInvalidCookie
	}
	nonce, ct := b[:cc.aead.NonceSize()], b[cc.aead.NonceSize():]
	plain, err := cc.aead.Open(nil, nonce, ct, []byte(name))
	if err != nil {
		return "", ErrInvalidCookie
	}
	return string(plain), nil
}

func main() {
	key := make([]byte, 32)
	rand.Read(key)
	cc, err := NewCookieCipher(key)
	if err != nil {
		panic(err)
	}

	enc := cc.Encrypt("cart", "book:3,pen:10")
	c := &http.Cookie{Name: "cart", Value: enc, HttpOnly: true, Secure: true}
	fmt.Println("valid cookie:", c.Valid() == nil)
	fmt.Println("encrypted length:", len(enc))

	plain, err := cc.Decrypt("cart", enc)
	fmt.Printf("decrypted=%q err=%v\n", plain, err)

	// same value under a different cookie name is rejected
	_, err = cc.Decrypt("other", enc)
	fmt.Println("wrong name:", err)

	// flipping a single character is detected
	tampered := []byte(enc)
	if tampered[20] == 'A' {
		tampered[20] = 'B'
	} else {
		tampered[20] = 'A'
	}
	_, err = cc.Decrypt("cart", string(tampered))
	fmt.Println("tampered:", err)
}
valid cookie: true
encrypted length: 55
decrypted="book:3,pen:10" err=<nil>
wrong name: invalid cookie value
tampered: invalid cookie value

The output overhead is 12 bytes of nonce plus a 16-byte tag, and base64 adds another third on top. In a real program, load the key from configuration. A key generated at startup invalidates every cookie when the server restarts.

The gorilla/securecookie package implements the same idea (signing plus optional encryption, with timestamps and key rotation) if you'd rather not write it yourself.

Server-side sessions

For logins, the usual approach is to keep session data on the server and put only a random, unguessable ID in the cookie. Logging out deletes the session on the server, so a stolen cookie stops working right away. Here's a minimal in-memory version. rand.Text() (Go 1.24+) returns a cryptographically random string with 128 bits of entropy:

package session

import (
	"crypto/rand"
	"fmt"
	"net/http"
	"sync"
)

const cookieName = "session_id"

type Store struct {
	mu       sync.Mutex
	sessions map[string]string // session id -> user name
}

func NewStore() *Store { return &Store{sessions: map[string]string{}} }

func (s *Store) Login(w http.ResponseWriter, r *http.Request) {
	user := r.FormValue("user")
	if user == "" {
		http.Error(w, "missing user", http.StatusBadRequest)
		return
	}
	id := rand.Text() // 26 random base32 characters, Go 1.24+

	s.mu.Lock()
	s.sessions[id] = user
	s.mu.Unlock()

	http.SetCookie(w, &http.Cookie{
		Name:     cookieName,
		Value:    id,
		Path:     "/",
		MaxAge:   7 * 24 * 3600,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteLaxMode,
	})
	fmt.Fprintf(w, "welcome, %s\n", user)
}

func (s *Store) user(r *http.Request) (string, bool) {
	c, err := r.Cookie(cookieName)
	if err != nil {
		return "", false
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	u, ok := s.sessions[c.Value]
	return u, ok
}

func (s *Store) Me(w http.ResponseWriter, r *http.Request) {
	u, ok := s.user(r)
	if !ok {
		http.Error(w, "not logged in", http.StatusUnauthorized)
		return
	}
	fmt.Fprintf(w, "you are %s\n", u)
}

func (s *Store) Logout(w http.ResponseWriter, r *http.Request) {
	if c, err := r.Cookie(cookieName); err == nil {
		s.mu.Lock()
		delete(s.sessions, c.Value) // invalidate on the server too
		s.mu.Unlock()
	}
	http.SetCookie(w, &http.Cookie{
		Name:     cookieName,
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteLaxMode,
	})
	fmt.Fprintln(w, "bye")
}

A real application would also expire old sessions and store them in a database or Redis, so they survive restarts and work across multiple servers.

Testing cookies

In tests, rec.Result().Cookies() parses the Set-Cookie headers of a recorded response, and req.AddCookie attaches a cookie to a request. Together they let you simulate a browser. See Testing HTTP requests for more on httptest.

package session

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestLoginSetsCookie(t *testing.T) {
	s := NewStore()
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("POST", "/login", strings.NewReader("user=alice"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	s.Login(rec, req)

	cookies := rec.Result().Cookies()
	if len(cookies) != 1 {
		t.Fatalf("got %d cookies, want 1", len(cookies))
	}
	c := cookies[0]
	if c.Name != cookieName || !c.HttpOnly || !c.Secure {
		t.Errorf("bad cookie: %s", c)
	}
	if len(c.Value) != 26 {
		t.Errorf("session id %q has length %d", c.Value, len(c.Value))
	}
}

func TestLoginMeLogout(t *testing.T) {
	s := NewStore()

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("POST", "/login?user=bob", nil)
	s.Login(rec, req)
	session := rec.Result().Cookies()[0]

	// send the cookie back, like a browser would
	rec = httptest.NewRecorder()
	req = httptest.NewRequest("GET", "/me", nil)
	req.AddCookie(session)
	s.Me(rec, req)
	if got := rec.Body.String(); got != "you are bob\n" {
		t.Errorf("Me: got %q", got)
	}

	rec = httptest.NewRecorder()
	req = httptest.NewRequest("POST", "/logout", nil)
	req.AddCookie(session)
	s.Logout(rec, req)
	if c := rec.Result().Cookies()[0]; c.MaxAge >= 0 {
		t.Errorf("logout cookie MaxAge = %d, want < 0", c.MaxAge)
	}

	// the old cookie no longer works even if the client keeps it
	rec = httptest.NewRecorder()
	req = httptest.NewRequest("GET", "/me", nil)
	req.AddCookie(session)
	s.Me(rec, req)
	if rec.Code != http.StatusUnauthorized {
		t.Errorf("after logout: got %d, want 401", rec.Code)
	}
}
$ go test -v
=== RUN   TestLoginSetsCookie
--- PASS: TestLoginSetsCookie (0.00s)
=== RUN   TestLoginMeLogout
--- PASS: TestLoginMeLogout (0.00s)
PASS

req.AddCookie only serializes Name and Value, just like a browser does.

Cookies in an HTTP client

By default http.Client ignores Set-Cookie headers and never sends cookies. To make it behave like a browser, give it a cookie jar from net/http/cookiejar:

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{Name: "session", Value: "s3cr3t", Path: "/"})
		fmt.Fprint(w, "logged in")
	})
	mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
		c, err := r.Cookie("session")
		if err != nil {
			http.Error(w, "not logged in", http.StatusUnauthorized)
			return
		}
		fmt.Fprintf(w, "hello, session %s", c.Value)
	})
	srv := httptest.NewServer(mux)
	defer srv.Close()

	get := func(c *http.Client, path string) {
		resp, err := c.Get(srv.URL + path)
		if err != nil {
			panic(err)
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("%s -> %d %s\n", path, resp.StatusCode, body)
	}

	fmt.Println("without a jar:")
	plain := &http.Client{}
	get(plain, "/login")
	get(plain, "/me")

	fmt.Println("with a jar:")
	jar, err := cookiejar.New(nil)
	if err != nil {
		panic(err)
	}
	client := &http.Client{Jar: jar}
	get(client, "/login")
	get(client, "/me")

	u, _ := url.Parse(srv.URL)
	for _, c := range jar.Cookies(u) {
		fmt.Printf("jar has %s=%s\n", c.Name, c.Value)
	}

	// add a cookie manually, e.g. one restored from disk
	jar.SetCookies(u, []*http.Cookie{{Name: "session", Value: "restored"}})
	get(client, "/me")

	// or attach a cookie to a single request
	req, _ := http.NewRequest("GET", srv.URL+"/me", nil)
	req.AddCookie(&http.Cookie{Name: "session", Value: "one-off"})
	resp, err := plain.Do(req)
	if err != nil {
		panic(err)
	}
	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()
	fmt.Printf("AddCookie -> %d %s\n", resp.StatusCode, body)
	fmt.Println("Cookie header:", req.Header.Get("Cookie"))
}
without a jar:
/login -> 200 logged in
/me -> 401 not logged in

with a jar:
/login -> 200 logged in
/me -> 200 hello, session s3cr3t
jar has session=s3cr3t
/me -> 200 hello, session restored
AddCookie -> 200 hello, session one-off
Cookie header: session=one-off

The jar follows browser rules. It respects Domain, Path, expiration and Secure, and it also stores cookies set by redirect responses that the client follows.

cookiejar.New(nil) works fine for talking to a single host. When the client visits arbitrary sites, pass a public suffix list so a server at evil.co.uk can't set cookies for all of co.uk:

import "golang.org/x/net/publicsuffix"

jar, err := cookiejar.New(&cookiejar.Options{
	PublicSuffixList: publicsuffix.List,
})

The jar is in-memory only. To persist cookies between runs, save jar.Cookies(u) for the URLs you care about and restore them with jar.SetCookies. Keep in mind that cookies read from a jar have only Name and Value set.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents