Next js hydration error when implementing private route

Viewed 22

I'm using nextjs 12.2.5 have created a higher order component in order to limit access to users that are logged in for certain pages but I keep getting hydration error. enter image description here

Here is my code:

WithAuth.jsx

import { useRouter } from "next/router";
const withAuth = (WrappedComponent) => {
  return (props) => {
    if (typeof window !== "undefined") {
      const Router = useRouter();

      const token = localStorage.getItem("token");

      if (!token) {
        Router.replace("/login");
        return null;
      }

      return <WrappedComponent token={token} {...props} />;
    }

    // If we are on server, return null
    return null;
  };
};

export default withAuth;

Home.jsx

const Home = () => {

  return (
    <Layout>
      Home
    </Layout>
  );
};

export default withAuth(Home);

I have read the documentation on hydration but I still don't understand how I can implement my private route with Higher Order Component and avoiding the hydration error. How am I supposed to implement private route with next js?

0 Answers
Related