03k64

03k64

Hi, I’ve been trying to add a markdown editor to my personal site and LiveView seems like a good candidate. I’ve built out various other pages on my site using traditional static views and I don’t really need LiveView functionality on other pages so I hadn’t used the --live option when creating the project. I’ve run through the installation guide multiple times trying to spot a step I missed but without success.

The page in question renders successfully but the websocket isn’t established - I see the following error in the logs:

[debug] LiveView session was misconfigured or the user token is outdated.

1) Ensure your session configuration in your endpoint is in a module attribute:

    @session_options [
      ...
    ]

2) Change the `plug Plug.Session` to use said attribute:

    plug Plug.Session, @session_options

3) Also pass the `@session_options` to your LiveView socket:

    socket "/live", Phoenix.LiveView.Socket,
      websocket: [connect_info: [session: @session_options]]

4) Define the CSRF meta tag inside the `<head>` tag in your layout:

    <%= csrf_meta_tag() %>

5) Pass it forward in your app.js:

    let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
    let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});

So far as I can tell I have done all of those steps as part of the installation guide. Each time I see the above debug log, it is preceded by the following info log:

[info] CONNECTED TO Phoenix.LiveView.Socket in 224µs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrfToken" => "LSBdOgQDDQNVPkQDPUcUDWgBG2ANInUNIdiqkIoIxopqN2PeXSn9dm9Z", "_mounts" => "0", "vsn" => "2.0.0"}

This gives me (possibly misplaced) confidence that the CSRF token is making it through and being sent with the WS connection request. I’ve included various other snippets from my project below relating to the sections in the debug message but I’d welcome any/all help on this because I’ve been stuck on it for a few days.

Two more things that may be relevant:

  1. I’ve noticed that when I open the LiveView enabled page and leave it alone, it repeatedly reloads the page. Each time it reloads the value of the _csrfToken in the info message changes
  2. I’m using Pow for authentication and I’m using the PersistentSession extension with it

Thank you in advance.

config/config.exs:

config :my_app, MyAppWeb.Endpoint,
  url: [host: "localhost"],
  secret_key_base: "A6DFaZxv0umgtupJyonqNf94nmXoZJeQxhRx3IFfrIdKzD4sojFR8VxOEPvfNPz0",
  render_errors: [view: MyAppWeb.ErrorView, accepts: ~w(html json), layout: false],
  pubsub_server: MyApp.PubSub,
  live_view: [signing_salt: "E0S8hIKgKFGFYiQAR341hR64N2f224tD"]

lib/my_app_web/endpoint.ex:

@session_options [
  store: :cookie,
  key: "_my_app_key",
  signing_salt: "EHfxVnHDQHSPKRsarohJJqNzrj8KUMWG"
]

...

socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [session: @session_options]]

...

plug Plug.Session, @session_options

lib/my_app_web/templates/layout/root.html.eex:

<head>
    ...
    <%= csrf_meta_tag() %>
    <script defer type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
    ...
</head>

assets/js/app.js:

import "../css/app.scss"

import "phoenix_html"
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"

const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
const liveSocket = new LiveSocket("/live", Socket, {params: {_csrfToken: csrfToken}})

liveSocket.connect()

window.liveSocket = liveSocket

Showing Posts 1 to 6

03k64

03k64 OP

I’ve now attempted the following:

  1. I ran mix clean --all, mix deps.get and mix deps.compile to ensure I didn’t have any borked dependencies.
  2. I ran rm -rf assets/node_modules, npm i --no-save --prefix assets to ensure I didn’t have any borked node modules.
  3. I’ve switched to using the MnesiaCache backend for Pow.

None of these things solved my issue and I still see the same debug message in my logs and the same pattern of page reloads. I added some calls to IO.inspect within the phoenix_live_view dependency and my problem seems to be that the created %Phoenix.Socket{} has no session information. The logged value of the socket is:

%Phoenix.Socket{
  assigns: %{},
  channel: Phoenix.LiveView.Channel,
  channel_pid: nil,
  endpoint: MyApp.Endpoint,
  handler: Phoenix.LiveView.Socket,
  id: nil,
  join_ref: "4",
  joined: false,
  private: %{connect_info: %{session: nil}},
  pubsub_server: MyApp.PubSub,
  ref: nil,
  serializer: Phoenix.Socket.V2.JSONSerializer,
  topic: "lv:phx-FjRz-igtqSANgQ2k",
  transport: :websocket,
  transport_pid: #PID<0.832.0>
}
BrentM

BrentM

I had the same sort of problems getting LiveView running. Getting all the little details right was pretty challenging.

It might be a long shot but I noticed that you didn’t call out including the LiveView js in your package.json. If i remember correctly, you have to add this to your deps in package.json:

"phoenix_live_view": "file:../deps/phoenix_live_view"

I also found it incredibly helpful to run the server in an interactive session if you aren’t already doing so.

iex -S mix phx.server

The LiveView will reset anytime you hit an error in your handlers and it’s really handy to see the error message right away.

03k64

03k64 OP

Thanks for the suggestions.

I double checked and I definitely have the phoenix_live_view dependency correctly included in my package.json.

I also tried running iex -S mix phx.server. Unfortunately I only saw the same output as before. I suspect the error I’m seeing prevents the socket from being established. I’m really struggling to think of anything else to try at this point.

Seb

Seb

Hi, Did you end up to solve that ? I’m inside this hell loop too

trisolaran

trisolaran

I believe this line might be the culprit:

Try to pass {params: {_csrf_token: csrfToken}} instead. The csrf token has to be passed as _csrf_token and not _csrfToken.

apohllo

apohllo

It might also happen, if you are running the code inside an IFrame.

For instance in Replit the WebView component displays the site inside an IFrame. As a result (I belive) the CSRF token is read from the Replit application, not the application you are developing. So the CSRF token is invalid.

The simplest solution in that case is to open the site directly in the browser and check if everything works as expected.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; 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
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews