Bird
Raised Fist0
NextJSframework~20 mins

Server-side session access in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Server-side Session Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Next.js server component accessing session?

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' } }?

NextJS
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>
  );
}
A<h1>Hello, Alice!</h1>
B<h1>Hello, Guest!</h1>
CError: getServerSession is not a function
D<h1>Hello, undefined!</h1>
Attempts:
2 left
💡 Hint

Check how the session object is accessed and the fallback value used.

📝 Syntax
intermediate
2:00remaining
Which option correctly imports and uses getServerSession in Next.js 14+?

Next.js 14+ requires correct import paths for server session access. Which option shows the correct import and usage of getServerSession?

A
import { getServerSession } from 'next-auth/client';
const session = await getServerSession(authOptions);
B
import { getServerSession } from 'next-auth/server';
const session = await getServerSession(authOptions);
C
import { getServerSession } from 'next-auth/next';
const session = await getServerSession(authOptions);
D
import getServerSession from 'next-auth';
const session = getServerSession(authOptions);
Attempts:
2 left
💡 Hint

Check the official Next.js 14+ documentation for the correct import path.

state_output
advanced
2:00remaining
What is the value of 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' } }?

NextJS
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;
}
A'no-email'
B'bob@example.com'
Cundefined
Dnull
Attempts:
2 left
💡 Hint

Look at the fallback value used when email is missing.

🔧 Debug
advanced
2:00remaining
What error does this Next.js server component raise?

This server component tries to access session but has a bug. What error will it raise?

NextJS
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>;
}
AError: authOptions is undefined
BNo error, renders user name
CError: JSX must be wrapped in a fragment
DError: 'await' is required for getServerSession
Attempts:
2 left
💡 Hint

Check if the async function is awaited properly.

🧠 Conceptual
expert
3:00remaining
Which statement about server-side session access in Next.js 14+ is TRUE?

Choose the correct statement about accessing sessions on the server in Next.js 14+ with next-auth.

AgetServerSession must be called inside a server component or server action and returns a Promise resolving to the session object or null.
BgetServerSession requires passing the HTTP request and response objects explicitly in Next.js 14+.
CSession data is automatically injected into all components without explicit calls to getServerSession.
DgetServerSession can be called directly in client components without async/await and returns session synchronously.
Attempts:
2 left
💡 Hint

Recall how server components and async data fetching work in Next.js 14+.

Practice

(1/5)
1. What is the main purpose of using getServerSession in Next.js?
easy
A. To fetch data from an external API on the client side
B. To handle client-side routing between pages
C. To style components dynamically based on user input
D. To access user session data securely on the server side

Solution

  1. Step 1: Understand the role of getServerSession

    This function is designed to retrieve session information securely on the server side in Next.js.
  2. Step 2: Compare with other options

    Options A, C, and D describe client-side or unrelated tasks, not server-side session access.
  3. Final Answer:

    To access user session data securely on the server side -> Option D
  4. Quick Check:

    Server-side session access = To access user session data securely on the server side [OK]
Hint: Remember: sessions store user info safely on the server [OK]
Common Mistakes:
  • Confusing client-side data fetching with server session access
  • Thinking getServerSession runs on the client
  • Mixing session access with styling or routing
2. Which is the correct way to import getServerSession in a Next.js page?
easy
A. import { getServerSession } from 'next-auth/next';
B. import getServerSession from 'next/server';
C. import { getServerSession } from 'next/router';
D. import { getServerSession } from 'next/head';

Solution

  1. Step 1: Identify the correct import source

    The official Next.js authentication library exports getServerSession from 'next-auth/next'.
  2. Step 2: Check other imports

    Options A, B, and D import from unrelated Next.js modules, causing errors or undefined functions.
  3. Final Answer:

    import { getServerSession } from 'next-auth/next'; -> Option A
  4. Quick Check:

    Correct import path = import { getServerSession } from 'next-auth/next'; [OK]
Hint: Use 'next-auth/next' to import server session helpers [OK]
Common Mistakes:
  • Importing from 'next/server' which lacks session helpers
  • Confusing routing or head modules with auth imports
  • Using default import instead of named import
3. Given this code inside getServerSideProps in Next.js, what will be logged if the user is not logged in?
export async function getServerSideProps(context) {
  const session = await getServerSession(context.req, context.res, authOptions);
  console.log(session);
  return { props: { user: session?.user || null } };
}
medium
A. undefined
B. An object with user details
C. null
D. A runtime error

Solution

  1. Step 1: Understand session when user is not logged in

    If no user is logged in, getServerSession returns null, not undefined or error.
  2. Step 2: Check the code's handling of session

    The code logs session directly, so it logs null. The props user is set to null safely.
  3. Final Answer:

    null -> Option C
  4. Quick Check:

    Session for no user = null [OK]
Hint: No login means session is null, not undefined or error [OK]
Common Mistakes:
  • Assuming session is undefined instead of null
  • Expecting an error when session is missing
  • Confusing logged user object with session presence
4. What is wrong with this Next.js server-side session code?
export async function getServerSideProps(context) {
  const session = getServerSession(context.req, context.res, authOptions);
  if (!session) {
    return { redirect: { destination: '/login', permanent: false } };
  }
  return { props: { user: session.user } };
}
medium
A. Missing await before getServerSession call
B. Redirect destination should be '/home' instead of '/login'
C. session.user is undefined even if session exists
D. getServerSideProps cannot return redirect objects

Solution

  1. Step 1: Check async function usage

    getServerSession returns a Promise, so it must be awaited to get the session object.
  2. Step 2: Analyze the impact of missing await

    Without await, session is a Promise, so the if check fails and code behaves incorrectly.
  3. Final Answer:

    Missing await before getServerSession call -> Option A
  4. Quick Check:

    Async calls need await = Missing await before getServerSession call [OK]
Hint: Always await async session calls in server functions [OK]
Common Mistakes:
  • Forgetting to await async functions
  • Confusing redirect destinations with errors
  • Thinking getServerSideProps can't redirect
5. You want to protect a Next.js page so only logged-in users can access it. Which approach correctly uses getServerSession inside getServerSideProps to redirect unauthenticated users to '/login' and pass user data to the page?
hard
A. export async function getServerSideProps(context) { const session = getServerSession(context.req, context.res, authOptions); if (session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: null } }; }
B. export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; }
C. export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); return { props: { user: session.user } }; }
D. export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session.user) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; }

Solution

  1. Step 1: Check session retrieval and await usage

    export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; } correctly awaits getServerSession to get the session object.
  2. Step 2: Verify redirect logic for unauthenticated users

    export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; } redirects if !session, which means no logged-in user, correctly protecting the page.
  3. Step 3: Confirm user data is passed when session exists

    export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; } returns user data in props only if session exists, enabling page to render user info.
  4. Final Answer:

    export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; } -> Option B
  5. Quick Check:

    Await session + redirect if no session = export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { user: session.user } }; } [OK]
Hint: Await session, redirect if missing, pass user in props [OK]
Common Mistakes:
  • Not awaiting the session Promise
  • Redirecting when session exists instead of missing
  • Checking session.user without confirming session exists