FastAPI Cannot Send Cookies to React Frontend
FastAPI is a popular Python framework for creating APIs. However, some users have reported issues with FastAPI not returning cookies to React frontend applications.
Why doesn't FastAPI return cookies to React frontend apps?
Here is a code snippet illustrating the issue:
@router.post("/login") def user_login(response: Response, username: str = Form(), password: str = Form(), db: Session = Depends(get_db)) -> dict: # Database operations omitted for brevity access_token = create_access_token(data={"sub": user.mobile_number}) response.set_cookie(key="fakesession", value="fake-cookie-session-value") return {"status": "success"}
When sending a login request from Swagger UI, the cookie appears in the response headers. However, from a React app, no cookie is returned.
There are two steps to resolve this issue:
Set Cookies Correctly:
Configure CORS and Credentials:
Cookie Setting:
Cross-Origin Resource Sharing (CORS):
Credentials in Request:
Explicitly specify the allowed origins to prevent unauthorized access to cookies. By default, only certain communication types are allowed in CORS requests without credentials, excluding cookies.
The above is the detailed content of Why Doesn't My FastAPI Backend Send Cookies to My React Frontend?. For more information, please follow other related articles on the PHP Chinese website!