Understanding Cookie Sizing and Chunking: A Supabase Dilemma

Understanding Cookie Sizing and Chunking: A Supabase Dilemma

While working on our app (at Nexel), we encountered a peculiar bug with Supabase where it was generating duplicate auth cookies - one chunked and the other not. This bug led me to explore cookie sizing and chunking in order to understand why one cookie was chunked and the other not. Although I won't delve into the bug's specifics here, those curious about it can find more information in the Github issue.

An HTTP Cookie, also known as a web or browser cookie, is a small piece of data sent from a server to the user's web browser. The browser may store it and send it back with subsequent requests to the same server. Cookies are primarily used to recognize requests from the same browser, facilitating functionalities like session management (user logins, shopping carts etc.), personalization, and tracking.

Size Matters

The size of a cookie is not determined by the length of its content (like I had wrongly assumed) but by the space it occupies, capped at 4,096 bytes (4KB). This includes the cookie's name, value, and attributes. This means the auth cookie Supabase generates has to be within this limit.

Supabase was generating three cookies named: sb-prefix-auth-token, sb-prefix-auth-token.0 and sb-prefix-auth-token.1.

sb-prefix-auth-token was a single cookie that contained all the necessary auth information. While sb-prefix-auth-token.0 and sb-prefix-auth-token.1 had the auth information split between them. Their sizes were 3,216 bytes and 244 bytes, totaling 3,460 bytes - well within the 4KB limit. This raised the question: Why were they chunked if they didn't exceed the size limit?

Upon investigation, I found that Supabase sets its maximum chunk size to 3,180 bytes[1]. However, the reasoning behind this specific limit remains unclear, as there's no documentation or discussion in their codebase explaining this choice. Interestingly, this limit was initially set higher at 3,600 bytes before being reduced to 3,180 bytes shortly after.

I wondered if this is related to browser limitations, but a quick search revealed that most browsers support cookies of at least 4KB. So, the mystery continues.

Well, I could keep digging but that’s as far down the rabbit hole as time allows. If anyone has insights into Supabase's decision to chunk cookies at less than 4KB, I'd love to hear from you!

A Note on Cookie Chunking

It's worth mentioning that the .0 and .1 suffixes in the cookie names serve a practical purpose - they indicate the order in which the cookie chunks should be merged, with .0 preceding .1.

Learn more about cookies here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

[1] https://github.com/supabase/auth-helpers/blob/84ef39c4a498a94717660842a20df3d10b86c794/packages/ssr/src/utils/chunker.ts#L6