{"record":{"id":"bc586ed409dd403c","repo":"pallets/flask","slug":"the-session-is-unavailable-because-no-secret-key-w","errorCode":null,"errorMessage":"The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.","messagePattern":"The session is unavailable because no secret key was set\\.  Set the secret_key on the application to something unique and secret\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/flask/sessions.py","lineNumber":90,"sourceCode":"\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n\n\nclass SessionInterface:\n    \"\"\"The basic interface you have to implement in order to replace the\n    default session interface which uses werkzeug's securecookie\n    implementation.  The only methods you have to implement are\n    :meth:`open_session` and :meth:`save_session`, the others have\n    useful defaults which you don't need to change.\n\n    The session object returned by the :meth:`open_session` method has to\n    provide a dictionary like interface plus the properties and methods","sourceCodeStart":72,"sourceCodeEnd":108,"githubUrl":"https://github.com/pallets/flask/blob/3596b1ab61cea85edb8970e83ff61daa073facf8/src/flask/sessions.py#L72-L108","documentation":"When app.secret_key is not set, Flask's SecureCookieSessionInterface uses NullSession, whose mutating methods (__setitem__, clear, pop, update, etc.) all call _fail and raise RuntimeError. Sessions need the secret key to sign cookies; without it, write attempts are rejected. Read access to the empty session still works.","triggerScenarios":"Writing to flask.session (session['user']=x) before setting app.secret_key; running a dev server with FLASK_DEBUG but no SECRET_KEY in config; tests that mutate session on a freshly created app without a key.","commonSituations":"Missing SECRET_KEY env var; config loading order putting secret_key assignment after the first request; switching from server-side sessions to default cookie sessions without setting a key; tutorial code that omitted the key.","solutions":["Set app.secret_key to a long random value: app.secret_key = os.environ['SECRET_KEY'] or os.urandom(32).","Load SECRET_KEY from environment/secret store before app.run; fail startup loudly if it is missing.","For tests, set app.secret_key = 'test' in the test app factory."],"exampleFix":"// before\napp = Flask(__name__)\n@app.route('/')\ndef index():\n    session['k'] = 1  # raises\n    return 'ok'\n\n// after\napp = Flask(__name__)\napp.secret_key = os.environ['SECRET_KEY']\n@app.route('/')\ndef index():\n    session['k'] = 1\n    return 'ok'","handlingStrategy":"validation","validationCode":"def require_secret_key(app):\n    if not app.secret_key:\n        raise RuntimeError('app.secret_key is not set; session writes will fail')\n","typeGuard":"def app_has_secret_key(app) -> bool:\n    return bool(getattr(app, 'secret_key', None))\n","tryCatchPattern":"try:\n    session['k'] = value\nexcept RuntimeError as e:\n    if 'session is unavailable' in str(e).lower():\n        # set secret_key before serving; do not ignore\n        raise","preventionTips":["Set SECRET_KEY at app construction, sourced from env or a secret store.","Fail fast at startup if SECRET_KEY is missing.","In tests, always assign app.secret_key in the factory."],"tags":["flask","session","secret-key","security","configuration"],"backgroundTag":null,"analyzedSha":"3596b1ab61cea85edb8970e83ff61daa073facf8","analyzedAt":"2026-08-11T20:11:52.622Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}