annad

annad

I’m posting this for beginners who are new to Phoenix LiveView and web development (like myself). I really struggled to get my head wrapped around storing server-side session data. Below is the problem Use Case and solution that ended up being crazy easy to set up … if you know what to do. :slight_smile:

For those who are experienced in Liveview … please feel free to make any corrections! I’m just trying to contribute to the community when I figure things out in hopes it will make it easier for others.

First, I want to thank @hive and @kokolegorille for their help with this. Both provided examples that helped me understand how to use OTP. Also want to reference this blog post that was super helpful: Persistent session data via a database in Phoenix LiveView – The Pug Automatic

ASSUMPTION: This example assumes you are using phx.gen.auth for authentication and you have a working knowledge of how that works.

USE CASE: This is not my app, but it is a good example to explain the use case. Think of a typical real estate website like Zillow or Redfin. A user will often start searching the website without being logged in. The user selects a bunch of filters to target their search of properties. If they find a property they like, they “save” that property. As soon as they click on “save”, they are asked to log into the website so that the property can be saved to their user profile. After the “save” is executed, the app will redirect the user back to the search page and ALL of the filters will still be in place. You never want the user to lose their pre-selected filters. That would be annoying.

LIVE VIEW: To implement this, I used two LiveViews:

Unauthenticated Liveview
Index.ex (lists the resources and allows the user to select filters without being logged in)

Authenticated Liveview - this path sits behind [:require_authenticated_user] in the router
Save_Resource.ex (allows user to save resource after redirecting them to login)

PROBLEM:

When the user selects “Save”, they are redirected to the Save_Resource Liveview. The key word here is “redirected.” The assigns from Index are not passed along. Even if you implemented Save as a component, you’d still need to redirect the user to Login and again that would flush the assigns. The advantage to using a Liveview behind the “authenticated” path in the router is that it automatically handles the login enforcement. But that redirection also means that all of the FILTERS that the user selected could be potentially lost. We want the user to return to Index and still have all of their filters in place. This is the key problem being solved by the solution below.

So there are two options for storing those filters:

  1. Send them back as params in live_redirect which would create a very heavy and ugly URL
  2. Store the filter criteria in server side storage.

Ok, there is a third option of storing them as cookies, but this example is focused on the server side. :slight_smile:

Both @hive and @kokogorille helped me understand how to use OTP to store and retrieve the filter criteria on the server. Here are the steps:

ROUTER.ex
Create a plug to generate a unique session_id. First add the plug name to the browser pipeline

pipeline :browser do
	# …
	plug :assign_session_id
end

At the bottom of the router.ex file, add the function to set a unique ID number to the session if it is not already set.

defp assign_session_id(conn, _) do
    if get_session(conn, :session_id) do
      # If the session_id is already set, don't replace it.
      conn
    else
      session_id = Ecto.UUID.generate()
      conn |> put_session(:session_id, session_id)
    end
  end

MYAPP/key_value_store.ex
Create this file (and call it whatever you want). The code in this file is used to store and retrieve session data as key/value pairs.

defmodule MyApp.KeyValueStore do
  use Agent

  def start_link(initial_value \\ %{}) do
    Agent.start_link(fn -> %{} end, name: __MODULE__)
  end

  def store(key, val) do
    Agent.update(__MODULE__, &Map.put(&1, key, val))
  end

  def get(key) do
       Agent.get(__MODULE__, &Map.get(&1, key))
  end
end

APPLICATION.ex
Add this to def start(_type, _args) so that the KeyValueStore is created when the app is started

   def start(_type, _args) do
      children = [
         # …
        MyApp.KeyValueStore
   ]

   # …
end

USER_AUTH.ex
Add this code into user_auth.ex so that you don’t lose your session_id when it calls renew_session() on the conn:

def log_in_user(conn, user, params \\ %{}) do

   # The line below is auto generated with phx.gen.auth. Notice that it’s doing the 
   # same thing we’re doing with the session_id.  It’s grabbing the token so that
   # it can be assigned back into conn AFTER renew_session() is called
   token = Users.generate_user_session_token(user)

  # Add this line to grab the existing session id
  session_id = get_session(conn, :session_id)

  conn
    |> renew_session()
    |> put_session(:session_id, session_id) # put the session_id back into the conn!
    |> put_session(:user_token, token)
    … # the rest of the code just stays

end

INDEX.ex
In mount, add the session_id to the assigns. You’re able to access session[“session_id”] thanks to that plug in the router.

def mount(_params, session, socket) do
    # …
   socket = assign(socket, :session_id, session[“session_id”]

{:ok, socket}
end

Now store the session data you want to access across LiveViews. This is just a function inside my Index.ex file. I call it from another function when I want the filter criteria stored.

defp store_search_criteria(socket) do

    criteria = “Whatever you are going to store.  This can be a List, Map, etc”

    # Put it in the store with the session_id
    MyApp.KeyValueStore.store(socket.assigns.session_id, criteria)

  end

In my app the control flows as follows:
Index.ex → SaveResource.ex → phx.gen.auth Login code → SaveResource → Index

When the user “saves” the resource, the router will check if the user is authenticated and send the user to login if that is required. Then the user will be redirected back to SaveResource and then ultimately redirected back to Index. So by the time the control makes it back to Index … those assigns are LONG gone!!!

INDEX.ex
Once back in Index, the user should be shown the resources AND the filters they applied before the save. The following code retrieves the filter criteria from the storage and resets the search to reflect those pre-selected filters:

defp apply_action(socket, :index, _params) do

    # Retrieve criteria from storage
    criteria = KeyValueStore.get(socket.assigns.session_id)

    # Update criteria in my app if there are preselected filters
    if criteria != nil do
      socket
           |> assign(:resourceform, nil)
           |> assign(:resource_forms,
              Resourceforms.list_resource_forms(criteria))
    else
      socket |> assign(:resourceform, nil)
             |> assign(:resource_forms, list_resource_forms())
    end
end

Be sure to restart phx.server after updating the files.

AND THAT’S IT!!!

One last note is that you will have to do periodic cleanup of the KeyValue store. My next challenge is to figure out how to do periodically clear the storage using a scheduled OTP event.

First 2 of 2 Posts Switch mode

kokolegorille

kokolegorille

Well done, next step is to use GenServer, so that You can send yourself a periodic message, to clear old session automatically.

I just want to point this code…

It is not going to do what You think it does, because of the immutable nature of Elixir :slight_smile:

annad

annad OP

Arg! That was a copy and paste error. Thank you for catching that. I just fixed it above. It seems to work for me. The “if” and “else” both send back an updated socket which is then returned via the “handle_params” call. Let me know if I’m still doing it incorrectly.

— All posts loaded —

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 91898 914
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
AstonJ
Just a general thread to post chat/news/info relating to AI/ML stuff that may be relevant for Nx now or in the future. Got anything to sh...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
mudasobwa
While I am working on the Language Agnostic Code Audit SaaS, which uses MetaAST (spoiler: I am expecting it to be in a good shape for ann...
New

We're in Beta

About us Mission Statement