0
0
NextJSframework~10 mins

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

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