Overview
Cookies are small pieces of data stored on the client side that are sent with every request to your server. FastAPI makes it easy to set and manage cookies in your responses.Setting Cookies
To set cookies, return aResponse object and use the set_cookie() method:
You need to return a
Response object (or a subclass like JSONResponse) to set cookies. Returning a plain dict or Pydantic model won’t allow cookie manipulation.Cookie Parameters
Theset_cookie() method accepts several parameters to configure cookie behavior:
Cookie Parameters Explained
key: The cookie namevalue: The cookie valuemax_age: Cookie lifetime in secondsexpires: Expiration date (datetime object or seconds since epoch)path: URL path where cookie is valid (default:"/")domain: Domain where cookie is validsecure: IfTrue, cookie only sent over HTTPShttponly: IfTrue, cookie not accessible via JavaScript (security feature)samesite: CSRF protection ("lax","strict", or"none")
Secure Cookies for Authentication
For session cookies and authentication, use secure settings:Multiple Cookies
Set multiple cookies in a single response:Using Response Parameter
Inject aResponse parameter to set cookies while returning your data normally:
This approach is cleaner when you want to leverage FastAPI’s automatic response serialization while still setting cookies.
Deleting Cookies
Delete a cookie by setting it with an expired date:set_cookie() with max_age=0:
Reading Cookies
Read cookies from incoming requests:Cookie Expiration
Using max_age
Using expires
SameSite Cookie Attribute
Protect against CSRF attacks with thesamesite attribute:
samesite="strict": Cookie never sent on cross-site requestssamesite="lax": Cookie sent on top-level navigation (e.g., clicking a link)samesite="none": Cookie sent on all requests (requiressecure=True)
Best Practices
- Security first: Always use
httponly=Trueandsecure=Truefor sensitive cookies - Set expiration: Use
max_ageto control cookie lifetime - Use SameSite: Set
samesite="lax"or"strict"for CSRF protection - Path and domain: Restrict cookies to specific paths and domains when appropriate
- Don’t store sensitive data: Cookies are stored on the client and can be viewed
- Sign cookies: Consider signing cookie values to prevent tampering
- HTTPS in production: Always use HTTPS in production when setting
secure=True