Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 895
Rez Mohsnei Avatar asked Oct 29 '25 04:10

Rez Mohsnei


1 Answers

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

like image 123
Daniel Bellmas Avatar answered Oct 30 '25 22:10

Daniel Bellmas



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!