How to fix cookie size exceeded error by splitting cookies
A solution for cookie size exceeded error: split the cookie into multiple smaller cookies and reconstruct them on the server side. This solution works especially well for serverless platforms without requiring additional infrastructure.
TL;DR: When your cookie size exceeds the 4KB browser limit, split it into multiple smaller cookies and reconstruct them on the server side. This solution works especially well for serverless platforms without requiring additional infrastructure.
Cookie usage in Logto SDKs
In most of the Logto SDKs for traditional web apps, we store session data in HTTP-only cookies for security. Here's our approach:
When the SDK performs actions that require session data, it:
- Encrypts it using symmetric encryption
- Stores the encrypted string in an HTTP-only cookie
- Sets secure flags to ensure HTTPS-only transmission
This approach requires no external storage and can be deployed directly to popular serverless platforms like Vercel without any additional infrastructure changes.
The problem: Cookie size exceeded error
However, when implementing multi-organization support, we hit a limitation. Our cookie size grew beyond the 4KB browser limit because we needed to store:
- Sign in and other session data
- ID tokens for user authentication
- Refresh tokens
- Access tokens with different resource indicators
- Organization tokens which is in JWT with payload, one per organization, which can be quite large for the case that multiple organizations are alive at the same time
This resulted in the error:
Browsers enforce strict cookie size limits, with most limiting individual cookies to 4KB and total cookie size to 8KB per domain.
What about using external storage?
Using external storage like Redis or a database would require additional infrastructure setup, increasing both costs and complexity for SDK users. This goes against our goal of providing a developer-friendly solution.
While in-memory storage could be an alternative, it doesn't work well for serverless environments where instances are ephemeral and memory is not shared between requests.
The solution: Cookie splitting
A simple solution is to split large cookies into smaller chunks. This article demonstrates the approach using Next.js as an example:
1. Split the session data
2. Store the chunks
3. Reconstruct on request
Best practices for implementation
1. Chunk size management
2. Clean session management
Monitor total cookie size:
Conclusion
Cookie splitting offers an elegant solution that's both easy to implement and minimally disruptive to existing application architecture. By simply breaking down large cookies into smaller chunks, developers can overcome browser size limitations without changing their core session management approach or adding external dependencies.