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.
EN/CH Mode
Lazy to read articles? Then watch videos!
What is Cookie? Its Working Principle
Cookie is small text data stored by websites in user browsers, which browsers automatically send back to servers in subsequent requests.
Cookie Workflow
1. User visits website
↓
2. Server responds and sets Cookie
Set-Cookie: user_id=123
↓
3. Browser stores Cookie
↓
4. User visits website again
↓
5. Browser automatically sends Cookie
Cookie: user_id=123
↓
6. Server identifies user
Basic workflow:
- 1. Server creates Cookie through Set-Cookie header in HTTP response
- 2. Browser receives and stores Cookie
- 3. Browser automatically sends Cookie through Cookie header in subsequent requests
- 4. Server receives Cookie and uses it to identify users or maintain state
// Backend (Node.js) setting Cookie
res.setHeader('Set-Cookie', [
'user_id=abc123; Max-Age=3600',
'session=xyz789; HttpOnly; Secure'
]);
// When frontend sends request, browser automatically includes Cookie
fetch('https://api.example.com/data', {
credentials: 'include', // Required for cross-origin requests
headers: {
'Content-Type': 'application/json'
}
});
// Cookie header sent by browser
Cookie: user_id=abc123; session=xyz789; theme=dark; lang=en; _ga=GA1.2.1234567890.1234567890
Cookie Attributes and Their Security Implications
Cookie has multiple important attributes that control its behavior and security:
Attribute | Description | Security Implication |
---|---|---|
Expires /Max-Age | Set Cookie expiration time | Limit sensitive information storage time |
Domain | Specify domain to which Cookie can be sent | Prevent unrelated subdomains from accessing Cookie |
Path | Specify URL path where Cookie is available | Limit path scope under same domain |
Secure | Only send Cookie through HTTPS | Prevent man-in-the-middle interception of Cookie |
HttpOnly | Prevent JavaScript from accessing Cookie | Prevent XSS attacks from stealing Cookie |
SameSite | Control strategy for sending Cookie in cross-site requests | Prevent CSRF attacks |
SameSite
is a newer security attribute with three optional values, defaulting to Lax
after Chrome 80:
SameSite Value | Description | Applicable Scenarios |
---|---|---|
Strict | Only same-site requests will send Cookie | Applications with high security requirements, such as banking websites and admin systems |
Lax | Same-site requests and clicking links from external sources (like Google search) will send Cookie, but only for GET requests, POST and other request methods will not send | Balanced choice for most websites, default value after Chrome 80 |
None | Allow cross-site requests to send Cookie (must also set Secure attribute) | Applications requiring cross-site functionality, such as third-party embedded services |
Practical application examples:
Scenario 1: Online banking login Cookie
res.cookie('sessionId', 'abc123', { sameSite: 'strict', secure: true, httpOnly: true });
Ensure authentication Cookie is only sent when users directly visit the banking website, preventing requests from other websites from carrying authentication information
Scenario 2: Social media website
res.cookie('user_session', 'xyz789', { sameSite: 'lax', secure: true, httpOnly: true });
Allow users to maintain login status when clicking links from external sources, but prevent operations like form submissions from third-party websites from carrying Cookie
Scenario 3: Third-party embedded services (like comment systems)
res.cookie('embed_token', 'def456', { sameSite: 'none', secure: true });
Allow Cookie to be sent in cross-site requests, enabling third-party embedded functionality to work properly, but must be transmitted via HTTPS to ensure basic security
Cookie vs localStorage vs sessionStorage
Feature | Cookie | localStorage | sessionStorage |
---|---|---|---|
Capacity Limit | ~4KB | ~5MB | ~5MB |
Expiration Time | Configurable | Permanent | Session End |
HTTP請求 | Auto Send | Not Sent | Not Sent |
Scope | Cross Browser Tabs | Cross Browser Tabs | Current Tab Only |
Use Cases | Session Management Server Needs to Read | Persistent User Preferences Large Data Cache | Form Data Storage One-time Session Data |
Why do websites show Cookie consent prompts?
In recent years, almost all websites pop up 'Accept Cookies' prompts. This is not a website design trend, but due to global privacy regulations, especially the EU's General Data Protection Regulation (GDPR) and ePrivacy Directive.
Core Reasons for Regulatory Requirements
- User Right to Know: Laws require websites to inform users what data they collect and how they use this data.
- Explicit Consent: Before collecting non-essential cookies, explicit user consent (opt-in) must be obtained, not default collection (opt-out).
- Right to Choose: Users have the right to refuse non-essential cookies, and websites must still function normally.
Types of Cookie Consent Prompts
Basic Notification Type
Only notify users that the website uses cookies, continuing to use the website is considered consent. This approach no longer meets regulatory requirements in some regions.
Accept/Reject Choice Type
Provide options to accept or reject all cookies, meeting basic regulatory requirements.
Category Selection Type
Allow users to choose to accept different categories of cookies (such as necessary, functional, analytics, advertising, etc.).
Detailed Management Type
Provide detailed cookie management interface where users can individually control each type of cookie.
Regulatory Differences Across Regions
Region | Main Regulations | Cookie Consent Requirements |
---|---|---|
EU | GDPR, ePrivacy | Explicit consent (opt-in), must provide rejection options |
US | CCPA/CPRA (加州) | Right to know and opt-out rights |
Taiwan | Personal Data Protection Act | Need to inform and obtain consent, but requirements are more relaxed |
Why do global websites show Cookie prompts?
Even if a website is not in the EU, as long as EU users visit, it must comply with GDPR. Due to the global nature of the internet, most websites choose to implement cookie consent mechanisms to ensure global compliance, rather than showing different content for users in different regions. Additionally, as global privacy awareness increases, more and more countries are enacting similar regulations.
For developers, cookie consent mechanisms are not just legal compliance issues, but also a manifestation of respecting user privacy. Implementing good cookie policies helps build user trust while avoiding potential huge fines (up to 4% of global annual revenue or 20 million euros under GDPR).
🔥 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. Server sends Set-Cookie header
- 2. Browser saves Cookie
- 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
Lax (默認)
Same-site requests + top-level navigation
None
All cross-site requests send
// 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));