Rez Mohsnei
Rez Mohsnei

Reputation: 207

nextjs: Warning: Prop `className` did not match. Server: "x" Client: "y"

This is my code:

export default function Nav() {
    const { userLogin } = useUser()
    console.log(userLogin)
    
    return (
        <nav className={styles.nav}>
            {!userLogin ? (
                <Link href={"/login"}><a className={`${styles.top}`}></a></Link>
            ) : (
                <Link href={"/profile"}><a className={`${styles.userLogged}`}></a></Link>
            )}
        </nav>
    )
}

And this is useUser:

export default function useUser(){
    var userLogin = false

    const cookies = parseCookies()
    if (cookies.token) {
        userLogin = true
    }

    return { userLogin }
}

So, if userLogin is false, everything is OK.

But if userLogin is true I get this error:

Warning: Prop `className` did not match. Server: "x" Client: "y"

This error show when I use cookies.

I don't want to use next/dynamic. because dynamic reload component again on click.

Upvotes: 4

Views: 1168

Answers (1)

Daniel Bellmas
Daniel Bellmas

Reputation: 657

If parseCookies happen only client-side, aka, uses document then next will have different HTML from the client, this happens to me with localStorage because I'm using window.

But because you are using cookies you can get them from getInitialProps's req argument:

App.getInitialProps = async ({ ctx }) => {
  const { req } = ctx;

  const cookies = parseCookies(req ? req.headers.cookie : document.cookie);

  return {
    pageProps:  { cookies }
  };
};

If you are using nookies they have a cool integration with Next.js which allows you to pass the ctx as the first argument like so: const cookies = parseCookies(ctx) and ctx will come from getInitialProps or getServerSideProps

see https://github.com/maticzav/nookies/blob/c4b1ca461e7b04877d295cb740fa8cbc1db2ad36/packages/nookies/src/index.ts?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L15

Upvotes: 3

Related Questions