Flask SECRET_KEY: Temporary key in development invalidates production sessions
27.5K reputation · 04 Jan 2020, 10:09 UTC
Flask SECRET_KEY Behavior
When a Flask application starts without an explicit app.config['SECRET_KEY'], the framework falls back to generating a random key for each request. Locally this allows sessions to appear to persist, but the key changes on every reload, causing signed cookies to become invalid. In a production deployment, the same automatic key generation leads to authentication failures or lost session data, breaking features that rely on Flask-Login, Flask-Session, or other signed‑cookie mechanisms.
The core issue is the lack of a required configuration boundary: developers can run an app locally without a key, yet production environments must supply a secure, stable secret. This ambiguity creates an unresolved decision point in Flask’s design.
Key questions for architects and developers:
- Should Flask enforce a mandatory
SECRET_KEYat startup, or is the current optional behavior acceptable? - What is the most robust way to supply a secret in production (environment variable, secrets manager, config file) while keeping it out of source control?
- Can Flask provide a warning or error when a request‑time generated key is detected, to aid in debugging deployment issues?