Bird
Raised Fist0
NextJSframework~10 mins

JWT vs session strategy in NextJS - Visual Side-by-Side Comparison

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
Concept Flow - JWT vs session strategy
User logs in
Server verifies credentials
Create JWT token
Send JWT to client
Client stores JWT
Client sends JWT
Server verifies JWT
Access granted or denied
Logout clears JWT or session
This flow shows how user login leads to either JWT token creation or server session creation, how the client stores and sends them, and how the server verifies them for access.
Execution Sample
NextJS
async function login(req, res) {
  const { username, password } = req.body;
  if (validUser(username, password)) {
    const token = createJWT(username);
    res.json({ token });
  } else {
    res.status(401).end();
  }
}
This code logs in a user, creates a JWT token if valid, and sends it to the client.
Execution Table
StepActionInput/StateOutput/State ChangeNotes
1Receive login requestusername='alice', password='1234'Request receivedStart login process
2Validate credentialsCheck username and passwordValid userCredentials match
3Create JWT tokenusername='alice'JWT token createdToken contains user info
4Send token to clientJWT tokenClient receives tokenClient stores token locally
5Client sends token with requestJWT token in headerServer receives tokenToken used for auth
6Server verifies tokenJWT tokenToken validAccess granted
7LogoutClient deletes tokenToken invalidated client-sideSession ends
8Session strategy alternativeUser logs inServer creates session and cookieSession stored server-side
9Client sends cookieSession cookieServer checks sessionAccess granted if session valid
10LogoutClient deletes cookieSession destroyed server-sideSession ends
💡 Process ends after logout or failed validation
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 6Final
usernameundefined'alice''alice''alice''alice'undefined
passwordundefined'1234''1234''1234''1234'undefined
validUserfalsetruetruetruetruefalse
tokenundefinedundefined'jwt_token_string''jwt_token_string''jwt_token_string'undefined
sessionundefinedundefinedundefinedundefinedundefinedsession object or undefined
Key Moments - 2 Insights
Why does JWT store user info on the client while sessions keep it on the server?
JWT tokens are self-contained and include user info, so the server just verifies the token signature (see execution_table step 3 and 6). Sessions store data on the server, so the client only holds a session ID cookie (see step 8 and 9).
What happens if the JWT token is stolen?
Since JWT is stored client-side and sent with requests (step 5), if stolen, it can be used until it expires. Sessions can be invalidated server-side immediately (step 10), offering more control.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the JWT token created?
AStep 3
BStep 2
CStep 5
DStep 8
💡 Hint
Check the 'Action' column for 'Create JWT token'
According to variable_tracker, what is the value of 'validUser' after step 2?
Afalse
Btrue
Cundefined
D'jwt_token_string'
💡 Hint
Look at the 'validUser' row under 'After Step 2'
If the client deletes the JWT token, what happens next according to the flow?
AServer creates a new token automatically
BSession is destroyed server-side
CAccess is denied on next request
DClient sends session cookie instead
💡 Hint
Refer to concept_flow step 'Logout clears JWT or session'
Concept Snapshot
JWT vs Session Strategy

- JWT stores user info in a token sent to client.
- Sessions store user info on server, client holds session ID cookie.
- JWT verification is stateless; sessions require server memory.
- JWT tokens expire; sessions can be destroyed anytime.
- Choose JWT for scalability; sessions for control and security.
Full Transcript
This visual execution compares JWT and session strategies in Next.js authentication. The flow starts with user login, then either a JWT token is created and sent to the client, or a session is created and stored on the server with a cookie sent to the client. The client stores and sends these tokens or cookies with requests. The server verifies JWT tokens by checking their signature, or checks sessions by looking up stored data. Logout clears tokens or sessions. The execution table traces each step from login to logout, showing state changes. The variable tracker follows key variables like username, password, validUser, token, and session through the process. Key moments clarify why JWT stores info client-side while sessions keep it server-side, and the security implications if tokens are stolen. The quiz tests understanding of when tokens are created, variable states, and logout effects. The snapshot summarizes the main differences and use cases for JWT and sessions.

Practice

(1/5)
1. What is a key difference between JWT and session strategies in Next.js authentication?
easy
A. JWT stores user info on the client, sessions store it on the server
B. JWT requires server storage, sessions do not
C. Sessions are better for scaling across devices than JWT
D. JWT tokens expire immediately after login

Solution

  1. Step 1: Understand JWT storage

    JWT stores user information inside a token on the client side, allowing stateless authentication.
  2. Step 2: Understand session storage

    Sessions keep user information on the server, maintaining state and control centrally.
  3. Final Answer:

    JWT stores user info on the client, sessions store it on the server -> Option A
  4. Quick Check:

    Storage location difference = B [OK]
Hint: Remember: JWT = client, session = server [OK]
Common Mistakes:
  • Thinking sessions store data on client
  • Believing JWT requires server storage
  • Confusing scaling benefits
2. Which code snippet correctly initializes a session in Next.js using a session strategy?
easy
A. const session = localStorage.getItem('session');
B. const token = jwt.sign(payload, secret);
C. import { getSession } from 'next-auth/react'; const session = await getSession();
D. import jwt from 'jsonwebtoken'; const token = jwt.verify(tokenString, secret);

Solution

  1. Step 1: Identify session initialization

    Using 'getSession' from 'next-auth/react' is the correct way to get session data in Next.js.
  2. Step 2: Check other options

    Options B and D relate to JWT token creation and verification, not sessions. const session = localStorage.getItem('session'); uses localStorage, which is client-side and not a session strategy.
  3. Final Answer:

    import { getSession } from 'next-auth/react'; const session = await getSession(); -> Option C
  4. Quick Check:

    Session retrieval uses getSession() [OK]
Hint: Sessions use getSession(), JWT uses jwt.sign() [OK]
Common Mistakes:
  • Confusing JWT token code with session code
  • Using localStorage as session storage
  • Missing async/await with getSession
3. Given this Next.js API route using JWT, what will be the response if the token is expired?
import jwt from 'jsonwebtoken';
export default function handler(req, res) {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    jwt.verify(token, process.env.JWT_SECRET);
    res.status(200).json({ message: 'Access granted' });
  } catch (err) {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}
medium
A. 200 with message 'Access granted'
B. 401 with error 'Invalid or expired token'
C. 500 server error
D. 403 forbidden without message

Solution

  1. Step 1: Understand jwt.verify behavior

    If the token is expired, jwt.verify throws an error caught by the catch block.
  2. Step 2: Check catch block response

    The catch block sends a 401 status with error message 'Invalid or expired token'.
  3. Final Answer:

    401 with error 'Invalid or expired token' -> Option B
  4. Quick Check:

    Expired token triggers 401 error [OK]
Hint: Expired JWT triggers catch block with 401 [OK]
Common Mistakes:
  • Assuming expired token returns 200
  • Confusing 403 and 401 status codes
  • Missing try-catch around jwt.verify
4. Identify the bug in this Next.js session handling code snippet:
import { getSession } from 'next-auth/react';
export default async function handler(req, res) {
  const session = getSession();
  if (!session) {
    res.status(401).json({ error: 'Not authenticated' });
  } else {
    res.status(200).json({ message: 'Welcome!' });
  }
}
medium
A. Missing await before getSession()
B. Using getSession() instead of getServerSession()
C. No error handling for session retrieval
D. Incorrect status code for authenticated user

Solution

  1. Step 1: Check the context

    This is a Next.js API route (server-side).
  2. Step 2: Identify correct function for server-side

    While getServerSession() is recommended for server-side session retrieval, the immediate bug in the code is missing await before the async getSession() call, causing session to be a Promise instead of resolved value.
  3. Final Answer:

    Missing await before getSession() -> Option A
  4. Quick Check:

    Async function requires await to get session value [OK]
Hint: Async calls need await [OK]
Common Mistakes:
  • Forgetting await on async functions
  • Confusing getSession and getServerSession
  • Ignoring promise returned by getSession
5. You want to build a Next.js app that supports multiple devices per user and scales easily without server state. Which strategy fits best and why?
hard
A. Use sessions because they store data on the server for better control
B. Use sessions with database storage for multi-device support
C. Use JWT but store tokens only on the server
D. Use JWT because tokens store user info on client, enabling stateless scaling

Solution

  1. Step 1: Analyze multi-device and scaling needs

    Supporting multiple devices and easy scaling requires stateless authentication without server session storage.
  2. Step 2: Match strategy to needs

    JWT stores user info in tokens on the client, allowing stateless, scalable authentication across devices.
  3. Final Answer:

    Use JWT because tokens store user info on client, enabling stateless scaling -> Option D
  4. Quick Check:

    Stateless multi-device = JWT [OK]
Hint: Stateless multi-device apps use JWT [OK]
Common Mistakes:
  • Choosing sessions for stateless scaling
  • Thinking JWT tokens must be stored on server
  • Assuming sessions easily scale without extra setup