Expected server HTML to contain a matching <svg> in <nav> in NextJs

Viewed 452

enter image description here

I am getting above error in my code. The code is

{ !get_cookie('token') ?
   <div className="sign-in-option"><Link href="/signin" className="nav-item">Signin</Link></div> :
   <svg className="icon icon-Vector">
     <use xlinkHref="/images/svg/sprite/sprite.svg#icon-Vector"></use>
   </svg>
}

If i remove cookie condition i will not get above error. From the error i understand that rendered Html is not able to match to the html returned by server. As get_cookie is a method to get cookie stored on browser. So server is returning something else.

How can i fix this issue.

1 Answers

As you correctly mentioned, the HTML rendered on the browser doesn't match the one generated on the server. To solve it you can move the value of get_cookie('token') to state and update it inside a useEffect.

const Header = () => {
    const [token, setToken] = useState()

    useEffect(() => {
        setToken(get_cookie('token'))
    }, [])

    return !token ? (
        <div className="sign-in-option">
            <Link href="/signin" className="nav-item">Signin</Link>
        </div>
    ) : (
        <svg className="icon icon-Vector">
            <use xlinkHref="/images/svg/sprite/sprite.svg#icon-Vector"></use>
        </svg>
    )
}
Related