How to store 'return to' URL when navigating from LiveView to another page (LiveView/regular)?

I have a live session called :home that consists of four LiveViews. From the LiveViews of this live session the user can navigate to a set of ‘secondary’ pages (LiveViews and regular views). Whenever a user does so, this ‘secondary’ page should show a back button that returns the user to the LiveView that they navigated from. If the user loads a ‘secondary’ page directly from the browser’s location bar, the back button is still visible and returns the user to one of the :home LiveViews by default.

I went into this problem thinking I would build it quickly, but cannot seem to find an elegant way to solve it. I can compare the navigation history (History API) with the URL’s of the :home live session, but I wanted to try to store the URL of the LiveView before redirecting the user to the requested page. Because the user is redirected from a LiveView, rather than a regular view, I fail to see how I can add the URL to the session data of the redirected-to page. There is no redirect(socket, to: "/path", session: %{return_to: "/path"}).

Edit:
So my question is: how can I pass data from a LiveView to a navigated-to LiveView/regular page?

First thing comes to my mind is to pass “return_to” as a query parameter and have a plug that would read that param and put the value into an “assign” for conn (for “dead” views). And attach an on_mount hook that does the same but for live_sessions.

3 Likes

This has the benefit of the button going to the right place when the user has multiple tabs open on your app, which is not the case if you store the path in the session.

3 Likes

Oh yes. Makes total sense. I like the approach.

Check. I hadn’t realized that issue yet. Ty.

Make sure to validate the return_to value to mitigate phishing attacks: Unchecked Redirect | Hacker101

Also, you might want to remove it from the URL so that when people bookmark or share the current URL, it doesn’t send them somewhere unexpected after visiting the URL.

4 Likes