Skip to content

fix: persist generated FLASK_SECRET_KEY to prevent session loss on restart#1721

Open
gdeyoung wants to merge 1 commit into
agent0ai:mainfrom
gdeyoung:fix/persist-flask-secret-key
Open

fix: persist generated FLASK_SECRET_KEY to prevent session loss on restart#1721
gdeyoung wants to merge 1 commit into
agent0ai:mainfrom
gdeyoung:fix/persist-flask-secret-key

Conversation

@gdeyoung

Copy link
Copy Markdown
Contributor

Problem

When FLASK_SECRET_KEY is not explicitly set in the environment, the server generates a new random secret key on every restart:

webapp.secret_key = os.getenv("FLASK_SECRET_KEY") or secrets.token_hex(32)

This invalidates all browser session cookies, causing authenticated API/WebSocket requests to redirect to /login (returning HTML) instead of returning JSON. The frontend then fails with:

"Unexpected token <"

This is particularly impactful for Docker deployments where containers are restarted regularly.

Fix

When FLASK_SECRET_KEY is not set, auto-generate one AND persist it to usr/.env using the existing dotenv.save_dotenv_value() helper:

flask_secret_key = os.getenv("FLASK_SECRET_KEY")
if not flask_secret_key:
    flask_secret_key = secrets.token_hex(32)
    dotenv.save_dotenv_value("FLASK_SECRET_KEY", flask_secret_key)
webapp.secret_key = flask_secret_key

This way, the generated key survives restarts and sessions remain valid. Users can still override with their own key via the env var.

Testing

  • Verified on local Docker deployment with 3 separate containers
  • Sessions persist across container restarts
  • No more Unexpected token < errors after restart
  • Existing manually-set FLASK_SECRET_KEY values are respected (backward compatible)

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

When FLASK_SECRET_KEY is not set, the server generates a random key
on every restart. This invalidates all browser session cookies,
causing API/WebSocket requests to redirect to /login (HTML) instead
of returning JSON. The frontend then fails with 'Unexpected token <'.

Fix: auto-generate and persist the key to usr/.env using the existing
dotenv.save_dotenv_value() helper, so sessions survive restarts.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant