A browser automatically sends matching cookies with requests. That convenience lets a session cookie keep a user signed in, but it also means a malicious site may be able to make the browser send an authenticated request the user did not intend. For a small web app, the practical fix is to combine secure cookie settings with server-side CSRF protection on every state-changing action.
This guide covers the controls to check whether you use server-rendered forms or a JavaScript API. It focuses on ordinary cookie-authenticated web apps; use your framework's maintained security features rather than writing a new CSRF library.
Why cookie-authenticated apps need CSRF protection
Cross-site request forgery (CSRF) abuses the browser's automatic credential handling. If a signed-in browser visits another site, that site may cause the browser to send a request to your app. The browser can attach the app's session cookie, even though the request did not originate from your interface. The attacker does not need to read the response for an unwanted action to happen.
Treat a request as state-changing if it can change an account, submit a payment, update settings, create or delete data, or perform another action under the user's permissions. Do not use GET for these operations: browsers and other systems use safe methods for navigation, previews, and retrieval. Use an unsafe method such as POST, PUT, PATCH, or DELETE, and still apply CSRF protection.
Set secure session-cookie attributes
For an HTTPS-only app that does not need its session cookie on other subdomains, configure the session cookie with Path=/; Secure; HttpOnly; SameSite=Lax. The __Host- prefix is supported by modern browsers and requires Secure, Path=/, and no Domain attribute. Naming the cookie __Host-session and omitting Domain keeps it host-only instead of sharing it with subdomains. Let your framework generate and manage the session identifier.
| Attribute | What it does | What it does not do |
|---|---|---|
Secure |
Sends the cookie only over HTTPS (apart from localhost exceptions). | It does not stop a browser from attaching the cookie to a forged HTTPS request. |
HttpOnly |
Prevents page JavaScript from reading the cookie through APIs such as document.cookie. |
It does not stop the browser from sending the cookie with JavaScript-initiated requests or prevent CSRF. |
SameSite=Lax |
Restricts the cookie on cross-site requests while allowing some top-level navigations. | It is not a complete CSRF defense; cross-site safe-method navigations can still carry it, and same-site subdomains are a separate trust boundary. |
SameSite=Strict blocks the cookie on cross-site requests more aggressively, but a user following a link from another site may arrive without their session. Use it when that behavior fits the app. SameSite=None permits cross-site cookie use and requires Secure; choose it only when a real cross-site workflow needs it, and add an explicit CSRF defense.
The browser's definition of “site” is broader than “origin.” Two different subdomains can be same-site, so a SameSite policy does not protect you from an untrusted or compromised sibling subdomain. Avoid broad cookie domains unless the app needs them. Cookie Path is a routing scope, not a security boundary. See MDN's Set-Cookie reference for browser behavior and OWASP's session management guidance for session-cookie recommendations.
Validate a CSRF token on state-changing requests
First check whether your framework already provides CSRF middleware or form helpers. Enable and configure that feature, then make sure every cookie-authenticated state-changing endpoint uses it.
For a server-side session, a common approach is the synchronizer token pattern:
- Generate an unpredictable token on the server and associate it with the user's session.
- Include it in each relevant form as a hidden field, or provide it to same-origin JavaScript for a request header.
- On the server, compare the submitted token with the token for the authenticated session. Reject the operation if it is missing or does not match.
Do not put a synchronizer token in a URL, where it can leak into browser history, logs, or referrer data. The token must be validated by the server; merely adding a hidden field in the page is not protection. For apps without server-side session state, OWASP recommends a signed double-submit cookie pattern bound to the user's session. Avoid a naive cookie-and-request-value comparison, which can be vulnerable to cookie injection.
For a JavaScript API, a custom request header can be part of the defense because an ordinary cross-origin HTML form cannot set it. This depends on the browser enforcing CORS correctly: allow only origins you control, and do not accept broad or reflected origins for credentialed requests. If you also accept form-encoded or other simple request types, ensure those routes are protected too. See the OWASP CSRF Prevention Cheat Sheet for framework support, token patterns, and API guidance.
Add origin and Fetch Metadata checks as extra layers
For state-changing requests, you can also check that the Origin header matches your expected origin. A carefully implemented Referer check can serve as a fallback when Origin is absent. These checks complement a CSRF token; they should not replace it without a deliberate framework-supported design.
Modern browsers may send the Sec-Fetch-Site header to describe whether a request is same-origin, same-site, or cross-site. A server can reject cross-site unsafe requests and apply a stricter policy to same-site requests if it does not trust every subdomain. Decide how to handle missing headers rather than silently treating them as safe, and account for legitimate cross-origin integrations before enforcing a rule.
Use your framework's CSRF and cookie protections alongside broader browser controls. Our guide to HTTP security headers for small web applications covers other layers that can reduce the impact of browser-based attacks.
How bearer-token APIs differ
A browser app that explicitly adds a bearer token in an Authorization header has a different CSRF exposure from one that relies on an automatically attached session cookie: a cross-site form cannot add that header. Cross-origin JavaScript requests with custom headers are subject to CORS, so keep the allowed origins narrow and avoid granting credentials to origins you do not control.
This is not a reason to treat every bearer-token design as automatically safe. If the browser stores the token in a cookie, or automatically attaches it to cross-origin requests, the request may again carry credentials without the user's intent. XSS is also a separate risk: script running in your app can often act with the user's authority even when cookie settings prevent it from reading the session cookie. See MDN's CSRF overview and CORS guide when deciding how your browser client sends credentials.
A short implementation checklist
- Keep the session cookie
SecureandHttpOnly; set an explicitSameSitevalue that fits the app. - Prefer a host-only session cookie and avoid changing application data through
GET. - Use maintained framework CSRF protection for every cookie-authenticated state change.
- Verify the token on the server, and reject missing or invalid values.
- Treat
SameSite, origin checks, and Fetch Metadata as layers, not a substitute for an appropriate primary defense. - Test sign-in, form submissions, API mutations, external login or payment callbacks, and any trusted subdomain flows before enforcing stricter policies.
The goal is not to add every possible header or token. It is to make the browser's automatic session cookie insufficient on its own to authorize a state change, while preserving the cross-site flows your app intentionally supports.