๐ก๐ฒ๐ ๐.๐ท๐ฆ ๐๐๐๐ต๐ฒ๐ป๐๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป ๐๐ถ๐๐ต ๐๐ช๐ง
Authentication secures your web application. You need it for SaaS, e-commerce, or AI tools to protect user data.
This guide shows you how to build JWT authentication in Next.js. You will use the App Router, Route Handlers, Middleware, and HTTP-only cookies.
What is JWT? JSON Web Token (JWT) is a way to send user information between a client and a server. It has three parts: Header, Payload, and Signature.
Why use JWT?
- It is stateless.
- It is fast to verify.
- It scales easily.
- It works well with APIs and microservices.
The Workflow:
- User enters email and password.
- Server checks credentials.
- Server creates a JWT.
- Server stores the token in an HTTP-only cookie.
- Middleware verifies the token for protected routes.
Implementation Steps:
Install dependencies: npm install jsonwebtoken bcryptjs
Set a secret in your .env.local: JWT_SECRET=your_long_random_secret
Create a login route: Use Route Handlers to validate users. When valid, sign a token and set it as an HTTP-only cookie.
Protect routes with Middleware: Use a middleware.ts file. This file checks for the token before a user reaches a page. If no token exists, redirect them to the login page.
Create a logout route: Clear the cookie by setting its expiration to the past.
Security Rules:
- Do not store tokens in localStorage. Use HTTP-only cookies to stop XSS attacks.
- Always use secure: true in production.
- Use short expiration times like 1 day or 2 hours.
- Use long, random secrets.
- Always verify tokens on the server. Never trust the client.
For high security, use short-lived access tokens and long-lived refresh tokens.
JWT vs Sessions:
- JWT is stateless and scales better.
- Sessions require server storage.
- JWT is better for APIs and microservices.
Build a strong foundation for your next project by following these steps.