javascripthtmlauthenticationevent-handlingejs

How to Ensure that Clicks on <li> Element in Nav Bar Correctly Redirect Authenticated Users to the Dashboard Page?


I'm experiencing an issue with my web application where clicking on an account icon behaves inconsistently. When I click near the edge of the account icon, it correctly redirects to the dashboard page. However, clicking in the middle of the icon redirects to the login page. This is problematic since authenticated users should be directed to the dashboard, not the login page.

Below is the relevant part of my index.ejs file:

<header class="header nav-open">
  <a href="/">
    <img class="logo" src="img/NAMO.png" alt="NAMO logo"/>
  </a>
  <nav class="main-nav">
    <ul class="main-nav-list">
      <li>
        <a class="main-nav-link underline" href="/">Home</a>
      </li>
      <li>
        <a class="main-nav-link underline" href="#meals">About Us</a>
      </li>
      <li>
        <a class="main-nav-link underline" href="#blog">Blog</a>
      </li>
      <li>
        <a class="main-nav-link" data-action="toggle-cart">
          <i class="fa-solid fa-cart-shopping"></i>
          <span class="cart-number"></span>
        </a>
      </li>
      <li id="account-icon-container">
        <a id="account-icon" class="main-nav-link" href="/login">
          <ion-icon name="person" class="profile-icon"></ion-icon>
        </a>
      </li>
    </ul>
  </nav>
</header>

Here is the JavaScript code I am using to handle the click events:

document.addEventListener("DOMContentLoaded", () => {
  const personLi = document.getElementById("account-icon-container");
  const personBtn = document.getElementById("account-icon");

  const updateHref = async () => {
    try {
      const response = await fetch("/api/check-auth");
      const authData = await response.json();

      if (authData.isAuthenticated) {
        personBtn.href = "/dashboard";
      } else {
        personBtn.href = "/login";
      }
    } catch (error) {
      console.error("Error checking authentication status:", error);
      personBtn.href = "/login";
    }
  };

  if (personLi) {
    personLi.addEventListener("click", async event => {
      event.preventDefault();
      await updateHref();
      window.location.href = personBtn.href;
    });
  }

  if (personBtn) {
    personBtn.addEventListener("click", event => {
      event.preventDefault();
    });
  }
});

Solution

  • You are using an <a> tag in the <li> when you already have an event handler to handle the click on li. I believe the <a href="/login"> is what's causing the redirect to login. Do this instead

    <li>
     <span id="account-icon" class="main-nav-link">
        <ion-icon name="person" class="profile-icon"></ion-icon>
      </span>
    </li>  
    

    If there is a CSS-associated reason why you were using <a> in the first place (e.g. pointer cursor) you can style that in your CSS.