BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE Interview Notes - HTTP Cookie Explained

In-depth analysis of HTTP Cookie working principles, attribute settings, security considerations and application scenarios. Master core Cookie knowledge for frontend interviews, including SameSite strategy and storage method comparisons.

影片縮圖

Lazy to read articles? Then watch videos!

🔥 Common Interview Questions

(1) What is the basic principle of HTTP Cookie? What are its limitations?

Answer: HTTP Cookie is small text data stored by websites in user browsers.

Working Principle:

  1. 1. Server sends Set-Cookie header
  2. 2. Browser saves Cookie
  3. 3. Subsequent requests automatically include Cookie header

// Server response

HTTP/1.1 200 OK

Set-Cookie: userId=123; Expires=Wed, 21 Oct 2023 07:28:00 GMT

// Subsequent request

GET /api/profile HTTP/1.1

Cookie: userId=123

Main Limitations:

  • 1. Single Cookie size about 4KB
  • 2. Cookie count limit per domain (about 50-180)
  • 3. Cannot access across domains
  • 4. Can be deleted or disabled by users
  • 5. Subject to privacy regulations
  • 6. Increases HTTP request size

(2) What does Cookie's SameSite attribute do? What are the differences between different values?

Answer: The SameSite attribute controls whether cookies are sent in cross-site requests, mainly used to prevent CSRF attacks.

Strict

Only same-site requests send

External link redirects don't carry Cookie

Lax (默認)

Same-site requests + top-level navigation

Clicking links carries Cookie, iframe doesn't

None

All cross-site requests send

Must be used with Secure attribute (HTTPS)

// Strict mode

Set-Cookie: sessionId=abc123; SameSite=Strict

// Lax mode (Chrome default)

Set-Cookie: sessionId=abc123; SameSite=Lax

// Allow cross-site

Set-Cookie: sessionId=abc123; SameSite=None; Secure

(3) What are the use cases for Cookie, localStorage and sessionStorage respectively?

Answer: Three storage mechanisms have different applicable scenarios:

Cookie

  • 1. Automatically sent to server
  • 2. Authentication tokens
  • 3. Cross-tab sharing
  • 4. Can set expiration time
  • 5. Small capacity (~4KB)

document.cookie = "theme=dark; max-age=86400";

localStorage

  • 1. Permanent storage
  • 2. User preference settings
  • 3. Cross-tab sharing
  • 4. Not sent to server
  • 5. Large capacity (~5MB)

localStorage.setItem("theme", "dark");

sessionStorage

  • 1. Current tab only
  • 2. Form temporary data
  • 3. One-time process state
  • 4. Auto-clear when tab closes
  • 5. Large capacity (~5MB)

sessionStorage.setItem("formData", JSON.stringify(data));