1

I'm trying to make a redirect if the user has a token saved in cookies or not, here's my code:

const Secret = () => {
  const router = useRouter();
  const [token] = useState({
    token: cookies.get("token") || null,
  });
  if (token.token == null || token.token.hasOwnProperty("error")) {
    router.push("/login");
  } else {
    router.push("/");
  }
  return (
    <>
      <h1>Secret</h1>
    </>
  );
};

But I get this error: No router instance found. you should only use "next/router" inside the client side of your app. Anyone knows how to fix it? Thanks!

1 Answer 1

4

I think the problem coming from where you put the code in. Your condition is supposed to be happened as the component is mounted, so try this:

React.useEffect(() => {
 if (token.token == null || token.token.hasOwnProperty("error")) {
    router.push("/login");
  } else {
    router.push("/");
  }
}, [])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.