Flask-WTF raises KeyError: A secret key is required to use CSRF
KeyError: 'A secret key is required to use CSRF.'Short answer
Flask-WTF signs its CSRF token with the app's SECRET_KEY, or with WTF_CSRF_SECRET_KEY if you set that. The error means neither is set when the form is built. Set a long random value in the app config, and make sure it is loaded before the form is used.
Fix it fast
1Find out which cause you have
Print what the running app has for the key. None means it was never set.
python -c "from app import app; print(app.config.get('SECRET_KEY'))"2Match what you see, then jump to its fix
- 1
The print shows NoneSECRET_KEY is not set at allFix - 2
You exported FLASK_SECRET_KEY, but the config still shows NoneThe key is in an environment variable that Flask never readsFix - 3
The key exists in a config file, but the error shows when the app startsThe config is loaded too late or in another app instanceFix - 4
Your session key must stay private to another serviceYou want a separate key just for CSRFFix
- 1
What does the error look like?
KeyError: 'A secret key is required to use CSRF.'
Cause 1 of 4
SECRET_KEY is not set at all
1Check
Flask's SECRET_KEY default is None, and Flask-WTF uses it by default to sign tokens.
grep -rn "SECRET_KEY" .2Fix
Generate a long random value once and put it in your config.
# generate
python -c 'import secrets; print(secrets.token_hex())'
# app.py
app.config["SECRET_KEY"] = "<paste the generated value>"3Verify
Reload the page. The form renders with a hidden csrf_token field.
curl -s http://127.0.0.1:5000/login | grep csrf_tokenConfirmed by flask.palletsprojects.com
Cause 2 of 4
The key is in an environment variable that Flask never reads
1Check
Flask only copies prefixed environment variables into the config when from_prefixed_env() is called. The default prefix is FLASK_.
echo "$FLASK_SECRET_KEY"2Fix
Call from_prefixed_env() right after creating the app.
app = Flask(__name__)
app.config.from_prefixed_env()3Verify
Print the config value again; it is no longer None.
FLASK_SECRET_KEY=abc python -c "from app import app; print(app.config['SECRET_KEY'])"Confirmed by flask.palletsprojects.com
Cause 3 of 4
The config is loaded too late or in another app instance
1Check
Flask advises loading configuration very early, so extensions can read it when they start. With an application factory, set the key inside the same factory before init_app runs.
grep -n "CSRFProtect\|init_app\|config\.from" app.py2Fix
Load config first, then create extensions on that app.
def create_app():
app = Flask(__name__)
app.config.from_object("config.ProductionConfig")
csrf.init_app(app)
return app3Verify
Start the app and load a page with a form.
flask --app app runConfirmed by flask.palletsprojects.com
Cause 4 of 4
You want a separate key just for CSRF
1Check
WTF_CSRF_SECRET_KEY is the random data used to make tokens. If it is not set, SECRET_KEY is used.
grep -rn "WTF_CSRF" .2Fix
Set WTF_CSRF_SECRET_KEY in the config. Do not turn CSRF off with WTF_CSRF_ENABLED = False to silence the error; that only removes the protection.
app.config["WTF_CSRF_SECRET_KEY"] = "<another generated value>"3Verify
Render a form and submit it; the POST is accepted.
curl -s http://127.0.0.1:5000/login | grep csrf_tokenConfirmed by flask-wtf.readthedocs.io
How do I stop it coming back?
- Keep SECRET_KEY out of git; load it from an environment variable or an instance config file.
- Use one config loader and call it at the top of create_app.
- Never ship WTF_CSRF_ENABLED = False to production.
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:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Web apps
CORS fails when you open an HTML file straight from disk
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///
A page opened from disk has an opaque origin, so browsers treat every request it makes as cross-origin, and CORS only works over http or https.
3 causes, each with a fixWeb apps
django-cors-headers settings have no effect
CORS_ALLOWED_ORIGINS not working
django-cors-headers only works when corsheaders is in INSTALLED_APPS, CorsMiddleware sits high in MIDDLEWARE (before CommonMiddleware), and at least one origin setting is defined.
4 causes, each with a fixWeb apps
django-tailwind cannot find the npm executable (cPanel, Windows, Linux)
CommandError raised by the tailwind management command about npm
django-tailwind runs npm as a subprocess, and Python sometimes cannot find it.
3 causes, each with a fixWeb apps
Django deploy on Vercel fails because Cargo (Rust) is not installed
Cargo, the Rust package manager, is not installed or is not on PATH.
The message means one of your packages had no ready-made wheel for the Python version Vercel used, so pip tried to build it from source, and that needs Rust.
2 causes, each with a fixWeb apps
tsconfig rejects allowImportingTsExtensions
An error that allowImportingTsExtensions needs noEmit or emitDeclarationOnly
allowImportingTsExtensions lets files import each other with .ts or .tsx extensions, and TypeScript only allows it together with noEmit or emitDeclarationOnly.
2 causes, each with a fixWeb apps
AuthUserPoolException: Auth UserPool not configured in a Next.js app
Auth UserPool not configured
The error means an Amplify Auth call ran before Amplify.configure did.
3 causes, each with a fix