In my Next.js app I have a navbar , and it displays a different UI based on if a user is logged in or not. I decided to keep track of if user is logged in by reading a cookie. Here is a relevant part of code:
export default function Navbar() {
let loggedin
if (typeof window !== undefined) {
loggedin = getCookie('auth')
}
return (
{!loggedin?
// one UI logic
:
//different UI logic
}
)
}
getCookie
is a simple function that is using npm package js-cookie
:
export const getCookie = (name) => cookies.get(name)
My issue is that when I hard reload a page or load it for the first time I get this warning in my console and some part of CSS is broken :
react-dom.development.js:88 Warning: Expected server HTML to contain a matching <div> in <div>.
in div (at Navbar.js:68)
in div (at Navbar.js:67)
in ul (at Navbar.js:34)
in div (at Navbar.js:26)
in nav (at Navbar.js:25)
in Navbar (at Layout.js:12)
in div (at Layout.js:11)
in Layout (at pages/index.js:18)
in Home (at _app.js:13)
in UserProvider (at _app.js:13)
in MyApp
in ErrorBoundary (created by ReactDevOverlay)
in ReactDevOverlay (created by Container)
in Container (created by AppContainer)
in AppContainer
in Root
After I navigate on a client to any other page this warning does not appear any more and CSS is fixed. I was able to pinpoint the issue, and if I comment out this part in my code the error is gone :
if (typeof window !== undefined) {
loggedin = getCookie('auth')
}
Of course, my navbar logic is broken in this case. I realize that there is no cookies on the server side, therefore to prevent it running on the server I check where the code is executed in this line if (typeof window !== undefined){}
. However, by adding console.log()
inside of the if statement I can see that it's running on the server too.
What am I doing wrong? Why do I get this warning and have some broken CSS? Why is if statement
running on the server in this case? I appreciate any help.