Hi, I’m using clerk.com for authentication (I wrote a thin API wrapper for server-side checks). I rely on conn |> Plug.Conn.fetch_cookies to pull this off.
In a LiveView, is there a way to access cookies? I only see the CSRF in my mount/3 session value. I can see the cookies are there in the browser request to open the socket connection, but I don’t see them in my LiveView.
You need to extract what you want from the cookie and add it to the session. The session gets passed to LiveView in the mount/3 callback.
I do exactly this and it works fine.
Here’s my plug code:
defmodule MyWeb.Plug.PutUserFromCookie do
@moduledoc """
Reads a user_details cookie and puts user_details into session
"""
import Plug.Conn
def init(_) do
%{}
end
def call(conn, _opts) do
conn = fetch_cookies(conn)
cookie = conn.cookies["user_cookie"]
user_details = case cookie do
nil ->
%{user_name: "Anonymous", user_id: nil}
_ ->
Plug.Conn.Query.decode(cookie)
end
conn
|> put_session(:user_details, user_details) # Makes it available in LiveView
|> assign(:user_details, user_details) # Makes it available in traditional controllers etc
end
end
This plug needs to be included in the router pipeline:
If you get sick of copying / pasting the code to transfer the user details from session to socket assigns in each and every LiveView, you can set up an on_mount hook
I’ll try this tonight. A huge thank you! New to Elixir + Phoenix. Not the steepest learning curve I’ve experienced certainly, but definitely getting tripped up on “simple” things.