Get cookie session key in LiveView


I’d need to get the session key stored in _<app>_key cookie in the live view. I can’t see it in the session parameter.

I’ve created a plug to store it using put_session:

defmodule NhcWeb.Plugs.SessionKey do
  import Plug.Conn

  def set_session_key(conn, _params) do
    |> put_session(:nhc_key, conn.req_cookies["_nhc_key"])

But that gives me a cookie overflow errror after some reloads. Probably because the information stored in the session is getting bigger on every reload, but I can’t figure out why exactly. I guess it had to replace the content instead of appending.


so, um, I am confused why you would you like to do that.

The second argument to Phoenix LiveView mount/3 callback function is in fact session content. All the values you have set in the cookie are available for your LiveView at mounting through this interface.

And, when you are doing this:

    |> put_session(:nhc_key, conn.req_cookies["_nhc_key"])

I think you are putting the serialized value of the whole session into a session cookie itself and indeed it will explode with overflow pretty soon :).

What are you trying to achieve here that can’t be done by accessing the second argument of the mount/3 function?

1 Like

thanks for your answer @hubertlepicki!

Your comment made me realize that maybe we don’t have session id in the cookie :slight_smile:

What I’m doing is a cart for an ecommerce site. The cart is an Agent managed by a DynamicSupervisor and a Registry. I want to create agents for the cart based on the session_id of the users, that would be the cart id.

In the session parameter of mount I don’t have the key, but I realized that’s because there is no id, nor a hash for each user.

So I guess that I should create a cart_id using UUID for example, and store it in the cookie.

What do you think?


Yep, seems like the way to go.


You probably don’t need an example, but I put a UUID as session_id here, and use it in LiveView: