Consider this Next.js server component that reads a user session and renders a greeting. What will it display if the session contains { user: { name: 'Alice' } }?
import { getServerSession } from 'next-auth/next'; import { authOptions } from '@/lib/authOptions'; export default async function Greeting() { const session = await getServerSession(authOptions); return ( <main> <h1>Hello, {session?.user?.name ?? 'Guest'}!</h1> </main> ); }
Check how the session object is accessed and the fallback value used.
The component uses optional chaining to safely access session.user.name. Since the session has the user name 'Alice', it renders 'Hello, Alice!'.
Next.js 14+ requires correct import paths for server session access. Which option shows the correct import and usage of getServerSession?
Check the official Next.js 14+ documentation for the correct import path.
In Next.js 14+, getServerSession is imported from next-auth/next. Other paths are deprecated or invalid.
userEmail after this server action runs?Given this Next.js server action that reads the session and extracts the email, what is the value of userEmail if the session is { user: { email: 'bob@example.com' } }?
import { getServerSession } from 'next-auth/next'; import { authOptions } from '@/lib/authOptions'; export async function getUserEmail() { const session = await getServerSession(authOptions); const userEmail = session?.user?.email ?? 'no-email'; return userEmail; }
Look at the fallback value used when email is missing.
The session contains the user email 'bob@example.com', so userEmail is set to that value, not the fallback.
This server component tries to access session but has a bug. What error will it raise?
import { getServerSession } from 'next-auth/next'; import { authOptions } from '@/lib/authOptions'; export default function Profile() { const session = getServerSession(authOptions); return <p>{session?.user?.name}</p>; }
Check if the async function is awaited properly.
getServerSession returns a Promise, so it must be awaited in an async function. Here, the component is not async and does not await, causing a runtime error.
Choose the correct statement about accessing sessions on the server in Next.js 14+ with next-auth.
Recall how server components and async data fetching work in Next.js 14+.
In Next.js 14+, getServerSession is async and must be called in server components or server actions. It returns a Promise resolving to the session or null if no session exists. It does not run synchronously in client components, nor is session data injected automatically. Passing request/response is optional depending on setup.