🍪 Cookie Manager
Submitted by Lukas Masuch
Summary
Read and write browser cookies from Python using a dict-like interface.
Functions
cookie_manager
Create a cookie manager to read and write browser cookies from Python.
This component provides a dict-like interface for managing browser cookies. The manager must be rendered in your app (it creates a hidden component) and requires a rerun to sync cookies from the browser on first load.
The returned CookieManager implements Python's MutableMapping protocol,
so you can use it like a dictionary:
manager["name"]- get a cookie value (raisesKeyErrorif not found)manager.get("name", "default")- get with a default valuemanager["name"] = "value"- set a cookie (with default options)del manager["name"]- delete a cookie"name" in manager- check if a cookie existslen(manager)- count of cookiesdict(manager)- convert to a regular dictmanager.keys(),manager.values(),manager.items()- iterate
For fine-grained control over cookie attributes (expiration, path, domain,
secure, samesite), use the explicit manager.set() and manager.delete()
methods instead of dict-style assignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A unique key for this component instance. Defaults to "cookie_manager". Use different keys if you need multiple independent cookie managers. |
'cookie_manager'
|
Returns:
| Type | Description |
|---|---|
CookieManager
|
A CookieManager instance that provides dict-like access to cookies. |
Note
- Call
manager.ready()to check if cookies have synced from the browser - Use
st.stop()on first load while waiting for sync - This can only manage JavaScript-accessible cookies (not HttpOnly)
- After setting/deleting cookies, call
st.rerun()to see changes
Example:
```python
manager = cookie_manager()
if not manager.ready():
st.stop() # Wait for browser sync
theme = manager.get("theme", "light")
if st.button("Use dark theme"):
manager["theme"] = "dark"
st.rerun()
```
Example with custom cookie options:
```python
manager = cookie_manager()
if manager.ready():
# Set cookie with 1-hour expiration
manager.set("session", "abc123", max_age=3600, secure=True)
```
Source code in src/streamlit_extras/cookie_manager/__init__.py
Import:
- You should add this to the top of your .py file
Examples
example
def example() -> None:
"""Example usage of the cookie_manager component."""
st.info("This component can only manage JavaScript-accessible cookies. HttpOnly cookies are not supported.")
manager = cookie_manager(key="demo_cookie_manager")
if not manager.ready():
st.info("Syncing cookies from browser. The app will be ready on the next rerun.")
st.stop()
st.subheader("Current cookies")
st.json(dict(manager))
get_col, set_col, delete_col = st.columns(3)
with get_col:
st.markdown("**Get cookie**")
cookie_name = st.text_input("Cookie name", key="cookie_get_name")
if st.button("Read cookie", key="cookie_get_button"):
st.write(manager.get(cookie_name))
with set_col:
st.markdown("**Set cookie**")
set_name = st.text_input("Name", key="cookie_set_name")
set_value = st.text_input("Value", key="cookie_set_value")
set_max_age = st.number_input(
"Max age (seconds)",
min_value=0,
value=86400,
step=60,
key="cookie_set_max_age",
)
set_secure = st.checkbox("Secure", value=False, key="cookie_set_secure")
set_samesite = st.selectbox(
"SameSite",
["lax", "strict", "none"],
index=0,
key="cookie_set_samesite",
)
if st.button("Write cookie", key="cookie_set_button"):
selected_samesite = cast(
"Literal['strict', 'lax', 'none']",
"lax" if set_samesite is None else set_samesite,
)
manager.set(
set_name,
set_value,
max_age=int(set_max_age),
secure=set_secure,
samesite=selected_samesite,
)
st.rerun()
with delete_col:
st.markdown("**Delete cookie**")
delete_name = st.text_input("Cookie to delete", key="cookie_delete_name")
if st.button("Delete cookie", key="cookie_delete_button"):
manager.delete(delete_name)
st.rerun()
st.subheader("Basic usage")
st.code(
"""
manager = cookie_manager()
if not manager.ready():
st.stop() # Wait for browser sync
# Dict-like access
theme = manager.get("theme", "light")
st.write(f"Current theme: {theme}")
if st.button("Use dark theme"):
manager["theme"] = "dark"
st.rerun()
# Or use set() for more control
manager.set("session_id", "abc123", max_age=3600, secure=True)
""".strip(),
language="python",
)