Question Details

No question body available.

Tags

python cookies fastapi

Answers (2)

Accepted Answer Available
Accepted Answer
January 8, 2026 Score: 2 Rep: 294 Quality: High Completeness: 60%

FastAPI just isn’t wiring your dependency the way you think it is.

In WebSocket routes, the usual Cookie(...), Header(...), etc. parameter injection that you get on normal HTTP endpoints doesn’t run, so this:

async def getcookie(session: Annotated[str | None, Cookie()] = None):

never gets a value from the incoming WebSocket request, and session stays None even though the browser is actually sending the cookie.​

The cookie you see under websocket.cookies is parsed by Starlette directly on the WebSocket, not passed through FastAPI’s dependency system. To make it work, you need to grab the cookie from the WebSocket object itself inside the dependency:

from fastapi import Depends, FastAPI, WebSocket, WebSocketException, status

app = FastAPI()

async def getcookie(websocket: WebSocket): sid = websocket.cookies.get("SID") print("SID in dependency:", sid) if sid is None: raise WebSocketException(code=status.WS1008POLICYVIOLATION) return sid

@app.websocket("/ws") async def websocketendpoint( websocket: WebSocket, sid: str = Depends(get_cookie), ): print("All cookies:", websocket.cookies) print("SID from dependency:", sid) await websocket.accept() ...

In short: Cookie() works for HTTP routes, not for WebSocket routes, so read cookies from websocket.cookies (optionally via a dependency that takes websocket: WebSocket) instead.

January 8, 2026 Score: 2 Rep: 96 Quality: Low Completeness: 60%

You’re using Cookie() as if FastAPI can automatically extract cookies from a WebSocket.
please check your code:

async def getcookie(
    websocket: WebSocket,
    session: Annotated[str | None, Cookie()] = None,
):
    print(session)
    return session

Cookie() works for HTTP requests, not WebSocket connections.

When you use Depends(getcookie) in a WebSocket endpoint, FastAPI tries to resolve the dependency like it would for an HTTP request — but WebSockets do not have the same request lifecycle, so Cookie() doesn’t populate.

That’s why session is always None.

I think you need to read cookies directly from websocket.cookies, not via Cookie()
ex:

from fastapi import FastAPI, WebSocket, WebSocketException, status
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.addmiddleware( CORSMiddleware, allowcredentials=True, alloworigins=[ "http://localhost", "http://localhost:80", ], allowmethods=[""], allow_headers=[""], )

@app.websocket("/ws") async def websocketendpoint(websocket: WebSocket): await websocket.accept()

# Access the cookie directly sidcookie = websocket.cookies.get("SID") print("SID cookie:", sidcookie)

if sidcookie is None: # Example: reject the connection await websocket.close(code=status.WS1008POLICYVIOLATION) return

# Continue handling WebSocket try: await websocket.sendtext(f"Your session ID is: {sidcookie}") except Exception: await websocket.close(code=400)

If you need to mimic Depends behavior, just make a helper function:

def get
sid_cookie(websocket: WebSocket): return websocket.cookies.get("SID")