Flask Secret Key Generator

Generate a Flask SECRET_KEY: 32 random bytes as hex, the same as Python's secrets.token_hex(). Signs sessions, cookies and CSRF tokens.

Why Flask needs a secret key

Flask signs its session cookie with SECRET_KEY, and extensions such as Flask-WTF and Flask-Login use it for CSRF tokens and remember-me cookies. Anyone who knows the key can forge a session and sign in as any user, so it must be long, random and private.

The Flask documentation suggests running python -c ‘import secrets; print(secrets.token_hex())’, which prints 32 random bytes as hex. That is exactly what this generator makes.

Loading it safely

import os
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

Never commit the key, and never leave a placeholder like “dev” in production. Use a different key per environment.

Frequently asked questions

What happens if I change the secret key?

Existing sessions become invalid and users are logged out. Flask 3.1 and later can accept older keys during a rotation through the SECRET_KEY_FALLBACKS setting.

Is hex the right format?

Any long random string works, but hex is safe everywhere: shells, environment files and YAML.