How to Set a SameSite Cookie in Python

Set a SameSite cookie attribute in Python using the standard library's SimpleCookie class.

Easy Python 3.8+ Aug 9, 2026 Auth & security at scale 12 views 0 copies

Python code

12 lines
Python 3.8+
from http.cookies import SimpleCookie

def set_same_site_cookie(name, value, same_site="Lax"):
    cookie = SimpleCookie()
    cookie[name] = value
    cookie[name]["path"] = "/"
    cookie[name]["samesite"] = same_site
    return cookie[name].OutputString()

if __name__ == "__main__":
    print(set_same_site_cookie("session_id", "abc123", "Strict"))
    print(set_same_site_cookie("prefs", "dark_mode"))

Output

stdout
session_id=abc123; Path=/; SameSite=Strict
prefs=dark_mode; Path=/; SameSite=Lax

How it works

The SimpleCookie class from the http.cookies module provides a convenient way to construct HTTP cookie headers. Setting the samesite attribute ensures the cookie is only sent on same-site requests, which helps mitigate CSRF attacks. The OutputString() method returns the cookie in RFC 6265 format. Using the standard library avoids external dependencies and keeps the code portable. This is a building block for secure session handling in web applications.

Common mistakes

  • Forgetting to set the `path` attribute, which can cause the cookie to be sent on unexpected paths.
  • Using case-sensitive attribute names incorrectly (e.g., `SameSite` instead of `samesite`).
  • Not validating the `same_site` value, allowing invalid values like 'None' or ' '.

Variations

  1. Use `SimpleCookie` to set multiple cookies at once, each with its own attributes.
  2. Set the `secure` and `httponly` flags in addition to `samesite` for enhanced security.

Real-world use cases

  • Setting session cookies in web frameworks like Django or Flask by generating the Set-Cookie header manually.
  • Configuring authentication cookies in API gateways to enforce CSRF protection across microservices.
  • Implementing cookie-based consent banners where SameSite helps track user preferences safely.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Auth & security at scale

Related tutorials and quizzes for this topic.