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
Implementing JWT vs Session Strategy in Next.js
📖 Scenario: You are building a simple Next.js app that needs user authentication. You want to compare two common ways to keep users logged in: using JSON Web Tokens (JWT) stored in cookies, and using server-side sessions.This project will guide you through setting up both strategies step-by-step so you can see how each works in a real app.
🎯 Goal: Build a Next.js app with two authentication methods: JWT stored in cookies and server-side sessions. You will create the data, configure settings, implement the core logic for each method, and complete the setup to handle user login state.
📋 What You'll Learn
Create initial user data and basic Next.js API routes
Add configuration variables for JWT secret and session options
Implement JWT token creation and verification logic
Implement session creation and retrieval logic
Complete API routes to handle login and authentication using both strategies
💡 Why This Matters
🌍 Real World
Web apps often need to keep users logged in securely. JWT and session strategies are two popular ways to do this. This project shows how to implement both in Next.js.
💼 Career
Understanding authentication methods is essential for web developers building secure applications. Knowing how to implement JWT and sessions is a common job requirement.
Progress0 / 4 steps
1
DATA SETUP: Create initial user data and API route
Create a constant users as an array with one user object: { id: 1, username: 'user1', password: 'pass123' }. Then create a Next.js API route handler function handler that accepts req and res parameters.
NextJS
Hint
Think of users as a small database of one user. The handler function will be your API endpoint.
2
CONFIGURATION: Add JWT secret and session options
Add a constant JWT_SECRET with the value 'mysecretkey'. Also add a constant sessionOptions as an object with a property cookieName set to 'nextjs-session'.
NextJS
Hint
The JWT_SECRET is used to sign tokens. The sessionOptions will hold session cookie settings.
3
CORE LOGIC: Implement JWT token creation and session handling
Inside the handler function, write code to check if req.method is 'POST'. If so, find the user in users matching req.body.username and req.body.password. If user is found, create a JWT token signed with JWT_SECRET containing the user's id. Also create a session object with the user's id. Set a cookie named sessionOptions.cookieName with the session id. Return a JSON response with the token and a success message.
NextJS
Hint
Use jsonwebtoken to create the token. Store sessions in a simple object. Set the cookie with HttpOnly for security.
4
COMPLETION: Finalize API route to verify JWT and session
Extend the handler function to handle GET requests. For GET, check for a JWT token in the Authorization header. Verify it using jwt.verify with JWT_SECRET. Also check for a session cookie named sessionOptions.cookieName and verify it exists in sessions. Return JSON with authenticated: true and the user id if either JWT or session is valid. Otherwise, return authenticated: false.
NextJS
Hint
Check the Authorization header for a Bearer token. Also parse cookies to find the session cookie. Verify both to authenticate the user.
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
Step 1: Understand JWT storage
JWT stores user information inside a token on the client side, allowing stateless authentication.
Step 2: Understand session storage
Sessions keep user information on the server, maintaining state and control centrally.
Final Answer:
JWT stores user info on the client, sessions store it on the server -> Option A
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
Step 1: Identify session initialization
Using 'getSession' from 'next-auth/react' is the correct way to get session data in Next.js.
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.
Final Answer:
import { getSession } from 'next-auth/react'; const session = await getSession(); -> Option C
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?
B. Using getSession() instead of getServerSession()
C. No error handling for session retrieval
D. Incorrect status code for authenticated user
Solution
Step 1: Check the context
This is a Next.js API route (server-side).
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.
Final Answer:
Missing await before getSession() -> Option A
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
Step 1: Analyze multi-device and scaling needs
Supporting multiple devices and easy scaling requires stateless authentication without server session storage.
Step 2: Match strategy to needs
JWT stores user info in tokens on the client, allowing stateless, scalable authentication across devices.
Final Answer:
Use JWT because tokens store user info on client, enabling stateless scaling -> Option D
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