Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Flask-WTF raises KeyError: A secret key is required to use CSRF

ErrorKeyError: '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.

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

Fix it fast

  1. 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'))"
  2. 2Match what you see, then jump to its fix

    1. 1The print shows NoneSECRET_KEY is not set at allFix
    2. 2You exported FLASK_SECRET_KEY, but the config still shows NoneThe key is in an environment variable that Flask never readsFix
    3. 3The 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. 4Your session key must stay private to another serviceYou want a separate key just for CSRFFix

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_token

Confirmed by flask.palletsprojects.com

Did this fix it?

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

Did this fix it?

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.py

2Fix

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 app

3Verify

Start the app and load a page with a form.

flask --app app run

Confirmed by flask.palletsprojects.com

Did this fix it?

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_token

Confirmed by flask-wtf.readthedocs.io

Did this fix it?

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:

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 fix

Web 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 fix

Web 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 fix

Next step

Want this handled for good?

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