Next js hydration error when implementing private route


This Content is from Stack Overflow. Question asked by Sekki

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:


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

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

      if (!token) {
        return null;

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

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

export default withAuth;


const Home = () => {

  return (

export default withAuth(Home);

I have read the documentation on hydration but I still don’t understand how I can implement my private route code. I tried using useEffect so to retrieve the user datas after the page was first loaded but I could not find out how to differentiate when to display a loading state and when to redirect user to the login page.
How am I supposed to implement private route with next js?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?