Bird
Raised Fist0
NextJSframework~20 mins

Session management 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
🎖️
Session Mastery
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 with session check?

Consider this Next.js 14 server component that checks for a user session and renders accordingly.

import { cookies } from 'next/headers';

export default async function Page() {
  const cookieStore = cookies();
  const session = cookieStore.get('session-token');

  if (!session) {
    return <h1>Please log in</h1>;
  }

  return <h1>Welcome back!</h1>;
}

What will this component render if the 'session-token' cookie is missing?

NextJS
import { cookies } from 'next/headers';

export default async function Page() {
  const cookieStore = cookies();
  const session = cookieStore.get('session-token');

  if (!session) {
    return <h1>Please log in</h1>;
  }

  return <h1>Welcome back!</h1>;
}
A<h1>Welcome back!</h1>
BRenders nothing (empty page)
C<h1>Please log in</h1>
DThrows a runtime error because cookies() is undefined
Attempts:
2 left
💡 Hint

Think about what happens when the cookie named 'session-token' is not found.

state_output
intermediate
2:00remaining
What is the value of the session state after this client component runs?

Given this Next.js client component using useState and useEffect to fetch session data:

import { useState, useEffect } from 'react';

export default function SessionStatus() {
  const [session, setSession] = useState(null);

  useEffect(() => {
    fetch('/api/session')
      .then(res => res.json())
      .then(data => setSession(data.session));
  }, []);

  return <div>{session ? 'Logged in' : 'Not logged in'}</div>;
}

If the API returns {"session": "user123"}, what will be displayed after the fetch completes?

NextJS
import { useState, useEffect } from 'react';

export default function SessionStatus() {
  const [session, setSession] = useState(null);

  useEffect(() => {
    fetch('/api/session')
      .then(res => res.json())
      .then(data => setSession(data.session));
  }, []);

  return <div>{session ? 'Logged in' : 'Not logged in'}</div>;
}
ALogged in
BNot logged in
CDisplays 'null'
DThrows a fetch error
Attempts:
2 left
💡 Hint

Consider what happens when session state is updated with a non-null string.

📝 Syntax
advanced
2:00remaining
Which option correctly sets a cookie with HttpOnly and Secure flags in Next.js API route?

In a Next.js API route, you want to set a cookie named 'session-token' with value 'abc123' that is HttpOnly and Secure. Which code snippet is correct?

NextJS
export default function handler(req, res) {
  // set cookie here
  res.status(200).json({ success: true });
}
Ares.setHeader('Set-Cookie', 'session-token=abc123; HttpOnly; Secure; Path=/');
Bres.cookie('session-token', 'abc123', { httpOnly: true, secure: true });
Cres.setCookie('session-token', 'abc123', { httpOnly: true, secure: true });
Dres.headers.set('Set-Cookie', 'session-token=abc123; HttpOnly; Secure');
Attempts:
2 left
💡 Hint

Remember that Next.js API routes use Node.js res object and setting headers directly is common.

🔧 Debug
advanced
2:00remaining
Why does this Next.js middleware fail to read the session cookie?

Examine this Next.js middleware code:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const session = request.cookies.get('session-token');
  if (!session) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

It always redirects to '/login' even when the cookie exists. Why?

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const session = request.cookies.get('session-token');
  if (!session) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
AThe cookie is HttpOnly and cannot be read in middleware
BThe cookie name is case-sensitive and should be 'Session-Token' instead
CThe 'request.cookies' API is only available in API routes, not middleware
DMiddleware runs before cookies are parsed; use 'request.headers.get("cookie")' instead
Attempts:
2 left
💡 Hint

Think about how cookies are accessed in Next.js middleware.

🧠 Conceptual
expert
2:00remaining
Which statement best explains why storing session data in client-side cookies is risky?

Why is it generally unsafe to store sensitive session data directly in client-side cookies?

ACookies expire immediately after the browser closes, so data is lost too soon
BCookies can be easily read and modified by the user, risking data tampering and theft
CCookies are encrypted by default, so storing sensitive data is safe
DCookies cannot be sent with HTTPS requests, so session data is exposed
Attempts:
2 left
💡 Hint

Consider who can access cookies stored on the client side.

Practice

(1/5)
1. What is the main purpose of session management in Next.js applications?
easy
A. To remember user information between page visits
B. To style components dynamically
C. To optimize image loading
D. To handle API request routing

Solution

  1. Step 1: Understand session management concept

    Session management is about keeping track of user data across different pages or visits.
  2. Step 2: Identify the main purpose in Next.js

    Next.js uses session management to remember users, so they don't have to log in repeatedly or lose their data.
  3. Final Answer:

    To remember user information between page visits -> Option A
  4. Quick Check:

    Session management = Remember user info [OK]
Hint: Sessions keep user info across pages and visits [OK]
Common Mistakes:
  • Confusing session management with styling or routing
  • Thinking sessions optimize images
  • Believing sessions handle API routing only
2. Which of the following is the correct way to get the session on the server side in Next.js?
easy
A. const session = useSession();
B. const session = getServerSession();
C. const session = fetchSession();
D. const session = getSessionClient();

Solution

  1. Step 1: Recall server-side session retrieval method

    In Next.js, the function getServerSession() is used on the server to get the current session.
  2. Step 2: Check each option for correctness

    const session = useSession(); uses useSession(), which is client-side only. Options B and D are not valid Next.js functions.
  3. Final Answer:

    const session = getServerSession(); -> Option B
  4. Quick Check:

    Server session = getServerSession() [OK]
Hint: Use getServerSession() on server, useSession() on client [OK]
Common Mistakes:
  • Using useSession() on the server side
  • Assuming fetchSession() is a Next.js function
  • Confusing client and server session methods
3. Given this Next.js client component code snippet, what will be the output if the user is not logged in?
import { useSession } from 'next-auth/react';

export default function Profile() {
  const { data: session } = useSession();
  if (!session) return <p>Please log in</p>;
  return <p>Welcome, {session.user.name}</p>;
}
medium
A. <p>Please log in</p>
B. <p>Welcome, undefined</p>
C. Error: session is undefined
D. <p>Welcome, Guest</p>

Solution

  1. Step 1: Analyze the session check in the component

    The code checks if session is falsy (not logged in), then returns <p>Please log in</p> immediately.
  2. Step 2: Determine output when user is not logged in

    Since the user is not logged in, session is null or undefined, so the component returns <p>Please log in</p>.
  3. Final Answer:

    <p>Please log in</p> -> Option A
  4. Quick Check:

    Not logged in shows 'Please log in' [OK]
Hint: If no session, component returns 'Please log in' [OK]
Common Mistakes:
  • Assuming session.user.name exists when session is null
  • Expecting an error instead of conditional return
  • Thinking it shows 'Welcome, Guest' by default
4. Identify the error in this Next.js server-side session code:
import { getServerSession } from 'next-auth/next';

export async function getServerSideProps(context) {
  const session = await getServerSession(context);
  if (!session) {
    return { redirect: { destination: '/login', permanent: false } };
  }
  return { props: { user: session.user } };
}
medium
A. Returning props instead of redirect is incorrect
B. Using await without async function
C. Redirect destination should be '/home' not '/login'
D. Missing passing context to getServerSession

Solution

  1. Step 1: Check getServerSession usage

    The function getServerSession requires the request context to access cookies and headers, so it needs context.req and context.res or the full context passed.
  2. Step 2: Identify missing argument

    The code calls getServerSession() without arguments, which causes it to fail to read session data.
  3. Final Answer:

    Missing passing context to getServerSession -> Option D
  4. Quick Check:

    getServerSession needs context argument [OK]
Hint: Always pass context to getServerSession on server [OK]
Common Mistakes:
  • Forgetting to pass context to getServerSession
  • Confusing async/await usage
  • Incorrect redirect destination assumptions
5. You want to protect a Next.js page so only logged-in users can access it. Which approach correctly combines server and client session checks?
hard
A. Use getServerSession in the component to check session and redirect if missing.
B. Only use useSession in the component to check if user is logged in and redirect if not.
C. Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info.
D. Use useSession in getServerSideProps to fetch session and redirect unauthenticated users.

Solution

  1. Step 1: Understand server-side protection

    Using getServerSession in getServerSideProps allows redirecting users before the page loads if they are not logged in.
  2. Step 2: Understand client-side session usage

    Using useSession in the component helps show loading states or user info once the page is loaded.
  3. Step 3: Evaluate options

    Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. correctly combines server-side redirect and client-side session display. The other options misuse server/client functions or locations.
  4. Final Answer:

    Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. -> Option C
  5. Quick Check:

    Server redirect + client session hook = Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. [OK]
Hint: Protect server-side, then show session client-side [OK]
Common Mistakes:
  • Trying to use client hooks on server
  • Not redirecting unauthenticated users server-side
  • Using server functions inside components