π Table of Contents
- What Are Cookies?
- Cookies in JavaScript
- Types of Cookies
- HTTP vs HTTPS Cookies
- Cookies vs LocalStorage vs SessionStorage
- Real World Examples of Cookies
- Conclusion
πͺ Cookies in the Browser: A Complete Guide for Developers
When you visit a website, it often needs to remember information about you β whether it's your login session, shopping cart items, or theme preferences. Thatβs where cookies come in.
Cookies are small pieces of data stored in the browser by websites. They play a crucial role in user experience, personalization, and security.
πΉ What Are Cookies?
A cookie is a small text file that a website stores in your browser. Each cookie typically contains a key-value pair and metadata such as expiration date, path, domain, and security attributes.
- Size Limit: ~4KB per cookie
- Number of cookies per domain: ~20β50 depending on browser
- Scope: Bound by domain and path rules
π Example cookie string:
username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/;
πΌοΈ Cookie Lifecycle (Diagram)
sequenceDiagram
participant Browser
participant Server
Browser->>Server: HTTP Request (no cookies yet)
Server-->>Browser: HTTP Response + Set-Cookie: session=abc123
Browser->>Browser: Store cookie in browser storage
Browser->>Server: HTTP Request (includes Cookie: session=abc123)
Server-->>Browser: Response (user is authenticated)
This flow shows how cookies are set, stored, and sent back with requests.
πΉ Cookies in JavaScript
JavaScript provides the document.cookie
API to create, read, and delete cookies.
1. Creating and Setting Cookies
// Set a cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/";
2. Reading Cookies
console.log(document.cookie);
// "username=JohnDoe; theme=dark"
To fetch a specific cookie:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
3. Deleting Cookies
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
π Expiration date in the past deletes the cookie.
πΉ Types of Cookies
Type | Description | Example Use Case |
---|---|---|
Session | Temporary; deleted when browser closes | Login session |
Persistent | Stored with an expiry date | βRemember meβ login |
Secure | Sent only over HTTPS | Bank website |
HttpOnly | Inaccessible via JavaScript | Prevent XSS attacks |
SameSite | Restrict cross-site sending | CSRF protection |
πΉ HTTP vs. HTTPS Cookies
HTTP Cookies
- Sent over unencrypted HTTP connections
- Vulnerable to Man-in-the-Middle attacks
- Only suitable for non-sensitive data
HTTPS Cookies
- Sent over encrypted HTTPS connections
- Use Secure and HttpOnly flags for better protection
Example: Setting a Secure Cookie
Set-Cookie: sessionToken=abc123; Secure; HttpOnly; Path=/; Expires=Fri, 31 Dec 2024 12:00:00 GMT;
πΌοΈ Cookie Security Attributes (Diagram)
flowchart TD
A[Cookie] -->|Secure| B[Only sent over HTTPS]
A -->|HttpOnly| C[Not accessible via JavaScript]
A -->|SameSite=Lax| D[Sent only for same-site requests]
A -->|SameSite=None| E[Cross-site allowed (must be Secure)]
πΉ Cookies vs LocalStorage vs SessionStorage
Feature | Cookies | LocalStorage | SessionStorage |
---|---|---|---|
Size Limit | ~4KB | ~5β10MB | ~5β10MB |
Expiration | Manual / session-based | Persistent until cleared | Cleared when tab closed |
Sent with requests? | β Yes | β No | β No |
Security | Can be Secure/HttpOnly | Accessible via JS | Accessible via JS |
Use Case | Auth tokens, sessions | Preferences, caching | Temporary tab data |
πΉ Real World Examples of Cookies
- Authentication β Session tokens for logged-in users.
- E-commerce β Shopping cart persistence across visits.
- Personalization β Theme settings, language preferences.
- Analytics & Tracking β Google Analytics, ads tracking.
πΉ Conclusion
Cookies are essential to modern web apps for managing sessions, personalization, and security. But they come with risks β so always:
β
Use HttpOnly + Secure for sensitive cookies
β
Apply SameSite policies
β
Avoid storing sensitive info like passwords in cookies
β
Keep cookies lightweight
By handling cookies correctly, you can build secure, reliable, and user-friendly applications.
Top comments (0)