#App router - redirect on path check

1 messages · Page 1 of 1 (latest)

tardy axleBOT
#

Hi @hardy stump. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, your if statement is incorrect. The issue lies in the logical operator you're using. You're using the OR operator (||), which means that if either of the conditions is true, the entire statement is true. In this case, if the path is not equal to "/" OR the path is not equal to /users/${userID}, it will always redirect to "/".

This is because when you're on the "/" path, the second condition (path !== /users/${userID}``) is true, and when you're on the /users/${userID} path, the first condition (path !== "/") is true. So in both cases, the entire if statement evaluates to true, and the redirect happens.

You should use the AND operator (&&) instead. This way, the redirect will only happen if the path is not equal to both "/" AND /users/${userID}. Here's how you should write it:

  const router = useRouter();
  const path = usePathname();

  if (path !== "/" && path !== `/users/${userID}`) {
    router.push("/");
  }

This way, the redirect will only happen if you're not on either of the two paths.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: