Fetching User Session Data on the Client Side with useSession
Hello! I'm having trouble retrieving the logged-in user's information on the client side. I need the user information for my component, but how should I fetch the current user's session data?
Here is my code:
With this code, I get the following error:
Should I wrap my layout with SessionProvider, or is there a better way to get the current session on the client side?
13 Replies
you'll have to wrap your layout with
SessionProvider
as said in the docsGetting Started | NextAuth.js
The example code below describes how to add authentication to a Next.js app.
i doubt that there is another way as the
SessionProvider
is essential for next auth to function properlyThanks from your response, what if we use TRPC and get the useSession from there like this
app/utils/userClient.ts:
server/api/routers/user.ts:
app/_component_dashboard-content.tsx:
Could u fetch the current logged user like this?
You can but why?
yeah. your
/userClient.ts
is not required. you can use the status
returned from useSession
instead of doing it yourselfconsider checking this out if you want to check the user session on the server
https://next-auth.js.org/configuration/nextjs
Next.js | NextAuth.js
getServerSession
plus you should consider using auth.js. next auth has been converted to auth.js
https://authjs.dev/getting-started/session-management/get-session?framework=Next.js
these docs are more clearer on server usage
Auth.js | Get Session
Authentication for the Web
@Manqo off topic question
but why you do certain logic on the component it self?
is not simplier to do certain logic on the middleare and handle all cases?
and why you pass the user to DocumentTabs?
I'm not roasting, I'm just trying to understand the different ways people do this kind of thing. to understand what is be most common way. when using auth
well it depends what logic you want to do inside of your middleware
you can check out the recent nextjs middleware drama for more information on what is the best practice for auth checks
theo also made a video on it
i prefer to do auth checks on trpc instead of the components themselves
Its how you are supposed to do, use middleware to server side check auth or on page level SERVER SIDE, redirect away If not authenticated. Also you are supposed to check auth on your queries/ mutations because you can query manually without being on the page
yeah it makes sense