RuntimeError: The session is unavailable because no secret key was set
RuntimeError: session secret key missing
$ flask run
Traceback (most recent call last):
...
RuntimeError: The session is unavailable because no secret key was set.
Why this happens
Flask uses SECRET_KEY to sign session cookies. If it’s not configured, any access to session will fail. This often happens in new projects or when environment variables aren’t loaded.
Fix
- Set a
SECRET_KEYin config and load it before handling requests. - Use a strong random key for production and avoid committing secrets to source control.
Wrong code
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def index():
session['x'] = 1 # fails
return 'OK'
Fixed code
from flask import Flask, session
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev-change-me'
@app.route('/')
def index():
session['x'] = 1
return 'OK'