Longpoll and Phoenix LiveView - how do I make sure sessions are available on the LV callbacks?

Recently i got the need to switch to longpoll instead of using websockets. So i make a config change in the endpoint:

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

i also make the change to my JS that starts the livesocket

let autoscrubSocket = 
      new LiveSocket(
             "/live", 
             Socket, 
             { 
                transport: LongPoll
                params: { _csrf_token: csrfToken } 
             })

when i go to the page that renders the liveview i get two calls to mount callback on the liveview. The first call (the one that is trigerred by the normal routing through router) contains session information. The second callback that comes from the JS code above trying to connect is not passing any session info. I guess it is failing to process cookies that carry the session info in between that longpoll calls. So, i checked if longpoll even sends those and it does but when it gets to the server it seems those get ignored.

I am wondering how do i make sure sessions are available on the LV callbacks?

1 Like
 socket("/live", Phoenix.LiveView.Socket,
    websocket: [connect_info: [session: @session_options]],
    longpoll: [connect_info: [session: @session_options]]
  )
4 Likes

Thanks for your help, Chris.

i did make this change and did not see it do anything so dismissed it as a possible solution but after your post i did a fresh restart and all seems to click now.

one follow up question. are there any requirements on the gateways in case of longpoll use? like do the sessions need to be sticky? How does LV find the correct PID to route messages to? Say the first longpoll request lands on instance 1 of the service and a consequent request (for the same LV) lands on another instance of the clustered service?

You’ll also want to make sure that you have long poll added in the app.js like…

let liveSocket = new LiveSocket("/live", Socket, {
    longpollFallbackMs: 2500,
    params: {_csrf_token: csrfToken}
})
1 Like