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:
'use client';

import { useRouter } from 'next/navigation';
import { useUserResumes } from '@/app/utils/resumeClient';
import { useCoverLetterActions } from '@/app/utils/coverLetterClient';
import { useSubscription } from '@/app/utils/userClient';
import { useSession } from 'next-auth/react';
import LoadingSpinner from '@/app/_components/LoadingSpinner';
import DocumentTabs from '@/app/_components/DocumentTabs';

const DashboardPage = () => {
const router = useRouter();
const { data: session, status } = useSession();
if (status === 'unauthenticated') {
router.push('/api/auth/signin');
return null;
}

const { data: userResumes, isLoading: resumesLoading } = useUserResumes();
const { getUserCoverLetters } = useCoverLetterActions();
const { data: userCoverLetters, isLoading: coverLettersLoading } = getUserCoverLetters();
const { subscription, isLoading: subscriptionLoading } = useSubscription();
if (resumesLoading || coverLettersLoading || subscriptionLoading || status === 'loading') {
return <LoadingSpinner />;
}


return (
<DocumentTabs
userResumes={userResumes || []}
userCoverLetters={userCoverLetters || []}
user={session?.user}
subscriptionPlan={subscription}
/>
);
};

export default DashboardPage;
'use client';

import { useRouter } from 'next/navigation';
import { useUserResumes } from '@/app/utils/resumeClient';
import { useCoverLetterActions } from '@/app/utils/coverLetterClient';
import { useSubscription } from '@/app/utils/userClient';
import { useSession } from 'next-auth/react';
import LoadingSpinner from '@/app/_components/LoadingSpinner';
import DocumentTabs from '@/app/_components/DocumentTabs';

const DashboardPage = () => {
const router = useRouter();
const { data: session, status } = useSession();
if (status === 'unauthenticated') {
router.push('/api/auth/signin');
return null;
}

const { data: userResumes, isLoading: resumesLoading } = useUserResumes();
const { getUserCoverLetters } = useCoverLetterActions();
const { data: userCoverLetters, isLoading: coverLettersLoading } = getUserCoverLetters();
const { subscription, isLoading: subscriptionLoading } = useSubscription();
if (resumesLoading || coverLettersLoading || subscriptionLoading || status === 'loading') {
return <LoadingSpinner />;
}


return (
<DocumentTabs
userResumes={userResumes || []}
userCoverLetters={userCoverLetters || []}
user={session?.user}
subscriptionPlan={subscription}
/>
);
};

export default DashboardPage;
With this code, I get the following error:
Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider />
Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider />
Should I wrap my layout with SessionProvider, or is there a better way to get the current session on the client side?
13 Replies
webdevkaleem
webdevkaleem2w ago
you'll have to wrap your layout with SessionProvider as said in the docs
webdevkaleem
webdevkaleem2w ago
Getting Started | NextAuth.js
The example code below describes how to add authentication to a Next.js app.
webdevkaleem
webdevkaleem2w ago
i doubt that there is another way as the SessionProvider is essential for next auth to function properly
Manqo
ManqoOP2w ago
Thanks from your response, what if we use TRPC and get the useSession from there like this app/utils/userClient.ts:
export function useSession() {
const { data, isLoading } = api.user.getSession.useQuery();
return {
session: data,
status: isLoading ? 'loading' : data ? 'authenticated' : 'unauthenticated'
};
}
export function useSession() {
const { data, isLoading } = api.user.getSession.useQuery();
return {
session: data,
status: isLoading ? 'loading' : data ? 'authenticated' : 'unauthenticated'
};
}
server/api/routers/user.ts:
getSession: protectedProcedure.query(async ({ ctx }) => {
return ctx.session;
}),
getSession: protectedProcedure.query(async ({ ctx }) => {
return ctx.session;
}),
app/_component_dashboard-content.tsx:
export default function DashboardContent() {
// Get data from tRPC (server-prefetched)
const { data: userResumes, isLoading: resumesLoading } = api.resume.getUserResumes.useQuery();
const { data: userCoverLetters, isLoading: coverLettersLoading } = api.coverLetter.getUserCoverLetters.useQuery();
const { data: subscriptionPlan, isLoading: subscriptionLoading } = api.user.getSubscriptionPlan.useQuery({});
const { session } = useSession();

if (resumesLoading || coverLettersLoading || subscriptionLoading) {
return <LoadingSpinner />;
}
return (
<DocumentTabs
userResumes={userResumes || []}
userCoverLetters={userCoverLetters || []}
user={session?.user}
subscriptionPlan={subscriptionPlan}
/>
);
}

export default function DashboardContent() {
// Get data from tRPC (server-prefetched)
const { data: userResumes, isLoading: resumesLoading } = api.resume.getUserResumes.useQuery();
const { data: userCoverLetters, isLoading: coverLettersLoading } = api.coverLetter.getUserCoverLetters.useQuery();
const { data: subscriptionPlan, isLoading: subscriptionLoading } = api.user.getSubscriptionPlan.useQuery({});
const { session } = useSession();

if (resumesLoading || coverLettersLoading || subscriptionLoading) {
return <LoadingSpinner />;
}
return (
<DocumentTabs
userResumes={userResumes || []}
userCoverLetters={userCoverLetters || []}
user={session?.user}
subscriptionPlan={subscriptionPlan}
/>
);
}

Could u fetch the current logged user like this?
Ahmed Senousy
Ahmed Senousy2w ago
You can but why?
webdevkaleem
webdevkaleem2w ago
yeah. your /userClient.ts is not required. you can use the status returned from useSession instead of doing it yourself
webdevkaleem
webdevkaleem2w ago
consider 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
webdevkaleem
webdevkaleem2w ago
plus you should consider using auth.js. next auth has been converted to auth.js
webdevkaleem
webdevkaleem2w ago
Auth.js | Get Session
Authentication for the Web
devve2kcc
devve2kcc6d ago
@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?
const { data: session, status } = useSession();
if (status === 'unauthenticated') {
router.push('/api/auth/signin');
return null;
}
const { data: session, status } = useSession();
if (status === 'unauthenticated') {
router.push('/api/auth/signin');
return null;
}
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
webdevkaleem
webdevkaleem5d ago
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
rocawear
rocawear5d ago
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
webdevkaleem
webdevkaleem5d ago
yeah it makes sense

Did you find this page helpful?