Authentication——4 min read

JWT Authentication with HttpOnly Cookies in Next.js

A practical look at authentication architecture in the Next.js App Router, including sessions, HttpOnly cookies, authorization boundaries, and protected routes.

Laptop computer in a dark environment displaying application code

Authentication in web applications frequently suffers from a deceptive simplicity. Creating a login form that checks a username and password against a database takes less than an hour. However, building an authentication architecture that securely maintains sessions, protects server operations, enforces role permissions, and guards sensitive data across the Next.js App Router requires deliberate architectural choices.

A frequent debate in the modern React ecosystem is where to store session tokens: in browser localStorage or inside HttpOnly cookies. Storing tokens in localStorage makes them trivially accessible to client-side JavaScript, leaving sessions vulnerable to Cross-Site Scripting (XSS) token exfiltration. In contrast, HttpOnly cookies provide a secure foundation by preventing client-side scripts from reading session tokens while automatically attaching credentials to server requests.

Authentication versus authorization

Before writing authentication code, it is vital to distinguish between authentication and authorization: two distinct concerns that are frequently conflated.

**Authentication** answers *who the user is*. It verifies identity through credentials (such as an email and password hash) and issues a cryptographically signed session token. **Authorization** answers *what that user is permitted to do*. It evaluates whether the authenticated identity holds the requisite role or permission to view a report, update payroll records, or delete a customer account.

Keeping these concerns distinct ensures that modifying a user's permissions does not require re-issuing identity credentials or scattering authorization logic across user interface components.

The login workflow: token generation and cookie configuration

When a user submits credentials to a Next.js Server Action or Route Handler, the server validates the input using Zod, verifies the password against its bcrypt hash in MariaDB/MySQL, and constructs a signed JSON Web Token (JWT). The token payload contains essential, non-sensitive identity claims: user ID, email, and designated role.

typescript
// Setting secure session cookies in Next.js Server Actions
import { cookies } from "next/headers";
import jwt from "jsonwebtoken";

export async function loginUser(credentials: LoginCredentials) {
  // 1. Verify user credentials against database
  const user = await verifyCredentials(credentials);
  if (!user) throw new Error("Invalid email or password");

  // 2. Sign JWT with server-side private secret
  const token = jwt.sign(
    { sub: user.id, email: user.email, role: user.role },
    process.env.JWT_SECRET!,
    { expiresIn: "7d" }
  );

  // 3. Set HttpOnly cookie with strict security flags
  const cookieStore = await cookies();
  cookieStore.set("auth_session", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7 // 7 days
  });

  return { success: true };
}

Understanding cookie security attributes

The security of this pattern relies on configuring cookie attributes properly:

• **httpOnly: true:** Prevents browser-side JavaScript (including malicious third-party scripts or compromised dependencies) from accessing document.cookie. This prevents token theft via basic XSS injection.

• **secure: true:** Guarantees that cookies are only transmitted over encrypted HTTPS connections in production, preventing token sniffing over public Wi-Fi networks.

• **sameSite: 'lax':** Provides defense against Cross-Site Request Forgery (CSRF) by ensuring that session cookies are omitted on cross-site subrequests (such as unauthorized images or forms embedded on third-party sites), while permitting normal top-level navigation.

Enforcing authorization at the server boundary

A common mistake in Next.js applications is relying on frontend checks—such as conditionally rendering a button with {user.role === 'ADMIN' && <DeleteButton />}—as a security measure. Client-side rendering conditions enhance user experience, but they provide zero security.

Any user can inspect network requests and submit POST requests directly to server endpoints. In platforms like the HRM Platform and Karmayogi School, every sensitive server operation validates the session token and verifies the caller's role independently before executing queries.

typescript
// Enforcing role checks inside a protected Server Action
export async function updateEmployeeSalary(employeeId: string, newSalary: number) {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_session")?.value;

  if (!token) {
    throw new Error("UNAUTHORIZED: Session token required");
  }

  const session = verifyJwt(token);
  if (session.role !== "HR_ADMIN" && session.role !== "SUPER_ADMIN") {
    throw new Error("FORBIDDEN: Insufficient permissions for salary mutation");
  }

  // Proceed with authorized business operation
  return await executeSalaryUpdate(employeeId, newSalary);
}

Limits of HttpOnly cookies and CSRF considerations

While HttpOnly cookies mitigate direct token theft, they do not automatically solve all web security challenges. Because the browser attaches cookies automatically to outgoing requests, applications must still protect against Cross-Site Request Forgery (CSRF). Pairing SameSite=lax or SameSite=strict cookies with custom request headers (such as X-Requested-With) or anti-CSRF tokens ensures robust request validation.

Furthermore, JWTs are stateless by default. If a user's role is demoted or an account is suspended, a stateless token remains valid until its expiration timestamp. In production business platforms, we implement token revocation lists or verify an account's tokenVersion counter in the database during sensitive actions.

Conclusion and architectural takeaways

Authentication architecture is dependable when responsibilities are clearly bounded: use HttpOnly cookies for safe token transport, verify JWT signatures on the server, enforce role authorization at every database mutation boundary, and treat frontend UI conditions as visual conveniences rather than security barriers.

Dipesh Thapa

Dipesh Thapa

Full-Stack Engineer based in Nepal, specializing in Next.js, TypeScript, Prisma, and high-performance server architectures.

Related posts

Browse all articles

Get engineering
notes

Technical case studies, engineering lessons, and notes from building real-world digital products and systems.

Logo icon

Occasional deep-dives into software architecture, database performance, payment integration, and engineering practices.

No spam · Unsubscribe anytime