Course contentsShow
← Web Development
Lesson 805 of 2,98214. Browser StorageFree lesson

Cookie Size Limitations

Browser limits on cookie size (typically 4KB) and total cookies per domain, and strategies to work within them.

Cookie Size Limitations

You'll learn: How browsers restrict cookie size and count, and what to do when you need more storage.

The Size Problem

Browsers impose strict limits on cookies to prevent abuse and keep headers efficient. Each cookie can typically hold only 4KB (4096 bytes) of data, including the name, value, and attributes like expires, path, and domain. Additionally, browsers limit you to around 20-50 cookies per domain (exact number varies by browser).

These limits exist because cookies are sent with every HTTP request to that domain. Hundreds of large cookies would bloat headers and slow down your site significantly.

What Counts Toward the Limit

The entire cookie string counts:

document.cookie = "userData=JohnDoe; path=/; max-age=3600; secure";

That's not just "JohnDoe" — it's the full serialized string including all attributes. Names, values, semicolons, and spaces all consume bytes from your 4KB budget.

Strategies to Work Within Limits

  1. Store references, not data: Save a session ID in the cookie and keep actual data server-side
  2. Compress data: Use shorter key names (u instead of userName)
  3. Use localStorage: For client-side data that doesn't need server access, switch to localStorage (typically 5-10MB limit)
  4. Limit cookie scope: Use specific path attributes so cookies aren't sent with every request
  5. Clean up old cookies: Remove expired or unused cookies with removeItem patterns

If you exceed 4KB, browsers will silently truncate or reject the cookie — no error thrown, just data loss.

Key Takeaway: Cookies are limited to ~4KB each with 20-50 per domain; store only essential data in cookies and use localStorage or server-side storage for larger datasets.