What is the best practice for unstable_getServerSession()?
What is the best practice for unstable_getServerSession()? Should I get the data using getServerSideProps in a layout and do a state drill? Or return the data with unstable_getServerSession() in getServerSideProps for each component it needs?
10 Replies
or when should I use unstable_getServerSession()?
You can use it for example if you want to protect a page from non authorized users or visa versa
here a response from the openai chat lmao
You can do that in getServerSideProps and then do useSession in your component to get the session there if you need to use the information
You don't have to send it as props
If you use useSession without unstable_getServerSession() then it will have a loading state first, so the session won't be immediately available
So you'd have to show some loading state
Why wouldn't I return props?
I know it's super confusing, but the getServerSideProps actually passes through _app
And you have a session provider component there that wraps your entire app
So the session you return through props actually go there
Which is then available through useSession()
So if you do this, the session that comes out of useSession() should be guaranteed upon rendering the client component instead of having a if(isLoading) or if(!session) {return <div>Loading...</div>
Does that help?
that was an amazing explanation
I don't know how you could explain better I just need to unstable_getServerSession() once in getServerSideProps which will send the session to other components or pages via _app? have I got it right?
Here is the example from next-auth:
Instead of checking session in the component I do it in gssp() and redirect based on some conditions, so session doesn't need validation on component
thank you amanuel