Skip to main content
The SessionMiddleware class provides session management using signed cookies. It allows you to store user-specific data across requests securely.

Parameters

secret_key
str
required
Secret key used to sign session cookies. This should be a long, random string kept secure and never committed to version control.
secret_key="your-secret-key-min-32-characters-long"
Name of the session cookie stored in the browser.
session_cookie="my_app_session"
max_age
int | None
default:"1209600"
Session lifetime in seconds. Default is 1,209,600 seconds (14 days). Set to None for a session cookie that expires when the browser closes.
max_age=3600  # 1 hour
path
str
default:"\"/\""
Cookie path. Restricts the cookie to a specific path on your domain.
path="/api"
same_site
str
default:"\"lax\""
SameSite cookie attribute. Can be "strict", "lax", or "none". Controls whether cookies are sent with cross-site requests.
same_site="strict"
https_only
bool
default:"false"
Whether to set the Secure flag on the cookie, restricting it to HTTPS connections only. Should be True in production.
https_only=True
domain
str | None
default:"None"
Cookie domain. Allows sharing cookies across subdomains when set.
domain=".example.com"

Usage

from fastrapi import FastrAPI
from fastrapi.middleware import SessionMiddleware

app = FastrAPI()

app.add_middleware(
    SessionMiddleware,
    secret_key="super-secret-key-change-this-in-production",
    session_cookie="fastrapi_session",
    max_age=3600,
    https_only=False
)

Examples

Basic session configuration

from fastrapi import FastrAPI
from fastrapi.middleware import SessionMiddleware
from fastrapi.responses import JSONResponse

app = FastrAPI()

app.add_middleware(
    SessionMiddleware,
    secret_key="your-secret-key-min-32-characters-long",
    session_cookie="fastrapi_session",
    max_age=3600,
    https_only=False
)

@app.get("/counter")
def session_counter(request) -> JSONResponse:
    return JSONResponse({"message": "Session cookie should be set"})

Production configuration with HTTPS

app.add_middleware(
    SessionMiddleware,
    secret_key="your-secret-key-min-32-characters-long",
    session_cookie="secure_session",
    max_age=86400,        # 24 hours
    https_only=True,      # Require HTTPS
    same_site="strict",   # Strict SameSite policy
    domain=".example.com" # Share across subdomains
)
app.add_middleware(
    SessionMiddleware,
    secret_key="your-secret-key-min-32-characters-long",
    session_cookie="temp_session",
    max_age=None  # Expires when browser closes
)

Build docs developers (and LLMs) love