<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="307804" data-post-id="307804">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="RobertoSchneiders" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/RobertoSchneiders/120/32347_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  RobertoSchneiders
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>right, but at that time, the session didn’t exist, the user was not logged in.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="307804" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/user-authentication-across-multiple-tabs-with-liveview/59600/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-307804" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="307804"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="307806" data-post-id="307806">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Hermanverschooten" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Hermanverschooten/120/6447_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Hermanverschooten
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>The user is not logged in but phoenix creates a session anyway.<br>
When someone logs in you add their <code>user_id</code> to the session.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="307806" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/user-authentication-across-multiple-tabs-with-liveview/59600/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-307806" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="307806"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="307807" data-post-id="307807">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="RobertoSchneiders" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/RobertoSchneiders/120/32347_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  RobertoSchneiders
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>oh, I see what you mean. I’m gonna give it a try. thank you</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="307807" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/user-authentication-across-multiple-tabs-with-liveview/59600/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-307807" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="307807"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="308182" data-post-id="308182">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="RobertoSchneiders" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/RobertoSchneiders/120/32347_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  RobertoSchneiders
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Thanks, everyone. I ended up with a solution that is a mix of your suggestions.</p>
<h3><a name="p-308182-summary-1" class="anchor" href="#p-308182-summary-1" aria-label="Heading link" rel="nofollow"></a>Summary:</h3>
<ul>
<li>I’m adding a guest token to the browser session/cookie (there is a session cookie even when the user is not logged in) when the first tab is opened. When the user logs in, the guest token is cleared from the session.</li>
<li>In the <code>on_mount</code> of every LiveView we check if such token exists, if it does, we subscribe to <code>reload##{guest_token}</code>.</li>
<li>When a LiveView receives that message we send a force redirect to the socket.</li>
</ul>
<p>I’m using the same solution to fix the issue I mentioned <a href="https://forum.elixirforum.com/t/log-out-causes-attempting-to-reconnect-messages-on-additional-browser-tabs/59599" rel="nofollow">here</a> where other tabs would see the “We can’t find the internet. Attempting to reconnect” message when logging out.</p>
<p>Although forcing a page reload is an okay solution, for now, I would like to have more control over sessions in LiveView so I could refresh the page state without a page reload. I think that’s not a solved issue at the moment. I understand why we need a cookie-based session for the Plug requests (and initiating the WebSockets connections) but I’m thinking of also having a localStorage-based session (with all the security you can have) to allow the live sessions to be more dynamic.</p>
<h3><a name="p-308182-implementation-details-2" class="anchor" href="#p-308182-implementation-details-2" aria-label="Heading link" rel="nofollow"></a>Implementation Details:</h3>
<p>In the <code>fetch_current_user</code> method that is run in the <code>:browser</code> pipeline I add a “guest session token” to the cookie.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule AppWeb.UserAuth do
  ...
  def fetch_current_user(conn, _opts) do
    {user_token, conn} = ensure_user_token(conn)
    user = user_token &amp;&amp; Accounts.get_user_by_session_token(user_token)
    assign(conn, :current_user, user)

    conn
    |&gt; assign(:current_user, user)
    |&gt; maybe_add_guest_session_token()  &lt;--- Added this
  end

  defp maybe_add_guest_session_token(conn) do
    if conn.assigns.current_user || get_session(conn, :guest_session_token) do
      conn
    else
      put_session(conn, :guest_session_token, Ecto.UUID.generate())
    end
  end
end
</code></pre>
<p>The default live session runs the on_mount of a new module:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">live_session :default, on_mount: AppWeb.RealTimeSessions do
</code></pre>
<p>The RealTimeSessions module looks like this:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule SwayzeWeb.RealTimeSessions do
  @moduledoc false

  import Phoenix.LiveView

  def on_mount(:default, _params, session, socket) do
    if connected?(socket) do
      session |&gt; maybe_subscribe_to_guest_session() |&gt; maybe_subscribe_to_logged_in_session()

      socket =
        socket
        |&gt; attach_hook(
          :save_request_path,
          :handle_params,
          &amp;save_request_path/3
        )
        |&gt; attach_hook(:handle_reload, :handle_info, &amp;reload_page/2)

      {:cont, socket}
    else
      {:cont, socket}
    end
  end

  defp reload_page(_msg, socket) do
    if socket.assigns[:trigger_submit] do
      {:cont, socket}
    else
      {:cont, socket |&gt; redirect(to: socket.assigns.current_uri)}
    end
  end

  defp save_request_path(_params, uri, socket) do
    {:cont, Phoenix.Component.assign(socket, :current_uri, URI.parse(uri) |&gt; Map.get(:path))}
  end

  defp maybe_subscribe_to_guest_session(session) do
    guest_session_token = Map.get(session, "guest_session_token")

    if guest_session_token do
      Phoenix.PubSub.subscribe(Swayze.PubSub, "reload##{guest_session_token}")
    end

    session
  end

  defp maybe_subscribe_to_logged_in_session(session) do
    logged_in_session_token = Map.get(session, "logged_in_session_token")

    if logged_in_session_token do
      Phoenix.PubSub.subscribe(Swayze.PubSub, "reload##{logged_in_session_token}")
    end

    session
  end
end
</code></pre>
<p>The force reload caused some issues with the login LiveView specs where the liveview used in the spec would be killed because it was receiving the reload message and forcing a redirect on the socket. This doesn’t really happen in production or even development because we have a full page reload on login (which is when we broadcast that message), but it happened in the specs. For now, I’m checking if <code>socket.assigns[:trigger_submit]</code> is assigned and aborting the force reload. I’m pretty sure that’s a bad idea but I didn’t find a better solution just yet.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="308182" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/user-authentication-across-multiple-tabs-with-liveview/59600/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-308182" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="308182"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="385535" data-post-id="385535">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="fteschke" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fteschke/120/36108_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  fteschke
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Warming up the old discussion.</p>
<p>How about adding this snippet to logged-in pages</p>
<pre data-code-wrap="xml"><code class="lang-xml">&lt;script&gt;new BroadcastChannel('auth-change').postMessage('login')&lt;/script&gt;
</code></pre>
<p>and this to the login page</p>
<pre data-code-wrap="xml"><code class="lang-xml">&lt;script&gt;
new BroadcastChannel('auth-change')
  .addEventListener('message', () =&gt; window.location.reload())
&lt;/script&gt;
</code></pre>
<p>To keep things purely client-side.</p>
<aside class="onebox allowlistedgeneric" data-onebox-src="https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel">
  <header class="source">
      <img src="https://developer.mozilla.org/favicon.ico" class="site-icon" alt="" width="48" height="48">

      <a href="https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel" target="_blank" rel="noopener nofollow ugc">MDN Web Docs</a>
  </header>

  <article class="onebox-body">
    <img width="690" height="690" src="https://developer.mozilla.org/mdn-social-image.46ac2375.png" class="thumbnail onebox-avatar" alt="">

<h3><a href="https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel" target="_blank" rel="noopener nofollow ugc">BroadcastChannel - Web APIs | MDN</a></h3>

  <p>The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages...</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>
 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="385535" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/user-authentication-across-multiple-tabs-with-liveview/59600/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-385535" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="385535"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>