0
0
FlaskDebug / FixBeginner · 4 min read

How to Fix 'Secret Key Not Set' Error in Flask

To fix the secret key not set error in Flask, you must assign a secret key string to app.secret_key before using sessions or security features. This key helps Flask keep data safe and must be set to a random, secret value.
🔍

Why This Happens

This error occurs because Flask needs a secret key to securely sign session cookies and protect against tampering. If you try to use sessions or features like flash() without setting app.secret_key, Flask will raise this error.

python
from flask import Flask, session

app = Flask(__name__)

@app.route('/')
def index():
    session['user'] = 'Alice'
    return 'User set in session'

if __name__ == '__main__':
    app.run()
Output
RuntimeError: The secret key is not set. Set the secret_key on the application to something unique and secret.
🔧

The Fix

Set a secret key string on your Flask app by assigning a random, secret value to app.secret_key. This key should be kept private and can be any random string or bytes. This allows Flask to securely sign session data.

python
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'your-random-secret-key-12345'

@app.route('/')
def index():
    session['user'] = 'Alice'
    return 'User set in session'

if __name__ == '__main__':
    app.run()
Output
User set in session
🛡️

Prevention

Always set app.secret_key before using sessions or security features in Flask. Use environment variables or configuration files to keep the key secret and avoid hardcoding it in your code. For production, generate a strong random key using Python's secrets module.

  • Use secrets.token_hex(16) to generate a secure key.
  • Load the key from environment variables with os.environ.
  • Keep the key private and do not share it publicly.
python
import os
import secrets
from flask import Flask

app = Flask(__name__)

# Generate a strong secret key once and save it securely
# For example, set it as an environment variable
app.secret_key = os.environ.get('FLASK_SECRET_KEY', secrets.token_hex(16))
⚠️

Related Errors

Other errors related to Flask secret keys include:

  • Invalid session cookie: Happens if the secret key changes between requests.
  • Warning about weak secret key: Using simple or guessable keys can cause security warnings.
  • Missing environment variable: If you rely on environment variables but forget to set them, Flask won't have a secret key.

Fix these by ensuring the secret key is consistent, strong, and properly loaded.

Key Takeaways

Always set a secret key on your Flask app before using sessions or security features.
Use a strong, random secret key and keep it private to protect your app.
Load the secret key from environment variables or secure config files for production.
Changing the secret key invalidates existing sessions, so keep it consistent.
Use Python's secrets module to generate secure keys instead of simple strings.