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
- Store references, not data: Save a session ID in the cookie and keep actual data server-side
- Compress data: Use shorter key names (
uinstead ofuserName) - Use localStorage: For client-side data that doesn't need server access, switch to
localStorage(typically 5-10MB limit) - Limit cookie scope: Use specific
pathattributes so cookies aren't sent with every request - Clean up old cookies: Remove expired or unused cookies with
removeItempatterns
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.