Session management helps keep track of who a user is while they use your website. It lets the site remember the user between pages or visits.
Session management in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.status(200).json({ message: `Hello, ${session.user.name}` }); } else { res.status(401).json({ message: 'Not authenticated' }); } }
Use getServerSession to get the current user's session on the server side.
authOptions contains your authentication settings and must be imported from your NextAuth config.
Examples
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.end(`User email: ${session.user.email}`); } else { res.end('No session found'); } }
useSession hook on the client side to show user info or ask them to log in.NextJS
import { useSession } from 'next-auth/react'; export default function Profile() { const { data: session } = useSession(); if (!session) return <p>Please log in to see your profile.</p>; return <p>Welcome, {session.user.name}!</p>; }
Sample Program
This API route checks if a user session exists. If yes, it greets the user by name. If not, it returns a 401 error saying the user is not authenticated.
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.status(200).json({ message: `Hello, ${session.user.name}` }); } else { res.status(401).json({ message: 'Not authenticated' }); } }
Important Notes
Sessions are usually stored in cookies to keep users logged in across pages.
Always protect sensitive routes by checking the session on the server side.
Use HTTPS to keep session cookies secure.
Summary
Session management remembers users between pages or visits.
Use getServerSession on the server and useSession on the client.
Always check sessions to protect private data and pages.
Practice
1. What is the main purpose of session management in Next.js applications?
easy
Solution
Step 1: Understand session management concept
Session management is about keeping track of user data across different pages or visits.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.Final Answer:
To remember user information between page visits -> Option AQuick 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
Solution
Step 1: Recall server-side session retrieval method
In Next.js, the functiongetServerSession()is used on the server to get the current session.Step 2: Check each option for correctness
const session = useSession(); usesuseSession(), which is client-side only. Options B and D are not valid Next.js functions.Final Answer:
const session = getServerSession(); -> Option BQuick 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
Solution
Step 1: Analyze the session check in the component
The code checks ifsessionis falsy (not logged in), then returns <p>Please log in</p> immediately.Step 2: Determine output when user is not logged in
Since the user is not logged in,sessionis null or undefined, so the component returns <p>Please log in</p>.Final Answer:
<p>Please log in</p> -> Option AQuick 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
Solution
Step 1: Check getServerSession usage
The functiongetServerSessionrequires the request context to access cookies and headers, so it needscontext.reqandcontext.resor the full context passed.Step 2: Identify missing argument
The code callsgetServerSession()without arguments, which causes it to fail to read session data.Final Answer:
Missing passing context to getServerSession -> Option DQuick 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
Solution
Step 1: Understand server-side protection
UsinggetServerSessioningetServerSidePropsallows redirecting users before the page loads if they are not logged in.Step 2: Understand client-side session usage
UsinguseSessionin the component helps show loading states or user info once the page is loaded.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.Final Answer:
Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. -> Option CQuick 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
