๐—ก๐—ฒ๐˜…๐˜.๐—ท๐—ฆ ๐—”๐˜‚๐˜๐—ต๐—ฒ๐—ป๐˜๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐˜„๐—ถ๐˜๐—ต ๐—๐—ช๐—ง

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:

  1. User logs in with email and password.
  2. Server checks credentials.
  3. Server creates a JWT.
  4. Server stores the token in an HTTP-only cookie.
  5. Middleware checks the token for protected routes.

Step 1: Setup Install these tools:

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.

Source: https://dev.to/synfinity-dynamics-pvt-ltd/nextjs-authentication-with-jwt-complete-guide-for-secure-login-in-2026-3cmk