Which of the following best describes a key difference between JWT and session-based authentication strategies in Next.js?
Think about where the user data is kept in each method.
JWTs store user information encoded in a token on the client side, so the server does not need to keep session data. Sessions keep user data on the server, linked by a session ID stored in a cookie.
Given a Next.js API route that verifies a JWT token from the Authorization header, what will happen if the token is missing or invalid?
export default async function handler(req, res) { const authHeader = req.headers.authorization; if (!authHeader) { return res.status(401).json({ error: 'No token provided' }); } const token = authHeader.split(' ')[1]; try { const user = verifyToken(token); // throws if invalid res.status(200).json({ user }); } catch { res.status(403).json({ error: 'Invalid token' }); } }
Check the condition for missing token before verification.
If the Authorization header is missing, the code returns a 401 error with 'No token provided'. If the token is invalid, it returns 403 with 'Invalid token'.
In a Next.js app using session-based authentication, what will be the value of req.session.user after a user logs out?
export default async function handler(req, res) { if (req.method === 'POST' && req.url === '/logout') { req.session.destroy(); res.status(200).json({ message: 'Logged out' }); } else { res.status(200).json({ user: req.session.user || null }); } }
Consider what happens to session data after calling destroy().
Calling req.session.destroy() removes the session and all its data, so req.session.user will be null or undefined after logout.
Which option correctly verifies a JWT token using the jsonwebtoken library in a Next.js API route?
import jwt from 'jsonwebtoken'; export default function handler(req, res) { const token = req.headers.authorization?.split(' ')[1]; try { // Verify token here } catch (err) { res.status(401).json({ error: 'Unauthorized' }); } }
Which method checks the token signature using a secret?
jwt.verify checks the token's signature using the secret key. jwt.decode only decodes without verifying.
A Next.js API route uses JWT for authentication. The code catches errors during verification but does not distinguish token expiry errors. What is the likely user experience when a token expires?
try { const user = jwt.verify(token, process.env.JWT_SECRET); res.status(200).json({ user }); } catch (err) { res.status(401).json({ error: 'Unauthorized' }); }
Check how errors are handled in the catch block.
The catch block returns a generic 'Unauthorized' error for all verification failures, including expired tokens, so users do not get a specific expiry message.