Parse user cookies in Streamlit

In this article we will see how to parse cookies of users that are using your streamlit app.

If you have backend for your app for example in Flask, it is easy to see the cookies that come with the user request. In streamlit you will need to use additional library called streamlit-cookies-manager, installed via pip.

Usage is straightforward, use empty string prefix to see all cookies for your domain. Alternatively specify some app related 'prefix' as a string so the cookie parser will automatically filter out only the cookies starting with such unique prefix.

coil@coil-VM:~/Desktop/streamlit$ python3 -m venv streamlit_env
coil@coil-VM:~/Desktop/streamlit$ source streamlit_env/bin/activate
(streamlit_env) coil@coil-VM:~/Desktop/streamlit$ pip3 install streamlit
(streamlit_env) coil@coil-VM:~/Desktop/streamlit$ pip install streamlit-cookies-manager
cat app.py
import os
import streamlit as st
from streamlit_cookies_manager import EncryptedCookieManager

# This should be on top of your script
cookies = EncryptedCookieManager(
    # This prefix will get added to all your cookie names.
    # This way you can run your app on Streamlit Cloud without cookie name clashes with other apps.
    prefix="localhost/",
    #prefix="",   # no prefix will show all your cookies for this domain
    # You should setup COOKIES_PASSWORD secret if you're running on Streamlit Cloud.
    #password=os.environ.get("COOKIES_PASSWORD", "My secret password"),
    password='changeme'
)

if not cookies.ready():
    # Wait for the component to load and send us current cookies.
    st.stop()

st.write("Current cookies:", cookies)
name = st.text_input("New name for a cookie (key)")
value = st.text_input("New value for a cookie (value)")
if st.button("Change the cookie, will save on next rerun"):
    cookies[name] = value  # This will get saved on next rerun
    if st.button("Force saving cookies now, without rerun"):
        cookies.save()  # Force saving the cookies now, without a rerun
streamlit run app.py

When I want to see all cookies for my (streamlit) website, here localhost, in firefox we can use Storage Inspector by pressing Shift + F9 (more at https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector)

Source: