Session Management
Relevant source files
The following files were used as context for generating this wiki page:
Session management in Starlette provides a mechanism for persisting user data across multiple HTTP requests or WebSocket connections. It is primarily implemented via a signed cookie-based system, ensuring that session data is stored client-side while remaining tamper-proof through cryptographic signing.
The system relies on SessionMiddleware to intercept incoming requests, decode session data from cookies, and inject a session object into the request scope. Upon completion of the request, the middleware detects changes to the session and updates the client's cookie accordingly. This implementation requires the itsdangerous library for secure signing.
Sources: starlette/middleware/sessions.py, README.md:104-104
Architecture and Core Components
The session management system consists of two primary classes: SessionMiddleware, which handles the ASGI lifecycle and cookie I/O, and Session, a specialized dictionary that tracks its own state.
SessionMiddleware
This middleware is responsible for the transition between the raw cookie string and the structured session data. It uses itsdangerous.TimestampSigner to sign and verify session cookies. When a request arrives, the middleware checks for the presence of a configured session cookie. If found, it attempts to unsign and decode the JSON payload. If the signature is invalid or the cookie is missing, an empty session is initialized.
Sources: starlette/middleware/sessions.py:16-56
The Session Object
The Session class extends a standard Python dict. It introduces two internal flags: accessed and modified. These flags allow the middleware to determine if a Vary: Cookie header should be added or if a Set-Cookie header is necessary to persist changes.
Sources: starlette/middleware/sessions.py:82-126
| Component | Description |
|---|---|
SessionMiddleware | ASGI middleware that manages the serialization/deserialization of cookies. |
Session | A dictionary-like object stored in scope["session"] that tracks modifications. |
itsdangerous.TimestampSigner | Cryptographic tool used to sign the session data with a secret key. |
Sources: starlette/middleware/sessions.py:28, starlette/middleware/sessions.py:82
Data Flow and Lifecycle
The following diagram illustrates the lifecycle of a session during a standard HTTP request/response cycle.
The diagram shows how SessionMiddleware wraps the application to handle cookie processing before and after the application logic executes.
Sources: starlette/middleware/sessions.py:39-78
Configuration Options
SessionMiddleware supports various configuration parameters to control the security and behavior of the session cookies.
| Parameter | Type | Default | Description |
|---|---|---|---|
secret_key | str | Secret | Required | The key used for cryptographic signing. |
session_cookie | str | "session" | The name of the cookie used to store the session. |
max_age | int | None | 1209600 (14 days) | Time in seconds until the cookie expires. |
path | str | "/" | The cookie path scope. |
same_site | str | "lax" | SameSite cookie attribute (lax, strict, or none). |
https_only | bool | False | If True, the secure flag is added to the cookie. |
domain | str | None | None | The domain attribute for the cookie. |
Sources: starlette/middleware/sessions.py:17-36
Modification Tracking Logic
The Session object overrides standard dictionary methods to ensure the modified flag is set correctly. This ensures that Starlette only sends a Set-Cookie header when data has actually changed, improving performance and cacheability.
mark_accessed(): Setsaccessed = True. Triggered by reading data.mark_modified(): Sets bothaccessed = Trueandmodified = True.- Trigger Methods:
__setitem__,__delitem__,clear,pop,setdefault, andupdateall trigger modification tracking.
Sources: starlette/middleware/sessions.py:86-126, tests/middleware/test_session.py:228-258
Middleware Response Handling
When the application starts a response (http.response.start), the middleware performs the following checks:
- Vary Header: If
session.accessedis True, it addsVary: Cookieto the response headers to inform caches that the response depends on the session. - Persistence: If
session.modifiedis True and the session contains data, a new signed cookie is generated using Base64 encoding and theTimestampSigner. - Deletion: If
session.modifiedis True but the session is empty (and was previously not empty), it sends a cookie with an expiration date in the past to delete the session from the browser.
Sources: starlette/middleware/sessions.py:58-78
Integration with Starlette Application
Sessions are typically integrated by adding SessionMiddleware to the middleware stack of a Starlette or Router instance.
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
routes = [...]
middleware = [
Middleware(SessionMiddleware, secret_key="your-secret-key")
]
app = Starlette(routes=routes, middleware=middleware)
Sources: starlette/applications.py:46-52, tests/middleware/test_session.py:35-43
Testing Sessions
The TestClient can be used to verify session behavior by simulating cookie persistence. Because the session is cookie-based, the TestClient (built on httpx) naturally handles the exchange of Set-Cookie and Cookie headers during a test session.
Sources: starlette/testclient.py:440-450, tests/middleware/test_session.py:44-65
Conclusion
Starlette's session management is a lightweight, secure-by-default implementation that leverages signed cookies to avoid server-side state. By using the Session object's modification tracking and the SessionMiddleware's ASGI lifecycle hooks, it provides a seamless experience for developers while maintaining compatibility with HTTP caching and modern security standards like SameSite and Secure flags.