Middleware
CSRF
Double-submit cookie protection for state-changing requests.
CSRF
middleware.CSRF protects unsafe methods with a double-submit cookie. Safe
requests receive a token cookie, and unsafe requests must send the same value
in a header.
app.Use(middleware.CSRF())The defaults are:
| Option | Default |
|---|---|
CookieName | csrf_token |
HeaderName | X-CSRF-Token |
TokenLen | 32 bytes |
TokenLen is the number of random bytes. The cookie value is hex encoded, so
the string is twice as long.
How it works
GET,HEAD, andOPTIONSrequests are considered safe.- A safe request without the cookie gets a new random token.
- The token cookie uses
Path=/,HttpOnly=false, and a one-day lifetime. - Unsafe methods require the cookie and the header to be present and equal.
- A missing or mismatched token returns
403 Forbiddenwithinvalid csrf token. - Valid requests continue with
Next.
HttpOnly is disabled because browser code must read the cookie and copy it
into the header. The cookie is a random value, not a session secret.
Client usage
function csrfToken() {
const match = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
return match ? decodeURIComponent(match[1]) : "";
}
await fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken(),
},
body: JSON.stringify({ item: "book" }),
});The first page load must make a safe request, such as GET /, before the
client can read the cookie.
Notes
- The token is not signed. Its security comes from the same-origin policy and the requirement that an attacker cannot read the cookie.
- Use HTTPS in production.
- This middleware does not set
SameSite. Set it in a reverse proxy or add a custom cookie policy if your deployment needs it. - For APIs that authenticate with a bearer token and no cookies, CSRF is not required because the browser does not attach credentials automatically.

Ply