Course contentsShow
← Security
Lesson 1074 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Cookie Security Attributes Deep Dive

Mastering Secure, HttpOnly, SameSite, Domain, Path, and Expires attributes for cookie-based storage protection.

Cookie Security Attributes Deep Dive

What you'll learn: How to configure the five critical cookie attributes—Secure, HttpOnly, SameSite, Domain, and Path—to protect cookie-based data from theft and abuse.

Understanding Cookie Attributes

Cookies are just name-value pairs, but their attributes control when, where, and how browsers send them. Without proper configuration, cookies become easy targets for XSS, CSRF, and man-in-the-middle attacks.

Think of cookie attributes as security labels on a package: they tell the delivery system (your browser) exactly how to handle that package safely.

The Five Essential Attributes

Secure: Forces the browser to only send this cookie over HTTPS connections. Without it, attackers on public Wi-Fi can intercept your session tokens in plaintext.

HttpOnly: Prevents JavaScript (document.cookie) from accessing the cookie. This blocks XSS attacks from stealing authentication tokens—even if malicious script executes, it can't read HttpOnly cookies.

SameSite: Controls whether cookies accompany cross-origin requests. SameSite=Strict blocks cookies on all cross-site requests; SameSite=Lax allows them on top-level navigations (clicking links) but not embedded requests; SameSite=None requires Secure and permits all cross-site usage. This is your primary CSRF defense.

Domain: Specifies which hosts can receive the cookie. Setting Domain=example.com allows subdomains like api.example.com to receive it. Omitting this attribute restricts the cookie to the exact host that set it—often the safer choice.

Path: Limits cookies to specific URL paths. Path=/admin means the cookie only sends to URLs starting with /admin. However, this provides minimal security since same-origin JavaScript can still access these cookies.

Expires/Max-Age: Controls cookie lifetime. Session cookies (no expiration) disappear when the browser closes; persistent cookies survive restarts. Shorter lifetimes reduce exposure windows.

Example Configuration

A secure session cookie should look like:

Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict; Path=/; Max-Age=3600

Key Takeaway: Always use Secure and HttpOnly for sensitive cookies, choose the strictest appropriate SameSite value, and carefully scope Domain and Path to minimize attack surface.