Flask-WTF rejects a React request even though the CSRF token is sent
The 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.
Fix it fast
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>"2Match what you see, then jump to its fix
- 1
React 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
It 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
The 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
The 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
- 1
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
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 runConfirmed by flask.palletsprojects.com
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-cookieConfirmed by flask.palletsprojects.com
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
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Flask-WTF raises KeyError: A secret key is required to use CSRF
KeyError: 'A secret key is required to use CSRF.'
Flask-WTF signs its CSRF token with the app's SECRET_KEY, or with WTF_CSRF_SECRET_KEY if you set that.
4 causes, each with a fixWeb 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 fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
npm start stops with Could not find a required file in a React app
Name: index.html
react-scripts checks for two files before the dev server starts: public/index.html and a src/index file.
3 causes, each with a fixBack end
Create React App says Node is too old, and npm will not run on the new one
npm does not support Node.js v10.19.0
The shell is running an old Node.js that is below the version Create React App needs.
3 causes, each with a fixBack end
jwtDecode throws InvalidTokenError in React Native
Property 'atob' doesn't exist
jwt-decode uses the global atob function.
2 causes, each with a fix