0
0
NextJSframework~10 mins

Server-side session access in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Server-side session access
Client Request
Next.js Server receives request
Parse cookies from request
Retrieve session data using cookie
Use session data in server code
Render page or API response with session info
Send response back to client
The server receives a client request, reads cookies to find session info, accesses session data, and uses it to render the page or API response.
Execution Sample
NextJS
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";

export async function GET(req) {
  const session = await getServerSession({ req }, authOptions);
  return new Response(JSON.stringify({ user: session?.user ?? null }));
}
This code gets the session on the server during a GET request and returns user info in JSON.
Execution Table
StepActionEvaluationResult
1Receive GET requestRequest object contains cookiesRequest ready for processing
2Call getServerSession()Reads cookies from request headersExtracts session token
3Validate session tokenCheck token validity in session storeSession data found or null
4Assign session variablesession = session data or nullsession contains user info or null
5Create response JSONJSON.stringify({ user: session?.user ?? null })JSON string with user or null
6Return ResponseSend JSON back to clientClient receives session user info or null
💡 Session data retrieved or null if no valid session token
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
requndefinedRequest with cookiesRequest with cookiesRequest with cookiesRequest with cookies
sessionundefinedundefinedsession data or nullsession data or nullsession data or null
responseundefinedundefinedundefinedundefinedResponse with JSON string
Key Moments - 2 Insights
Why do we need to read cookies from the request on the server?
Cookies contain the session token needed to identify the user session. Without reading cookies (Step 2), the server cannot find the session data (Step 3).
What happens if the session token is invalid or missing?
The session variable becomes null (Step 3 and 4), so the server knows no user is logged in and can respond accordingly (Step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does the session variable contain after Step 4?
AResponse JSON string
BRequest object
CUser info or null
DCookies only
💡 Hint
Check the 'Result' column for Step 4 in the execution table.
At which step does the server validate the session token?
AStep 3
BStep 2
CStep 5
DStep 6
💡 Hint
Look for 'Validate session token' in the 'Action' column.
If the client sends no cookies, how does the session variable change?
AIt contains user info
BIt becomes null
CIt throws an error
DIt contains cookies
💡 Hint
Refer to the 'Result' in Step 3 and 4 when session token is missing.
Concept Snapshot
Server-side session access in Next.js:
- Server reads cookies from incoming request
- Uses getServerSession() to get session data
- Session can be user info or null if no valid session
- Use session data to render or respond
- Always handle null session safely
Full Transcript
When a client sends a request to a Next.js server, the server reads cookies from the request headers. These cookies contain a session token that identifies the user session. The server calls getServerSession() to extract and validate this token. If valid, it retrieves the session data including user information. If invalid or missing, the session is null. The server then uses this session data to render pages or send API responses. This process ensures the server knows who the user is during server-side rendering or API calls.