Shipmind Labs

Why a consent cookie sheds its oldest decisions before it writes

· 9 min read

A cookie is the only place a server can read a consent answer before any script runs, so a consent library that cares about the first response has to write one. It is also storage with two silent failure modes. A value past roughly four kilobytes is not rejected, it is simply not set, and a cookie write raises no event that another open tab could hear. From the calling code both failures look exactly like success, so the store gets built around them instead of around the happy path.

This is the cookieStore in consentcore, our GDPR consent library. The design question it answers is narrow, and worth stating precisely: what do you drop when the record you have to keep is larger than the place you have to keep it.

The record is a log, and a log grows#

Consent has to be demonstrable. Not "is marketing allowed" as a boolean, but which answer was given, when, and against which version of the notice. A decision recorded against an older notice is a decision to a different question, and restore does not carry it forward. So the stored value is a log of decisions, and the log keeps superseded entries on purpose, because deleting them would lose the one thing the record exists to prove.

A log that only grows and a container with a hard ceiling are in direct conflict, and the ceiling is not negotiable. Set a cookie whose name and value exceed the browser's limit and nothing happens. No exception, no rejected promise, no truncated value you could at least detect. The next read returns the previous value, or nothing. A store that ignores this writes a full history on a developer's machine, then quietly stops recording anything on the account that has been answering notices for three years.

Trim from the oldest end, and measure what you actually write#

typescript
const put = (log: readonly Decision[]): void => {
  const document = jar();
  if (!document) return;
  if (!log.length) {
    document.cookie = `${key}=; ${attributes(0)}`;
    return;
  }

  // A cookie over the size limit is not rejected, it is silently not set. The
  // oldest decisions go rather than the answer the visitor is living under.
  const keep = [...log];
  let encoded = encodeURIComponent(JSON.stringify(keep));
  while (keep.length > 1 && key.length + encoded.length > limit) {
    keep.shift();
    encoded = encodeURIComponent(JSON.stringify(keep));
  }
  if (key.length + encoded.length > limit) return;
  // ...
};

Three things in there are load-bearing.

The loop re-encodes after every shift instead of estimating. encodeURIComponent over JSON is not a small constant factor you can predict: quotes, braces and colons each become three characters, so a log of ISO timestamps and category arrays expands substantially, and by an amount that depends on the content. The only honest measurement of a cookie's size is the string you are about to assign.

key.length is in the comparison because the browser stores a pair. The name counts against the same budget as the value, so a project that renames the cookie for namespacing has just made its own history shorter. limit defaults to COOKIE_LIMIT, which is 4000, under the practical 4096 so the attributes have room.

The loop stops at one entry. Trimming is there for history, and it does not get to reach the decision the visitor is currently living under. If that single newest decision still does not fit, put writes nothing at all, and the caller is told, which is the subject of the last section.

The expiry comes from the decision, not from a constant#

typescript
const last = keep[keep.length - 1];
const seconds = Math.max(
  0,
  Math.round((Date.parse(expiresAt(last, months)) - now().getTime()) / 1000),
);
document.cookie = `${key}=${encoded}; ${attributes(seconds)}`;

expiresAt adds CONSENT_MONTHS, thirteen, to the decision's own timestamp. Deriving Max-Age from that rather than from a fixed thirteen months from now means the browser expires the record on the same schedule the code does. A tab left open for a year cannot refresh a cookie past the answer's life, and a record restored from a backup does not get a new lease by being written again.

Math.max(0, ...) is not defensive padding. A decision already past the window produces zero, the browser drops the cookie immediately, and that is precisely the behaviour the expiry rule wants. It is the same outcome as the explicit case where an empty log writes the key with Max-Age=0 to delete it. One arithmetic clamp instead of a branch.

The window rule itself lives with the decision logic rather than with the store, and that separation matters once anyone implements their own Store: restore re-checks both the thirteen-month window and the notice match, so a store that keeps the record forever still cannot keep a lapsed answer alive.

The attributes are deliberately unexciting: Path=/, SameSite=Lax, Secure on by default, Domain only when given. Secure by default has a consequence worth knowing. A plain-http origin drops the cookie entirely, which is one more way a write silently does not happen.

localStorage tells the other tabs for free. Cookies tell nobody. A visitor with two tabs open who withdraws consent in one of them has, as far as the other tab is concerned, changed nothing, and that tab is still running the tags that answer granted.

typescript
write(log) {
  put(fresh(log, now(), months));
  channel.announce();
},

The default channel is storageChannel on the key suffixed .sync. It holds no consent data, only a value built from Date.now and a tick counter, so the value comes out different from the last one every time. That counter exists because browsers do not fire a storage event when a key is written with the value it already had, and two writes inside the same millisecond would otherwise go unheard.

typescript
subscribe(listener) {
  const target = eventsOf(options.events);
  if (!target) return () => {};
  const handler = (event: StorageEvent) => {
    if (event.key === null || event.key === key) listener();
  };
  target.addEventListener("storage", handler);
  return () => target.removeEventListener("storage", handler);
},

A null key means storage was cleared, which is also news. The listener receives no payload, and the other tab re-reads the cookie. Keeping the signal empty is deliberate: the cookie is the authority, and a sync key carrying a copy of the decision is a second record that can disagree with the first.

The caller reads the record back#

Everything above still leaves cases where the write does not land: a single decision too large for the limit, Secure on a plain-http origin, cookies disabled, or no document at all because the code is rendering on a server, where put returns without writing rather than throwing.

So nothing reports success from having attempted a write. useConsent reads the store back after each write and reports persisted as false when the newest decision did not land. That is a flag a banner can act on (keep itself open, fall back to another store, log it) instead of a boolean that means "we called document.cookie and it did not throw", which is the only thing the platform would otherwise tell you.

read closes the same loop in the other direction. It parses the value out of the other cookies on the jar, applies the freshness rule, and rewrites the cookie when anything was dropped, so a lapsed entry leaves the browser the moment it is first noticed rather than at the next decision.

The reason to pay for a cookie at all is the server, and that path applies the same two rules in the same order:

typescript
export function readCookieHeader(
  header: string | null | undefined,
  options: CookieHeaderOptions,
): State {
  const stored = parse(cookieValue(header ?? "", options.key ?? "consent"));
  const keep = fresh(stored, options.now?.() ?? new Date(), options.months ?? CONSENT_MONTHS);
  return restore(keep.length ? keep : null, options);
}

Pure, and nothing handed to it can make it throw. A header that is absent, truncated, hand-edited or not JSON at all reads as undecided. The value came from the client, and undecided is the only safe reading of a record that cannot be read. The payoff is a first response that already knows the answer, so nothing has to be rendered as undecided and corrected once a script runs.

What it costs to run#

The cookie is not where a long consent history lives. By construction it holds the current answer plus as much history as fits, and on a busy record the older end is gone. If the history is evidence you have to produce, it belongs somewhere without a four-kilobyte ceiling. In consentcore that is the hash-chained proof document, with anchors kept outside it, a separate mechanism for a separate job.

The per-write cost is a JSON serialization and a percent-encode per trim iteration, bounded by the number of decisions in the log, which is small. Cross-tab notification depends on localStorage even though the record does not, so a browser that blocks it gets a working cookie and no live updates. subscribe returns a no-op function rather than pretending otherwise.

None of this is clever. It is the ordinary consequence of writing to a medium whose failures are silent. Measure the thing you are actually about to write, decide in advance which part of the data gives way, and read the record back instead of trusting the write.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com