0
0
NextJSframework~20 mins

Session management in NextJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.