Next.js Course
Next.js
/
Beginner

Secure Cookies

Definition

The practice of configuring HTTP cookies with specific flags (`HttpOnly`, `Secure`, `SameSite`) to drastically reduce the attack surface of an application.

Explain Like I'm New

A cookie is just a text file. If you just give it to the browser, JavaScript can read it, hackers can steal it, and other websites can use it. You must add 'Armor' to the cookie.

Real World Example

Storing a JWT authentication token in an `HttpOnly` cookie. This makes it literally impossible for an XSS attack (rogue JavaScript) to read the token.

Common Use Cases

  • •Authentication
  • •Session management
  • •GDPR compliance

Interactive Example

// A perfect, enterprise-grade secure cookie configuration in Next.js
import { cookies } from 'next/headers';

export async function login(token) {
  // 'cookies()' is available inside Server Actions and Route Handlers
  cookies().set('auth_token', token, {
    maxAge: 60 * 60 * 24 * 7, // 1 Week
    
    // SECURITY FLAGS:
    httpOnly: true, // No JS access
    secure: process.env.NODE_ENV === 'production', // HTTPS only in Prod
    sameSite: 'lax', // CSRF protection
    path: '/', // Available across the whole site
  });
}

Interview Questions

basic

  • What does the `HttpOnly` flag do to a cookie?

intermediate

  • What does the `Secure` flag do to a cookie?

Flash Cards

Question

HttpOnly flag?

Click to reveal answer
Answer

It completely hides the cookie from client-side JavaScript. `document.cookie` will not see it. It is ONLY sent in HTTP requests to the server.

Question

Secure flag?

Click to reveal answer
Answer

It ensures the browser will ONLY send the cookie over encrypted HTTPS connections, never over plain HTTP (preventing network interception/packet sniffing).