#Hydration error when window is used inside client component?

9 messages · Page 1 of 1 (latest)

dusky shale
#

Error msg : Error: Hydration failed because the initial UI does not match what was rendered on the server

'use client'

export default function Navbar({ isLoggedIn }) {
return  isLoggedIn ? null : 
          typeof window !== 'undefined' ? null : 
            <div>
                <a
                  href={`${
                    window.origin + process.env.NEXT_PUBLIC_BASE_PATH
                  }/auth/login?return_to=${window.location}`}
                  className="sign-in-button"
                >
                  Sign in
                </a> 
            </div>
}

So how do I fix this hydration issue?

drifting larkBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
mint tundra
#

client components are still rendered on the server (they are basically the same thing as components in the pages dir) so you can't access the window variable like that. you can only run client-side code in places you know won't run in the server, like inside useEffect

dusky shale
#

Thanks for the reply.

#

But I need entire location in return_to parameter, not just pathname.

#

How do I construct the entire url?

mint tundra
#

you could either:

  1. have the app base path as an env variable (like https://app.com) and use it to complete the URL so it works in the server
  2. delay the rendering of the link so it only reads from window after it has been mounted. using the useEffect hook
dusky shale
#

I will go with first method.