DEV Community

Discussion on: Authenticating things with cookies on Next.js

Collapse
 
rumeetgoradia profile image
Rumeet Goradia

Great approach! Thanks for this helpful article.
Quick question: how would you recommend maintaining the cookie data (i.e. the user information -- name, email, id, etc.) in a global state? For example, if you wanted to create a global Navbar component that displays the user's name, you wouldn't be able to pull that from the cookie, and you can't use getServerSideProps from a component. So, you'd most likely need to pull that data from the global state, e.g. using React Context API. After signing in, you could probably set the global state with the data from the response from the POST request to api/sessions, but after a page refresh, how would you initialize that global state with the data from the cookie?

Collapse
 
jfranciscosousa profile image
Francisco Sousa

Ah sorry for the delay... not receiving dev notifications on my email for some reason.

You can read pageProps on _app.tsx (nextjs.org/docs/advanced-features/...) and add that to a global provider. You can read that with useContext on any componeny you want!

Do it on the render function though. If you add a custom getInitialProps on _app.tsx you disable all kinds of static optimizations!

Collapse
 
rumeetgoradia profile image
Rumeet Goradia

Thanks for the reply! Will definitely try this out :)