Keep on getting websocket connected and disconnected: LiveView session was misconfigured or the user token is outdated

In a pretty basic phoenix app running on localhost I keep on getting the websocket connected and disconnected while the server’s phoenix_live_view/channel.ex:1034 is reporting this in the debug log:

  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) Ensure the `protect_from_forgery` plug is in your router pipeline:

    plug :protect_from_forgery

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

    <meta name="csrf-token" content={Plug.CSRFProtection.get_csrf_token()} />

6) 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}});

I checked that all the steps outlined are implemented, but this doesn’t help, and the client’s websocket connection keeps on bouncing. The “_csrf_token” stays the same between consecutive websocket connections, but it seems that the csrf check fails.

Has anyone experienced it, and if so, can you suggest a solution?

Is this a newly generated project?

If everything is up-to-date, try removing the cookies, otherwise make sure you are using the latest phx.new generator.

1 Like

I used this boilerplate, and added user authentication with help of mix phx.gen.auth about 6 months ago. So this is not new, though, I updated all deps to the latest.

I tried your suggestion to generate a new app and compared, but don’t see significant differences.

What I noticed was that it only happens if I use localhost:4000, but if I use 127.0.0.1:4000 then it works as expected.