Mutipages and st.session_state has no key "username"

There is an important detail to understand about assigning keys to widgets: when the widget is not rendered, all of its data (including its key and value in session state) are deleted.

You can use a pattern to copy data for widgets to other keys (not directly associated to a widget) in order to keep that data across multiple pages or through conditional rendering of various widgets.

Here’s a post where I give an example of this pattern. I prefix keys with underscores when assigning them to widgets and copy the data over to other keys (without the underscore) for keeping, independent of the widget.

Alternatively, there is a hacky trick you can use to interrupt the widget cleanup process. If you have:

if 'my_key' in st.session_state:
    st.session_state.my_key = st.session_state.my_key

at the top of every page where ‘my_key’ is assigned to some widget, this will prevent that widget’s key from getting deleted.

Important: I say to put this at the top of every page because in order to interrupt the key deletion, it needs to be executed on the first script (re)run when the widget is no longer rendered. So if you have a widget on page A and navigate to page B, the hacky script would have to be on page B.