๐ก๐ฒ๐ ๐.๐ท๐ฆ ๐๐๐๐ต๐ฒ๐ป๐๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป ๐๐ถ๐๐ต ๐๐ช๐ง
Authentication keeps your users safe. You need it for SaaS, e-commerce, or any web app.
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 data securely. It has three parts: โข Header โข Payload โข Signature
The server signs the token. If anyone changes the data, the token becomes invalid.
Why use JWT? โข It is stateless. โข It verifies fast. โข It scales easily. โข It works well with APIs.
The Secure Workflow:
- User logs in with email and password.
- Server checks credentials.
- Server creates a JWT.
- Server stores the token in an HTTP-only cookie.
- Middleware checks the token for protected routes.
Step 1: Setup Install these tools:
- jsonwebtoken
- bcryptjs
Set a secret key in your .env.local file. Use a long, random string.
Step 2: The Login Route Create a POST handler in app/api/auth/login/route.ts. This code validates the user and signs the token.
Crucial: Set the cookie with these settings: โข httpOnly: true โข secure: true โข sameSite: strict
Step 3: Middleware Protection Use middleware.ts to guard your routes. If the token is missing or invalid, redirect the user to the login page. This prevents unauthorized access to pages like /dashboard.
Step 4: Logout Create a logout route that clears the cookie by setting its expiration to the past.
Security Rules to Follow: โข Do not store tokens in localStorage. This leads to XSS attacks. โข Always use HTTP-only cookies. โข Always verify tokens on the server side. โข Set short expiration times. โข Use strong secrets.
JWT is better for APIs and microservices. Sessions are better for simple web apps. For modern Next.js apps, JWT with cookies is a top choice.