Login session lost on browser refresh in multi-page Streamlit app despite using st.session_state

I’m building a multi-page Streamlit app with custom authentication. User credentials are checked against a database (using a custom db.py module).

Login page code (simplified):
import streamlit as st
import db

if ‘un’ in st.session_state:
st.switch_page(“pages/Dashboard.py”)

username = st.text_input(“Username”).upper()
password = st.text_input(“Password”, type=“password”)

if st.button(“Login”):
row = db.check_user_credentials(username, password)
if row:
st.session_state.un = row[0]
st.switch_page(“pages/Dashboard.py”)
else:
st.error(“Invalid credentials”)

Dashboard page (and other protected pages):slight_smile:
import streamlit as st

if ‘un’ not in st.session_state:
st.switch_page(“Login_page.py”) # redirects to login

st.header(“Dashboard”)
st.subheader("Logged in as: " + st.session_state.un)

Libraries used: Only core streamlit (no extra auth libraries or components).

Problem faced:
After successful login, navigation to Dashboard works fine.
But on browser refresh (F5) or page reload on Dashboard, st.session_state is reset/empty, causing redirect back to login page. Session does not persist across refreshes. Also i have tried streamit_cookies_controller, but it is overrding the loggedin user.

Expected: Stay logged in on refresh (like most web apps). App will have 100+ concurrent users.

Any solutions without external auth providers? (e.g., cookies, tokens) Thanks!