How to manage session state with live view

When reading about live view, I read this from José:

Why would the login be an horrible idea for LiveView?

And, as a more general question, how should session be managed when using LiveView. For regular app, and API endpoints, I usually just have a require_user plug that check the session for a user_id and retrieve the corresponding user from the database. My login action just |> put_session("user_id", user.id) after a successful login.

How would this work with LiveView?

See the original text I was replying to. :slight_smile: If you login through LiveView, then if you navigate to another page or open up another tab, you will have to login again. LiveView keeps the current page state.

When you render a liveview, one of the parameters is the session, which are the session fields currently in your session that you want to send to the liveview.

So if you do:

 live "/foo", FooLiveView, session: [:user_id]

Then the user_id field will also be available in the LiveView mount, which you can retrieve it from the database once again.

So the idea is to login as usual and then pass the relevant session fields to the live view.

4 Likes

Right, I get it, this is what I thought at first, but I wasn’t sure.

So, I can still build my registration page with liveview, but when signing in, I should just use a normal Phoenix page?

Yes. If I understood correctly, LiveView can’t update the :user_id in the session and the LV session is distinct in each browser’s tab.

And two tabs in the same browser won’t sync with each other. Each LiveView session is distinct.

1 Like

Must have been a late night back in May…sorry I didn’t thank you, but this was very helpful, thanks!

1 Like