What is the best way to store data during the lifecycle of a liveview?


I am struggling here to add some LiveView to a regular phoenix app.

In a non-live route I use plugs to add to conn every bit of information required to auth and other things related to the user, like feature-flags, settings, tokes, etc this has been working well so far.
As Liveview uses sockets this cannot work the same way, but I cannot find which is the best option to keep this data accessible in handle_event without querying the DB or the external APIs each time.

As a basic use case, once the user authenticate (by using an external service) it receives a jwt token, I need to use that token to do some queries to external APIs, this token is never used in render time, this is not a bi piece of data, but I have other maps that are quite big (like feature flags) also I will like to avoid to “leak” unnecesary data to client-side to be ont he safe side of things.


1 Like

You can put things in socket.private, though you want to namespace your keys to your apps name to avoid collisions.

1 Like

We discussed this exact matter on the Discord and came up with socket.private, so I asked the LV team about collisions: Add non_rendering_assigns · Issue #1386 · phoenixframework/phoenix_live_view · GitHub

Yes, socket.private seems the best option right now, but the fact is not directly exposed with an API as other assign concerns me.

Also, I seeassign_new/3 (phoenix_live_view/phoenix_live_view.ex at v0.17.10 · phoenixframework/phoenix_live_view · GitHub) may store things in private so there are possible conflicts there.

Related question, which is the best way to add a new key to private without triggering a socket reload?