{"id":6253,"library":"starsessions","title":"Advanced sessions for Starlette and FastAPI frameworks","description":"Starsessions provides advanced session management for Starlette and FastAPI applications. It is currently at version 2.2.1 and maintains an active release cadence with regular updates and patches, ensuring compatibility and introducing new features.","status":"active","version":"2.2.1","language":"en","source_language":"en","source_url":"https://github.com/alex-oleshkevich/starsessions","tags":["starlette","fastapi","sessions","middleware","authentication","redis","cookie","async"],"install":[{"cmd":"pip install starsessions","lang":"bash","label":"Base installation"},{"cmd":"pip install starsessions[redis]","lang":"bash","label":"With Redis store support"},{"cmd":"pip install starsessions[cryptography]","lang":"bash","label":"With Fernet encryption support"}],"dependencies":[{"reason":"Core ASGI framework integration.","package":"starlette","optional":false},{"reason":"Used for signing session data, especially with CookieStore.","package":"itsdangerous","optional":false},{"reason":"Required for RedisStore functionality. Install with `starsessions[redis]`.","package":"redis","optional":true},{"reason":"Required for encryption, e.g., using FernetEncryptor with CookieStore. Install with `starsessions[cryptography]`.","package":"cryptography","optional":true}],"imports":[{"symbol":"SessionMiddleware","correct":"from starsessions import SessionMiddleware"},{"symbol":"CookieStore","correct":"from starsessions import CookieStore"},{"symbol":"InMemoryStore","correct":"from starsessions import InMemoryStore"},{"symbol":"load_session","correct":"from starsessions import load_session"},{"note":"RedisStore is located in a submodule and requires `starsessions[redis]` to be installed.","wrong":"from starsessions import RedisStore","symbol":"RedisStore","correct":"from starsessions.stores.redis import RedisStore"},{"note":"FernetEncryptor is located in a submodule and requires `starsessions[cryptography]` to be installed.","wrong":"from starsessions import FernetEncryptor","symbol":"FernetEncryptor","correct":"from starsessions.encryptors import FernetEncryptor"}],"quickstart":{"code":"import os\nimport uvicorn\nfrom starlette.applications import Starlette\nfrom starlette.middleware import Middleware\nfrom starlette.responses import JSONResponse\nfrom starlette.routing import Route\nfrom starsessions import SessionMiddleware, CookieStore, load_session\n\n# It's crucial to use a strong, randomly generated secret key in production.\n# For local development, you might use a placeholder, but fetch from env vars.\nSECRET_KEY = os.environ.get(\"SESSION_SECRET_KEY\", \"a-very-secret-key-that-you-should-change\")\n\nsession_store = CookieStore(secret_key=SECRET_KEY)\n\nasync def homepage(request):\n    await load_session(request)\n    if \"counter\" not in request.session:\n        request.session[\"counter\"] = 0\n    request.session[\"counter\"] += 1\n    return JSONResponse({\"message\": \"Session accessed!\", \"counter\": request.session[\"counter\"]})\n\nroutes = [\n    Route(\"/\", homepage),\n]\n\nmiddleware = [\n    Middleware(SessionMiddleware, store=session_store, lifetime=3600 * 24 * 7, cookie_https_only=False)\n]\n\napp = Starlette(routes=routes, middleware=middleware)\n\n# To run this example:\n# 1. Save as e.g., `app.py`\n# 2. `pip install starlette uvicorn starsessions`\n# 3. `uvicorn app:app --reload`\n# 4. Access at http://127.0.0.1:8000/","lang":"python","description":"This quickstart demonstrates setting up a basic Starlette application with `starsessions` using the `CookieStore`. It includes `SessionMiddleware` to enable session support and `load_session` to access session data within a view. A `SECRET_KEY` is mandatory for signing session cookies. For local testing, `cookie_https_only` is set to `False` for convenience, but it should be `True` in production for security."},"warnings":[{"fix":"Update your code to use `*Store` classes instead of `*Backend` classes, remove direct `Session` class usage, and review method signatures and middleware argument names against the v2.0.0+ documentation.","message":"Version 2.0.0 introduced significant breaking changes, most notably renaming session 'Backends' to 'Stores' (e.g., `CookieBackend` became `CookieStore`, `RedisBackend` became `RedisStore`). The `Session` class was also removed, and method signatures (like `Store.write`) were altered. Middleware argument names were also changed.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your project is running on Python 3.8 or newer to use `starsessions` v2.0.0 and above.","message":"Python 3.6 support was dropped in `starsessions` v2.0.0.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Add `await load_session(request)` at the beginning of any view or middleware that needs to interact with the session, or configure `SessionAutoloadMiddleware` in your application's middleware stack.","message":"By default, `starsessions` does not autoload session data for performance reasons. You must explicitly call `await load_session(request)` in your endpoint or middleware before accessing `request.session`, or use `SessionAutoloadMiddleware`. Failure to do so will result in an empty session or `SessionNotLoaded` errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Import `FernetEncryptor` from `starsessions.encryptors` and pass an instance to `SessionMiddleware` via the `encryptor` argument, ensuring `starsessions[cryptography]` is installed.","message":"When using `CookieStore`, session data is signed to prevent tampering but is NOT encrypted by default. This means sensitive information stored in the session cookie can be read by the client. For confidentiality, you must provide an `Encryptor` (e.g., `FernetEncryptor`) to the `SessionMiddleware`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Implement an ASGI lifespan handler to properly initialize and `aclose()` your `redis.asyncio.Redis` client when your application starts and stops.","message":"When using `RedisStore`, you must explicitly close the Redis connection when the application shuts down. The library does not handle this automatically. The recommended approach is to use a lifespan handler in your ASGI application.","severity":"gotcha","affected_versions":"All versions using RedisStore"},{"fix":"Ensure `SessionMiddleware` is placed appropriately in your middleware stack, typically before any middleware or route handlers that need to access or modify the session.","message":"The order of middleware in Starlette/FastAPI applications is crucial. If `SessionMiddleware` or `SessionAutoloadMiddleware` is placed incorrectly relative to other middlewares that modify the request or response, unexpected behavior or session issues may arise.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For development, you might set `cookie_https_only=False` and `cookie_same_site='lax'`. For cross-domain production deployments, carefully configure `cookie_same_site='none'` along with `cookie_https_only=True` and ensure your frontend handles `withCredentials`.","message":"Default cookie security settings (`cookie_https_only=True`, `cookie_same_site='strict'`) can cause issues in cross-domain or HTTP development environments. While secure by default, these might prevent cookies from being set or sent by the browser in certain scenarios.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z","problems":[]}