http.ErrNoCookie
GoERRORCommonHTTP
http: named cookie not present
Quick Answer
Check the error from r.Cookie("name") before using the result; return a 400 if the cookie is required.
What this means
Returned by Request.Cookie when no cookie with the specified name is found in the request. Always check for this before using the cookie value.
Why it happens
- 1Client did not send the expected cookie
- 2Cookie name mismatch between client and server code
Fix
Check and respond with 400
Check and respond with 400
c, err := r.Cookie("session")
if errors.Is(err, http.ErrNoCookie) {
http.Error(w, "missing cookie", 400)
return
}Why this works
Early return prevents nil pointer dereference when the cookie is absent.
Code examples
Detectgo
c, err := r.Cookie("token")
if errors.Is(err, http.ErrNoCookie) {
fmt.Println("no cookie")
}Use cookie value safelygo
c, err := r.Cookie("session")
if err == nil {
fmt.Println(c.Value)
}Set cookiego
http.SetCookie(w, &http.Cookie{
Name: "session", Value: "abc123",
})Same error in other languages
Sources
Official documentation ↗
Go standard library
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev