Complete Guide to Authentication in Next.js Using JWT and HTTP-Only Cookies

Amr Samir profile picture
Amr Samir
No Date
7 min read
1245 views
89 likes

Step-by-step tutorial implementing secure authentication in Next.js with JWT, HTTP-only cookies, middleware protection, and CSRF mitigation.

Level:intermediate

Why JWT with HTTP-only Cookies?

When building authentication in Next.js, you have several options for storing tokens. LocalStorage is vulnerable to XSS attacks, while regular cookies can be accessed by JavaScript. HTTP-only cookies provide the best security by:

  • • Being inaccessible to JavaScript
  • • Automatically sent with requests
  • • Protected against CSRF when combined with SameSite and CSRF tokens

Implementation Steps

1. Create a Next.js API route for login that:

  • • Validates credentials
  • • Generates a JWT with user data
  • • Sets an HTTP-only cookie containing the JWT

2. Create middleware to protect routes by verifying the JWT

3. Implement logout by clearing the cookie

// Example login API route
import jwt from 'jsonwebtoken';
import { serialize } from 'cookie';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).end();
  }

  // Validate credentials (pseudo-code)
  const user = await validateUser(req.body);
  if (!user) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  // Create JWT
  const token = jwt.sign(
    { userId: user.id },
    process.env.JWT_SECRET,
    { expiresIn: '1d' }
  );

  // Set HTTP-only cookie
  const cookie = serialize('auth', token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 86400, // 1 day
    path: '/',
  });

  res.setHeader('Set-Cookie', cookie);
  return res.status(200).json({ success: true });
}
Authentication flow diagram

Tags

nextjsjwtcookiesauthenticationsecurityapimiddlewarecsrf
Amr Samir profile picture

Amr Samir

Full-stack developer with 2+ years experience building secure web applications. Specializing in Next.js, Node.js, and authentication systems.