📎 Webclip
Persistent session data via a database in Phoenix LiveView
The post describes a way to keep LiveView session data across reloads and browser restarts by storing it in PostgreSQL. It assigns a unique session_id in the Plug session, keeps the cookie alive with a long max_age, and uses that ID as the lookup key for persisted settings.
Reading notes#
- LiveView keeps state in a process that ends when the page is left, so it does not have an obvious built-in way to persist session data.
- The approach starts by adding a
session_idto the browser session in the router with a Plug. - Session cookies are configured with a long
max_ageso the browser can keep them after a restart. - The app uses the
session_idas a key to store and retrieve data from PostgreSQL. - The example table stores
username,session_id, andread_at. - The
Settingsschema validatessession_idand definesfor_session/1to load the record for a session. - When a record exists,
read_atis updated so stale records can be tracked. - Stale records older than
@stale_after_daysare deleted whenfor_session/1runs. - If no record exists,
for_session/1returns an unpersisted%Settings{session_id: sid}. - In the LiveView example,
mount/3loads settings from the session and assigns them to the socket. - The form updates
usernameonphx-change, and the handler inserts or updates the settings record depending on whether it already has anid. - The author says this feels more elegant than the
localStorageversion because the data is available on the first render. - The discussion notes that this is similar to a database-backed session store, but LiveView accesses it outside the usual HTTP request/response cycle.
