Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Flask-WTF rejects a React request even though the CSRF token is sent

ErrorThe CSRF session token is missing.

Short answer

Flask-WTF checks two things: the token sent with the request and a copy kept in the session cookie. 'Session token is missing' means the cookie never reached Flask. From a React app on another origin the browser omits it unless fetch uses credentials: 'include'. A changing SECRET_KEY or a wrong cookie setting has the same effect.

  • Applies to Flask 3.1, Flask-WTF 1.2, React 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    In the browser Network tab, open the failing request and check its request headers. Is there a Cookie header with the session cookie (named 'session' by default) as well as the token header? A missing cookie points to the first cause below.

    curl -i -c jar.txt http://localhost:5000/csrf-token
    curl -i -b jar.txt -X POST http://localhost:5000/api/items -H "X-CSRFToken: <token>"
  2. 2Match what you see, then jump to its fix

    1. 1React runs on another origin (localhost:5173 or a different domain) than Flask, and the request has the token header but no Cookie header.The browser does not send the session cookie cross-originFix
    2. 2It works right after a restart and fails later, or fails only with several workers or containers.The secret key changes between requests, so the old session cookie is unreadableFix
    3. 3The Set-Cookie header shows on the response but the cookie is not stored or sent next time.The session cookie settings stop the browser keeping itFix
    4. 4The error is about the token (missing or invalid), not the session, and the request body is JSON.The token is sent in the wrong place or with the wrong headerFix

What does the error look like?

  • The CSRF session token is missing.
  • 400 Bad Request on POST, PUT, PATCH or DELETE from a React app

Cause 1 of 4

The browser does not send the session cookie cross-origin

1Check

fetch uses credentials: 'same-origin' by default, which sends cookies and respects Set-Cookie only for same-origin requests. For a cross-origin API, both the token request and the POST must opt in.

grep -rn "credentials" src/

2Fix

Use credentials: 'include' on the request that fetches the token and on the request that sends data. Flask must also answer with CORS headers that allow credentials for your specific origin; see your CORS library docs.

await fetch('http://localhost:5000/csrf-token', { credentials: 'include' });
await fetch('http://localhost:5000/api/items', {
  method: 'POST',
  credentials: 'include',
  headers: { 'Content-Type': 'application/json', 'X-CSRFToken': token },
  body: JSON.stringify({ name: 'x' }),
});

3Verify

The POST request in the Network tab now carries a Cookie header.

curl -i -b jar.txt -X POST http://localhost:5000/api/items -H "X-CSRFToken: <token>"

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 4

The secret key changes between requests, so the old session cookie is unreadable

1Check

SECRET_KEY signs the session cookie, and Flask-WTF uses it for tokens unless WTF_CSRF_SECRET_KEY is set. If each process starts with a different random key, a cookie signed by one cannot be read by another.

python -c "from app import app; print(bool(app.config.get('SECRET_KEY')))"

2Fix

Set one fixed key from the environment and use the same value in every process. For rotation, list old keys in SECRET_KEY_FALLBACKS (Flask 3.1).

import os
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

3Verify

Restart, load the page, then send the request again; the session survives.

flask --app app run

Confirmed by flask.palletsprojects.com

Did this fix it?

Cause 3 of 4

The session cookie settings stop the browser keeping it

1Check

SESSION_COOKIE_SECURE makes browsers send the cookie only over HTTPS, SESSION_COOKIE_DOMAIN limits which hosts get it, and SESSION_COOKIE_SAMESITE restricts cookies on requests from external sites.

python -c "from app import app; print({k: app.config.get(k) for k in ('SESSION_COOKIE_SECURE','SESSION_COOKIE_DOMAIN','SESSION_COOKIE_SAMESITE','SESSION_COOKIE_NAME')})"

2Fix

Match the settings to how you serve the app: no Secure flag on plain http during local development, no Domain unless you need subdomains, and a Lax value for same-site setups. Better still, serve React and Flask from one origin through a proxy so none of this applies.

app.config.update(
    SESSION_COOKIE_SECURE=False,   # local http only; keep True behind https
    SESSION_COOKIE_SAMESITE='Lax',
)

3Verify

The Application tab shows the session cookie after the first response.

curl -i -c jar.txt http://localhost:5000/csrf-token | grep -i set-cookie

Confirmed by flask.palletsprojects.com

Did this fix it?

Cause 4 of 4

The token is sent in the wrong place or with the wrong header

1Check

For AJAX Flask-WTF reads the token from a header. The default WTF_CSRF_HEADERS are X-CSRFToken and X-CSRF-Token; a form field must be named csrf_token.

grep -rn "X-CSRF" src/

2Fix

Send the token in one of those headers, and set WTF_CSRF_HEADERS only if you must use another.

headers: { 'X-CSRFToken': token }

3Verify

The request returns 200 instead of 400.

curl -i -b jar.txt -X POST http://localhost:5000/api/items -H "X-CSRFToken: <token>"

Confirmed by flask-wtf.readthedocs.io

Did this fix it?

How do I stop it coming back?

  • Serve the React build and the API from one origin in production, and proxy the dev server, so cookies stay first-party.
  • Keep SECRET_KEY in the environment, never generate it at startup.
  • Add a tiny endpoint that returns a token and call it with credentials before the first POST.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

The browser blocks your API response: no Access-Control-Allow-Origin header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin.

4 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.