Ankaj Gupta
August 13, 2024

AssertionError: SessionMiddleware Must Be Installed

Fixing the "AssertionError: SessionMiddleware Must Be Installed" in FastAPI

This error occurs when accessing request.session in custom middleware before the SessionMiddleware has been properly applied.

Understanding the Issue

The error indicates that the SessionMiddleware is either not installed correctly or is being accessed too late in the middleware stack. Ensure that SessionMiddleware is added before any custom middleware that relies on session data.

Key Point: The order of middleware matters in FastAPI. Session middleware must be added in the correct sequence.

Error Example Code

Here's a FastAPI application demonstrating the incorrect setup:

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()

# Add SessionMiddleware first (INCORRECT)
app.add_middleware(SessionMiddleware, secret_key="some-random-string")

@app.middleware("http")
async def testing_session(request: Request, call_next):
    if 'session' in request.scope:
        session = request.session
        test_value = session.get("test", None)
        if test_value:
            print(f"Middleware session value: {test_value}")
        else:
            print("No session value found.")
    else:
        print("Session middleware is not applied correctly.")

    response = await call_next(request)
    return response

@app.get("/test-session")
async def test_session(request: Request):
    request.session['test'] = 'value'
    return {"session": dict(request.session)}

Correct Solution

Fix: Move app.add_middleware(SessionMiddleware, secret_key="some-random-string") to the last line. This resolves the session middleware issue.

Here's the corrected FastAPI application:

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()

@app.middleware("http")
async def testing_session(request: Request, call_next):
    if 'session' in request.scope:
        session = request.session
        test_value = session.get("test", None)
        if test_value:
            print(f"Middleware session value: {test_value}")
        else:
            print("No session value found.")
    else:
        print("Session middleware is not applied correctly.")

    response = await call_next(request)
    return response

# Add SessionMiddleware LAST (CORRECT)
app.add_middleware(SessionMiddleware, secret_key="some-random-string")

@app.get("/test-session")
async def test_session(request: Request):
    request.session['test'] = 'value'
    return {"session": dict(request.session)}

Key Points

  1. Order Matters

    Ensure that SessionMiddleware is added after your custom middleware. This allows the session to be properly initialized and accessible.

  2. Check Middleware Setup

    In your custom middleware, check if request.session is available. If not, it might indicate that SessionMiddleware is not correctly applied.

  3. Testing

    Use endpoints like /test-session to set and retrieve session values, confirming that session management is working as expected.

Related Posts