Skip to main content

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 a Response 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.
The set_cookie() method accepts several parameters to configure cookie behavior:
  • key: The cookie name
  • value: The cookie value
  • max_age: Cookie lifetime in seconds
  • expires: Expiration date (datetime object or seconds since epoch)
  • path: URL path where cookie is valid (default: "/")
  • domain: Domain where cookie is valid
  • secure: If True, cookie only sent over HTTPS
  • httponly: If True, cookie not accessible via JavaScript (security feature)
  • samesite: CSRF protection ("lax", "strict", or "none")
When setting samesite="none", you must also set secure=True. This is required by modern browsers.

Secure Cookies for Authentication

For session cookies and authentication, use secure settings:
Always use httponly=True for session cookies to prevent XSS attacks, and secure=True in production to ensure cookies are only sent over HTTPS.

Multiple Cookies

Set multiple cookies in a single response:

Using Response Parameter

Inject a Response 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:
Or use set_cookie() with max_age=0:

Reading Cookies

Read cookies from incoming requests:
See the Cookie Parameters tutorial for more details on reading cookies.

Using max_age

Using expires

Protect against CSRF attacks with the samesite attribute:
  • samesite="strict": Cookie never sent on cross-site requests
  • samesite="lax": Cookie sent on top-level navigation (e.g., clicking a link)
  • samesite="none": Cookie sent on all requests (requires secure=True)

Best Practices

  1. Security first: Always use httponly=True and secure=True for sensitive cookies
  2. Set expiration: Use max_age to control cookie lifetime
  3. Use SameSite: Set samesite="lax" or "strict" for CSRF protection
  4. Path and domain: Restrict cookies to specific paths and domains when appropriate
  5. Don’t store sensitive data: Cookies are stored on the client and can be viewed
  6. Sign cookies: Consider signing cookie values to prevent tampering
  7. HTTPS in production: Always use HTTPS in production when setting secure=True