How to access session data in liveview/live controller?

Hey everyone! I have a project that adds the current user’s id to the session in a controller like so:

conn |> put_session(:current_user_id, user.id)

however trying to retrieve that in a liveview controller doesn’t seem to be possible since I can’t call

id = get_session(conn, :current_user_id)

since conn doesn’t exist. Suggestions for how I can access this state from within the LV controller? Thanks!

1 Like

Security considerations of the LiveView model — Phoenix LiveView v0.17.5 might be helpful

1 Like

Some very good information in there, but it doesn’t appear that they actually interact with or extract any session data from within the LV controller. They just read the user id in through a URL parameter

I guess the part most relevant to your situation is in Mounting considerations

def mount(params, %{"user_id" => user_id} = _session, socket) do
  ...

As you see above, the session is available as the second argument of mount/3. From there, you can save whatever data you need into the socket assigns:

  ...
  socket = assign(socket, current_user: Accounts.get_user!(user_id))
  ...
  {:ok, socket}
end

Then later, when the session is no longer available. You will still have the data accessible:

def handle_event("sample", _params, socket) do
  do_something(socket.assigns.current_user)
  ...
end
4 Likes

Am I missed the reference to _session there. Okay that makes more sense, thanks a ton.

2 Likes