Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.JS - Error when Checking if window == undefined : Hydration failed because the initial UI does not match what was rendered on the server

I am getting the following error:

Hydration failed because the initial UI does not match what was rendered on the server.

I am using getServerSideProps and in my page, I check whether we are in the browser (window=='undefined'), and then return things accordingly:

export default function Page() {
  const { data: session } = useSession()

  if (typeof window == 'undefined') return null

  if (session) {
    return (
      <div>
        <h1>Protected Page</h1>
        <p>You can view this page because you are signed in.</p>
      </div>
    )
  }
  return <p>Access Denied</p>
}

But this line here

if (typeof window == 'undefined') return null

seems to be the problem. When this line is commented out, everything works.

It's also true that what's returned on the server side will be different to whats' returned on the client side - but I don't fully understand how I should solve this problem and why this is a problem?

I am doing this check precisely because I only want to render this page on the client side -side & when I do have a session. Am I misunderstanding this?

like image 514
antonwilhelm Avatar asked Oct 27 '25 04:10

antonwilhelm


1 Answers

The point of SSR is to prerender the page on the server. If on the server your page renders always null there's no need to use SSR.

If you want to prerender the page only if a session exists, then you have to check the session on the server, inside of getServerSideProps.

If you check the session inside of the page component, the check is done on the client, and again there would be no need to use getServerSideProps.

Here is an example took from one of my projects, in which I used NextAuth to manage authentication:

import { getSession } from 'next-auth/client';

// ...your page component here...

export async function getServerSideProps(context) {

  const session = await getSession({ req: context.req });

  if (session) {
    return { props: { session } };
  }
  else {
    return {
      redirect: {
        destination: '/auth',
        permanent: false,
      }
    };
  }
}

In this snippet the session is checked on the server.
If a session exists it will accessible in the page component via its props.
If the session doesn't exist, the user is redirected to the authentication page.

PS: I just checked the docs and it looks like the import has changed to 'next-auth/react' (which, by the way, make more sense as using /client on the server is misleading).

like image 63
anotherOne Avatar answered Oct 29 '25 18:10

anotherOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!