Streamlit Persist Session
A Python library/utility designed for Persistent data across page reloads in Streamlit applications using cryptographically signed browser cookies and AES-encrypted local state files.
Demo
A live demo application is available at: https://persist-session.streamlit.app/
Purpose
The primary goal of streamlit-persist-session is to provide Persistent data across page reloads.
By default, Streamlit's built-in st.session_state resets whenever a user refreshes/reloads their browser tab or when the WebSocket connection is interrupted. This component bypasses that limitation by automatically preserving decorated class instances on the server side, indexing them via a unique session ID stored securely in the client's browser cookies.
Features
- Automatic Persistence: A simple class decorator (
@streamlit_persist_session.persist) wraps your state class, intercepting attribute reads/writes to keep the state synchronized. - Secure by Design:
- AES Encryption: State files are encrypted using authenticated cryptography (
Fernet) before being written to disk, preventing cleartext exposure of sensitive data in temporary directories (mitigating CWE-312 / CWE-922). - Strict Permissions: Files are created with
0600permissions (owner read/write only) to protect against unauthorized local access in shared server environments. - HMAC Cookie Signing: Signs session tokens using HMAC-SHA256 with a unique server-side secret key to prevent client-side tampering.
- Path Traversal Protection: Strict input validation of session IDs (UUIDv4).
- Configurable TTL & Expiration: Session state and browser cookies can expire automatically based on a configurable time-to-live (
ttl, default: 24 hours). - Memory-Only Attributes: Sensitive credentials or tokens can be kept in-memory (
st.session_state) only, omitting them from disk storage viaexclude_fieldsor the_ephemeral_prefix.
- AES Encryption: State files are encrypted using authenticated cryptography (
- Session Lifecycles: Supports explicit state clearing via
state.clear_cookie_state().
Key Architecture
streamlit-persist-session wraps streamlit_cookies_controller to implement:
- Cookie Key Allocation & HMAC Verification: Allocates a unique identifier to browser cookies and validates authenticity with an HMAC signature.
- Encrypted Storage & Restoration: Automatically serializes and encrypts Python objects to local server files on attribute mutation, restoring and decrypting state seamlessly upon page reload.
Integration with Authentication
Usage Examples
Basic Usage (100% Backward-Compatible)
By default, encryption, strict file permissions, and 24-hour TTL are applied automatically without any extra configuration:
import streamlit_persist_session
# Decorated class must be pickleable at the module level.
@streamlit_persist_session.persist("app-state")
class AppState:
def __init__(self):
self.count = 0
Advanced Security Configuration
You can customize secret keys, set expiration times, and exclude sensitive credentials from being stored on disk:
import streamlit_persist_session
@streamlit_persist_session.persist(
"secure-user-state",
# Session TTL in seconds (e.g. 1 hour; default is 86400 seconds = 24 hours)
ttl=3600,
# Exclude sensitive attributes from disk storage (stored only in-memory in st.session_state)
exclude_fields=["api_token", "oauth_session"],
# Optional custom encryption key (otherwise resolved from st.secrets or environment variable)
secret_key="my-app-secret-passphrase",
)
class SecureAppState:
def __init__(self):
self.count = 0
self.api_token = "secret_access_token" # Excluded from disk file
self._ephemeral_cache = {} # _ephemeral_* is also excluded from disk file
Secret Key Resolution Priority
When no secret_key is passed directly to the decorator, the key is resolved in the following order:
st.secrets["STREAMLIT_PERSIST_SECRET_KEY"]orst.secrets["persist_secret_key"]- Environment variable:
STREAMLIT_PERSIST_SECRET_KEY - Auto-generated 32-byte key stored securely with
0600permissions on the server.
Directory Structure
- src/streamlit_persist_session/: Core package containing the decorator logic.
- init.py: Package entry point exposing the decorator.
- _persister.py: Internal implementation of state persistence and encryption.
- main.py: A demo Streamlit application demonstrating state persistence.
- tests/: Unit and security regression test suites.
- pyproject.toml: Project metadata, package definition, and dependencies.
- README.md: This documentation.
Prerequisites
Ensure you have the following installed:
- Python 3.13 or higher
- uv (recommended Python package and workflow manager)
- mise (optional, runtime management tool)
Getting Started
1. Installation & Dependency Setup
Initialize and synchronize the virtual environment with the necessary dependencies:
uv sync
2. Run the Demo Application
Launch the interactive Streamlit dashboard:
uv run streamlit run main.py
If the browser does not open automatically, visit the URL output in your terminal (usually http://localhost:8501).
Alternatively, you can try the hosted version at https://persist-session.streamlit.app/.
How It Works
- Instantiation & Placeholder: When the app first loads, the decorator checks whether the session cookie exists. If cookies are not yet loaded, a temporary placeholder instance is returned while the cookie controller retrieves data.
- State Serialization & Encryption:
- Every modification to persisted state attributes triggers serialization and AES encryption (
Fernet). - The encrypted payload includes expiration timestamps (
expires_at) and metadata. - The file is saved to the server's temporary directory with restricted
0600permissions, using a random UUIDv4 as the filename. - A signed token (
<UUID>.<HMAC-SHA256>) is set in the client's browser cookies with matching expiration headers.
- Every modification to persisted state attributes triggers serialization and AES encryption (
- Restoration & Verification: On page reload or session reconnection, the cookie is read, HMAC signature is verified, the file payload is decrypted, and TTL expiration is checked. If verified, the original state object is restored.
- Invalidation & Clean up: If a session has expired, the HMAC verification fails, or the
clear_cookie_state()method is invoked, the temporary file is deleted, browser cookies are removed, andst.session_stateis updated.
License
This project is licensed under the MIT License. See the LICENSE file for the full license text.
Metadata
Release files for streamlit-persist-session 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| streamlit_persist_session-0.2.0.tar.gz | 15.0 kB | Without provenance | Details for streamlit_persist_session-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| streamlit_persist_session-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for streamlit_persist_session-0.2.0-py3-none-any.whl |
Total release size: 25.8 kB
Release files / streamlit_persist_session-0.2.0.tar.gz
| Download URL | streamlit_persist_session-0.2.0.tar.gz |
|---|---|
| Size | 15.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2e68f90352d4b448f0175df67e64aa4cf2c3bad91106dc7369ad4c3faf382529
|
|
BLAKE2b-256 checksum How to use checksums |
26bb47375d3481a72663bf9338434e010a5d7c9a3da21959b97b1cf9686b53c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / streamlit_persist_session-0.2.0-py3-none-any.whl
| Download URL | streamlit_persist_session-0.2.0-py3-none-any.whl |
|---|---|
| Size | 10.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
20879fa4cd58d76de6fa362d4dc74267ae2b49561f030d6c13967678e5b11386
|
|
BLAKE2b-256 checksum How to use checksums |
6710ebb54439f735a09b4f9131cd766d8d18a1339dc0e4cbc0115b160652580e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for streamlit-persist-session 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.