I have a component like this :
export default function Header () => {
return (
<button>
FIRST BUTTON
</button>
<button>
OTHER BUTTON
</button>
)
}
What I need to do is to display the first button if the user is not connected, and replace it by the other button if he is.
I receive the json web token from an other API and I set it in the local storage.
But I don’t know what to do after.
I tried to put a ternary expression but it seems that the token is not accessible when the HTML renders so it doesn’t work.
>Solution :
I set it in the local storage.
You cannot do it with local storage because it’s only available on the client-side rendering. With Next.js, you need to keep data for the server-side rendering too.
I’d suggest you should move your json web token to cookies with nookies that will share values with both client-side and server-side renderings.
And then you can get your token like this
export default function Header () => {
const cookies = nookies.get({}) //get all cookies value
const { tokenValue } = cookies //`tokenValue` is your cookie name
return (</>
{tokenValue ? <button>FIRST BUTTON</button> : <button>OTHER BUTTON</button>}
</>)
}
Beyond that, local storage is not safe from XSS attacks, so we should avoid keeping sensitive data (like tokens) in local storage. You can check this out for better understanding.