Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional rendering in Next JS with JWT

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading