Streamlit cookies - Which package to use? So many of them?

  1. I just installed “extra_streamlit_components” package to read cookies and then decide whether the page view is authorized or not.

    While it works…, there are some fleeting moments when the package does not return any cookies and so I end up displaying a “Access denied” message followed by an st.stop(). However, after a few seconds, the page automatically loads again and completes successfully.

    This had led to weird error messages and my users are literally laughing at me (Can’t this guy get accesses right?)

    One of the kind souls (lorentz) had suggested that a “time.sleep()” following the “get_all” method helps. And it did help indeed. For my case, a time.sleep(2) helped (1 did not help my case).

    So, Can someone guide me on whats the right way to do this?

  2. There is another package called “extra_streamlit_components_better_cookie_manager” whose development has stopped in Dec 2022.
    extra-streamlit-components-better-cookie-manager · PyPI
    Is this any better? Any suggestions?

  3. There is another “streamlit-cookie-manager” package streamlit-cookies-manager · PyPI
    This one is not actively developed. (Dec 2021 last release)
    But any inputs most welcome

  4. I think my app loading time has severely increased after this. I am yet to measure but I can visually see the difference. Is this to be expected?

1 Like

Hi @Sarnath_K

To help in making a decision which of the available Streamlit component for managing cookies, you can use a profiler to see how fast/slow each specific steps are taking.

Here are the links to streamlit-profiler:

1 Like

OKay, right now, I am using this Hack. That works well with the latest version of Streamlit (1.26?)

def get_all_cookies():
    WARNING: This uses unsupported feature of Streamlit
    Returns the cookies as a dictionary of kv pairs
    from streamlit.web.server.websocket_headers import _get_websocket_headers 
    from urllib.parse import unquote

    headers = _get_websocket_headers()
    if headers is None:
        return {}
    if 'Cookie' not in headers:
        return {}
    cookie_string = headers['Cookie']
    # A sample cookie string: "K1=V1; K2=V2; K3=V3"
    cookie_kv_pairs = cookie_string.split(';')

    cookie_dict = {}
    for kv in cookie_kv_pairs:
        k_and_v = kv.split('=')
        k = k_and_v[0].strip()
        v = k_and_v[1].strip()
        cookie_dict[k] = unquote(v) #e.g. Convert to
    return cookie_dict
1 Like

extra_streamlit_components was updated recently and works well for me.

1 Like