DEV Community

Linh Fish Dev
Linh Fish Dev

Posted on Originally published at linhfish.dev

FastAPI: Store Login Sessions with SessionMiddleware in 5 Minutes

Starlette’s SessionMiddleware stores login state in a signed browser cookie: after a successful login, the server only needs to read request.session to know who the user is — no database or Redis required. Attach the middleware once for the whole app, set secret_key from an environment variable, and use it for small apps, internal admin panels, or prototypes.

The Problem

Many FastAPI apps start by storing the logged-in user in a module-level global variable. That works on a dev machine but breaks as soon as the app runs for real: a global only remembers one user — the next login overwrites the previous one; restarting the server wipes all sessions; and with multiple workers, each worker holds a different copy, so the same cookie sometimes logs you in and sometimes kicks you out.

For example:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

current_user = None  # remembers only 1 user, gone on restart
USERS = {"linh": "mat-khau-123"}

@app.post("/login")
async def login(data: dict):
    global current_user
    if USERS.get(data.get("username")) == data["password"]:
        current_user = data["username"]
        return {"message": "Dang nhap thanh cong"}
    return JSONResponse({"detail": "Sai tai khoan hoac mat khau"}, status_code=401)

@app.get("/me")
async def me():
    if not current_user:
        return JSONResponse({"detail": "Chua dang nhap"}, status_code=401)
    return {"user": current_user}
Enter fullscreen mode Exit fullscreen mode

The Solution

SessionMiddleware solves this by pushing session state down into the browser’s own cookie. The cookie is signed with secret_key, so the client cannot tamper with its contents — change a single character and the signature no longer matches, and the server treats the request as not logged in. Attach the middleware once, and every endpoint after that can read request.session like a normal dict.

import os
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(
    SessionMiddleware,
    secret_key=os.environ.get("SECRET_KEY", "dev-only-change-me"),
    max_age=60 * 60 * 24,  # 1 ngay
    same_site="lax",
    https_only=False,  # production dat True
)
Enter fullscreen mode Exit fullscreen mode

The three endpoints for login, session check, and logout are only a few lines each:

USERS = {"linh": "mat-khau-123"}

@app.post("/login")
async def login(data: dict, request: Request):
    if USERS.get(data.get("username")) != data.get("password"):
        return JSONResponse({"detail": "Sai tai khoan hoac mat khau"}, status_code=401)
    request.session["user"] = data["username"]
    return {"message": "Dang nhap thanh cong"}

@app.get("/me")
async def me(request: Request):
    user = request.session.get("user")
    if not user:
        return JSONResponse({"detail": "Chua dang nhap"}, status_code=401)
    return {"user": user}

@app.post("/logout")
async def logout(request: Request):
    request.session.clear()
    return {"message": "Da dang xuat"}
Enter fullscreen mode Exit fullscreen mode

The key point: request.session is a dict — assign request.session[“user”] in the login endpoint, read request.session.get(“user”) in the endpoints you want to protect, and call request.session.clear() on logout. max_age sets the cookie’s lifetime (one day here); same_site=”lax” stops the cookie from being sent along from other sites; https_only=True should only be enabled once the app runs over HTTPS — turning it on early on a dev machine stops the cookie from being sent and makes the session mysteriously “disappear”.

Apply It to Your Project

This approach fits best for internal admin panels, small dashboards, or prototypes that need a quick login without setting up Redis or a session table in the database. When you ship to production, take SECRET_KEY from an environment variable and generate it with secrets.token_hex(32) — never hardcode a short string like the one in the example above. If you later need to log a user out of all devices, or store more than the cookie’s roughly 4KB limit, switch to server-side sessions (for example Redis) and keep only the session id in the cookie.

Related Posts

Frequently Asked Questions

How is SessionMiddleware different from setting a cookie yourself with Response.set_cookie?

set_cookie only writes a raw value to the browser — the client can edit it freely and the server cannot tell. SessionMiddleware signs the whole cookie content with secret_key, so any tampering is detected, and it provides a ready-made dict API through request.session.

Can a session cookie store a password or a sensitive token?

You should not. The cookie is only signed, not encrypted — anyone holding the cookie can still read its contents. Store only a user id or username; keep passwords and sensitive tokens on the server.

How much data can a cookie session hold?

About 4KB — the browser’s general cookie limit. Go over it and the browser refuses to store the cookie, silently breaking the session. So store only a few small fields like a user id, and keep large data in the database or Redis.

How do I log a user out of every device they are logged in on?

With cookie sessions, you cannot — the server keeps no list of sessions, so there is nothing to revoke; the only option is to change secret_key, which logs out absolutely everyone. To revoke individual sessions, use server-side sessions.

💬 Have you tried this in your own project? If you hit an error or have a shorter way to do it, leave a comment below — I read them all and will add the best ideas to the post.

Sources

Top comments (0)