If you are using NextAuth, how are you accessing Auth data in Client Components?

For those using the create-t3-app, let's say we add a collapsible sidebar and in that sidebar we have navigation links, but also at the bottom we would like to include the logged in user information (Name and Email). How do you achieve this?: 1. Passing a server component through children into a client component? 2. Using session provider to pass session info as a prop? Is one of these methods more secure? I'm getting hung up on the best way to go.
9 Replies
cje
cje7mo ago
get the session on the server, pass it to the client component as a prop
Hakkā 多
Hakkā 多7mo ago
You can use the context to use the hook and get to client component but you need to define the Provider in the layout :3
miikee
miikeeOP7mo ago
So my layout.tsx (which is server rendered), I can run a "const session = await auth()" and pass it to my ApplicationLayout component (which utilizes 'user client') like so: <ApplicationLayout session={session}> {children} </ApplicationLayout> This will allow me to display {session?.user.email} and {session?.user.name} within the children of ApplicationLayout?
Hakkā 多
Hakkā 多7mo ago
Yes on client component only by using the hook Else on server components you can use directly the normal await auth() by making your component async
miikee
miikeeOP7mo ago
This is the hook you are referring to?
No description
Hakkā 多
Hakkā 多7mo ago
I guess so
K1|ller
K1|ller7mo ago
yeah you can get the session with that hook but personally I keep in sync the user that was created in the DB, I don't care much about the session
miikee
miikeeOP7mo ago
Would you be able to elaborate a bit more on the "keep in sync the user that was created in the DB" comment? Doesn't NextAuth manage this aspect for you?
K1|ller
K1|ller7mo ago
next auth in server or client side will only return what's in the cookie that's: name, email, imageUrl You can create other properties and pass them to the session but I have had typesafe issue with that so I have a context with the user. To be honest I haven't gone deeper with it, there must be a smarter way, I use the session to get the email, the email is my weapon for verifying who's logged in btw i'm using v4
Want results from more Discord servers?
Add your server