How do you fetch and share authedUser throughout the app?
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
I tried several methods and I've landed on fetching the user in the middleware and then passing it to the _app.tsx through the headers and then sharing it with context. Please let me know if this is a right approach.
17 Replies
Sun bearOP
you can set session in cookies
https://nextjs.org/docs/app/building-your-application/authentication
https://nextjs.org/docs/app/building-your-application/authentication
Sun bearOP
I am using old pages router. Is this still relevant?
Maybe it is just better to fetch authedUser on client side?
Maybe it is just better to fetch authedUser on client side?
@Sun bear How do you consume the user data on your pages?
Sun bearOP
I take it out from the pageProps in the _app.tsx and then share it with context. But with this approach I have to fetch authedUser in every single route using getServerSideProps, to make it available under pageProps inside _app.tsx. Which is not ideal, because it does not let me use static generation
Sun bearOP
The reason I need it on every page is because I need user info in layout to show in the navigation bar
well, your approach is not correct
you want to show user data in the navigation bar but you still want SSG
it doesn't make sense
static generation happens in build time and at that moment you don't know auth user
Sun bearOP
yeah. I know it is not correct, that's why I am asking which would be the best approach, to fetch authed user on client side? What would you recommend
from your previous messages, I guess you are on the page router, right?
You can fetch user data from the client side and store it in your global state
Sun bearOP
Thanks
@Sun bear The reason I need it on every page is because I need user info in layout to show in the navigation bar
Why don't you wrap your all routes(pages) by a layout component?
Sun bearOP
I do. but I could not fetch it inside layout since I was using SSR
do client-side data fetching in your layout component I would suggest