JWT and session strategies help keep users logged in safely. They decide how your app remembers who you are.
JWT vs session strategy in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
JWT: Store user info in a token sent to client.
Session: Store user info on server, client keeps session ID cookie.JWT tokens are usually stored in localStorage or cookies on the client.
Sessions keep data on the server and use cookies to identify the user.
// JWT example const token = jwt.sign({ userId: 123 }, 'secretKey'); // Send token to client // Client sends token in Authorization header fetch('/api/data', { headers: { Authorization: `Bearer ${token}` } });
// Session example // Server stores session data req.session.userId = 123; // Client gets a cookie with session ID // Client sends cookie automatically on requests
This Next.js API route creates a JWT token when a user logs in. It shows how to sign a token and send it back. The commented part shows a simple session setup idea.
import { NextResponse } from 'next/server'; import jwt from 'jsonwebtoken'; const SECRET = 'mysecret'; export async function POST(request) { const { username } = await request.json(); // Create JWT token const token = jwt.sign({ username }, SECRET, { expiresIn: '1h' }); // Return token in JSON return NextResponse.json({ token }); } // Example session setup (pseudo-code) // import session from 'next-session'; // export async function handler(req, res) { // await session(req, res); // req.session.user = { username: 'user1' }; // res.end('Session set'); // }
JWT tokens are stateless and do not require server storage, making them good for scaling.
Sessions store data on the server, which can be safer but need more server resources.
Always keep your secret keys safe and use HTTPS to protect tokens and cookies.
JWT stores user info in a token on the client, good for scaling and multi-device use.
Sessions keep user info on the server, good for security and control.
Choose based on your app needs: ease of scaling vs. control and security.
Practice
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 AQuick Check:
Storage location difference = B [OK]
- Thinking sessions store data on client
- Believing JWT requires server storage
- Confusing scaling benefits
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 CQuick Check:
Session retrieval uses getSession() [OK]
- Confusing JWT token code with session code
- Using localStorage as session storage
- Missing async/await with getSession
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' });
}
}Solution
Step 1: Understand jwt.verify behavior
If the token is expired, jwt.verify throws an error caught by the catch block.Step 2: Check catch block response
The catch block sends a 401 status with error message 'Invalid or expired token'.Final Answer:
401 with error 'Invalid or expired token' -> Option BQuick Check:
Expired token triggers 401 error [OK]
- Assuming expired token returns 200
- Confusing 403 and 401 status codes
- Missing try-catch around jwt.verify
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!' });
}
}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 AQuick Check:
Async function requires await to get session value [OK]
- Forgetting await on async functions
- Confusing getSession and getServerSession
- Ignoring promise returned by getSession
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 DQuick Check:
Stateless multi-device = JWT [OK]
- Choosing sessions for stateless scaling
- Thinking JWT tokens must be stored on server
- Assuming sessions easily scale without extra setup
