DEV Community

Cover image for Cookies in the Browser: A Complete Guide for Developers
ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Cookies in the Browser: A Complete Guide for Developers

πŸ“‘ Table of Contents

  1. What Are Cookies?
  2. Cookies in JavaScript
  3. Types of Cookies
  4. HTTP vs HTTPS Cookies
  5. Cookies vs LocalStorage vs SessionStorage
  6. Real World Examples of Cookies
  7. 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=/;
Enter fullscreen mode Exit fullscreen mode

πŸ–ΌοΈ 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)
Enter fullscreen mode Exit fullscreen mode

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=/";
Enter fullscreen mode Exit fullscreen mode

2. Reading Cookies

console.log(document.cookie);
// "username=JohnDoe; theme=dark"
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

3. Deleting Cookies

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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;
Enter fullscreen mode Exit fullscreen mode

πŸ–ΌοΈ 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)]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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

  1. Authentication β†’ Session tokens for logged-in users.
  2. E-commerce β†’ Shopping cart persistence across visits.
  3. Personalization β†’ Theme settings, language preferences.
  4. 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)