Improving Login Flow – Redirect Users to Previous Page

Improving Login Flow – Redirect Users to Previous Page

itsrin
Visitor
3 0 0

Hello! 

 

I'm trying to update the login flow so that users are redirected back to the previous page they were on before logging in. Currently, after users log in, they're automatically redirected to their account page. While I have a script, I'm not sure how I can find all the pages/sections I need to update the code to the following: 

<a href="{{ routes.account_login_url }}?return_to={{ request.path | url_encode }}">


I've tried asking chatGPT, here's the link if more information is needed:
https://chatgpt.com/share/67f95c01-3c64-8005-b6a8-7b2aab6ec79c

 

What I Want to Achieve:

Instead of always redirecting to the account page, I want to dynamically redirect users back to the page they were previously viewing before they clicked "Login." For example:

  • If a user was on the "In Stock" page, logs in, they should be redirected back to the "In Stock" page.
  • If a user was on the "New Arrivals" page, logs in, they should go back to "New Arrivals" after login.

Here is the JS Script:

Placed in header.liquid file, and right before the final {% endschema %} line.

<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', function() {
    if (window.location.pathname === '/account/login') {
      sessionStorage.setItem('previousUrl', document.referrer);
    }

    if (window.location.pathname === '/account' && sessionStorage.getItem('previousUrl')) {
      window.location.href = sessionStorage.getItem('previousUrl');
      sessionStorage.removeItem('previousUrl');
    }
  });
</script>

 

Replies 0 (0)