Calling shared functions that expects the conn interface from live_view

I’m currently building an authentication system in Phoenix LiveView where users can register and log in via a modal without a full page reload. My process involves logging the user in immediately after registration and then displaying a PIN verification modal.

In a traditional Phoenix controller, I’d typically use conn to manage session data, like this:

def log_in_user(conn, user, params \\ %{}) do
    token = Account.generate_user_session_token(user)
    user_return_to = get_session(conn, :user_return_to)

    conn
    |> renew_session()
    |> put_token_in_session(token)
    |> maybe_write_remember_me_cookie(token, params)
    |> redirect(to: user_return_to || signed_in_path(conn))
  end

However, I’m struggling to adapt this to LiveView. Since LiveView primarily works with socket instead of conn, I’m not sure how to properly manage the session and authentication state. I initially tried passing the socket to the above function, but it didn’t work as expected because it requires conn.

I understand that LiveView’s lifecycle means that data set on conn during the static render isn’t accessible in the live render. I’ve read that using assign_new to set session data or using the new on_mount callback in LiveView could help, but I’m unsure how to apply these concepts when my session management relies heavily on conn.

Has anyone successfully managed this transition from conn-based session handling to a LiveView-compatible approach? Any best practices for structuring the code so that it’s reusable across both traditional controllers and LiveViews?

Thanks in advance for any advice or examples!

You could use a server side session store, which would allow you to manage the session from LV. But with the default cookie based session storage you need a controller. You can only write to cookies when handling http requests, which you don’t have on a websocket based LV connection.

Thanks for the suggestion! I’ll give the server-side session store a try to see how it works. Do you have any recommendations for specific approaches? I’m curious to know if there are any potential pitfalls to watch out for.

I used Javascript hook to Solve the issue, here is the flow

User registersLiveView handles registration and triggers the login eventJavaScript receives the event and makes an AJAX request to log in the userAfter successful login, the PIN modal is shown

1 Like