0
0
NextJSframework~5 mins

JWT vs session strategy in NextJS

Choose your learning style9 modes available
Introduction

JWT and session strategies help keep users logged in safely. They decide how your app remembers who you are.

You want users to stay logged in across many devices without server checks.
You want to keep user info on the server for better control and security.
You need to build a simple login system for a small app.
You want to build a scalable app that works well with many servers.
You want to easily share login info between different parts of your app.
Syntax
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.

Examples
This example shows creating a JWT token and sending it to the client. The client sends it back in requests.
NextJS
// 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}` } });
This example shows storing user info in a server session. The client only keeps a cookie with the session ID.
NextJS
// Session example
// Server stores session data
req.session.userId = 123;
// Client gets a cookie with session ID
// Client sends cookie automatically on requests
Sample Program

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.

NextJS
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');
// }
OutputSuccess
Important Notes

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.

Summary

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.