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?