How to redirect to previous URL after login?

It’s simple to redirect to a specific URL by adding (to wherever your login form is) this:


However, if you need to redirect to the previous URL dynamically, it’s a little more tricky (add to global.js) with this:

// Add this script to the customer login page or a global script file
document.addEventListener('DOMContentLoaded', function() {
  // Check if we are on the login page
  if (window.location.pathname.includes('/account/login') || window.location.pathname.includes('/pages/doctor-login')) {
    // Store the referrer URL in a cookie
    document.cookie = "previousPage=" + document.referrer + "; path=/";
  }
  // Check if we are on the account page after login
  if (window.location.pathname.includes('/account') && document.referrer.includes('/account/login') || document.referrer.includes('/pages/doctor-login')) {
    // Retrieve the referrer URL from the cookie
    var cookies = document.cookie.split(';');
    var previousPage = null;
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.startsWith('previousPage=')) {
        previousPage = cookie.substring('previousPage='.length, cookie.length);
        break;
      }
  }
  // Redirect to the previous page if it exists
  if (previousPage) {
    window.location.href = previousPage;
  }
}
});

This second option feels pretty overkill, and I haven’t been able to get it to work anyway. If I could just use the first option, but get that URL dynamically, with a little JS or the assign tag, it would be ideal. I’m still learning Shopify, so the following examples are obviously wrong, but something like this would be great:


or

{% assign prev_url = 'history.go(-2);' %}

Thanks