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
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.