Box + Cart: KV Sessions That Survive a Refresh
Add a working cart: an anonymous KV session, a validated /api/cart, and a drawer that keeps the box across reloads.
Stage 3 ended with a box selector that only knew about the current page. Stage 4 gives it somewhere to live.
The cart is a KV-backed session, not a database table. The browser keeps an anonymous session token, every request sends it in a header, and the Worker stores the lines under that token. Adding a box, changing a quantity, removing a line, and refreshing the page all hit the same Worker route.
What it is#
Four moving parts:
- A session token in
localStorage, generated by the client. - A KV record per token, written with
kvfromvoid/kv. /api/cartwithGET,POST,PATCH, andDELETE.- A cart drawer that reads the view returned by the API and renders the lines, quantities, and subtotal.
There is no D1 migration in this stage. The cart is intentionally ephemeral. D1 gets involved when the cart becomes an order in stage 5.
Why you'd care#
A storefront that loses the box on refresh is a demo. A cart needs four guarantees:
- The server owns the price. A client can send
size: 6, but it cannot send$1.00. - The line is validated against the current menu and the known box sizes.
- The same flavor and box size merge into one line with a quantity.
- The selection survives a reload, a second tab, and a return tomorrow.
KV is the right shape for this data: small JSON values, keyed by an anonymous token, with a TTL. Checkout is the transaction that needs D1.
The session#
The token is a UUID. The client creates it once, stores it in localStorage, and sends it as x-jumble-cart.
export const CART_HEADER = "x-jumble-cart";
export const CART_STORAGE_KEY = "jumble.cart.session";
export const CART_TTL_SECONDS = 60 * 60 * 24 * 30;
export function isCartToken(value: unknown): value is string {
return typeof value === "string" && CART_TOKEN_PATTERN.test(value);
}
function ensureCartToken(): string {
const stored = window.localStorage.getItem(CART_STORAGE_KEY);
if (isCartToken(stored)) return stored;
const token = createCartToken();
window.localStorage.setItem(CART_STORAGE_KEY, token);
return token;
}
async function requestCart(token: string, init?: RequestInit): Promise<CartView> {
const response = await fetch("/api/cart", {
...init,
credentials: "same-origin",
headers: {
"content-type": "application/json",
[CART_HEADER]: token,
},
});
return response.json();
}
This is why the embedded preview works without relying on a third-party cookie. localStorage belongs to the Jumble origin; the API is on the same origin. A cookie would be simpler in a first-party app, but it is the wrong dependency for a lesson that has to run inside an iframe.
The token is a capability, not authentication. Anyone who knows it can change that cart. That is acceptable for an anonymous box; stage 7 adds the account boundary.
The KV record#
export type CartLine = {
slug: string;
size: number;
quantity: number;
};
export type CartRecord = {
lines: CartLine[];
};
import { kv } from "void/kv";
import { z } from "zod";
const carts = kv.map<unknown>("carts");
const cartRecordSchema = z.object({
lines: z
.array(
z.object({
slug: z.string().min(1).max(120),
size: z.number().int().positive(),
quantity: z.number().int().min(1).max(12),
}),
)
.max(24),
});
export async function readCart(token: string): Promise<CartRecord> {
const parsed = cartRecordSchema.safeParse(await carts.get(token));
return parsed.success ? normalizeLines(parsed.data.lines) : emptyCartRecord();
}
export async function writeCart(token: string, record: CartRecord) {
await carts.put(token, record, { ttl: 60 * 60 * 24 * 30 });
}
Importing kv from void/kv is enough for Void to infer and provision the KV binding. Local dev gets a file-backed namespace; void deploy creates the production namespace.
The API#
routes/api/cart.ts exports one handler per method. The GET path returns the enriched view. The write paths validate the body, load the record, mutate it, and return the same view.
export const GET = defineHandler(async (c) => {
const token = cartToken(c);
if (!token) return emptyCartView();
const menu = await getActiveMenu();
return present(token, await readCart(token), menu);
});
export const POST = defineHandler(async (c) => {
const token = cartToken(c);
if (!token) return c.json({ error: "Start a cart session first." }, 400);
const body = await readBody(() => c.req.json(), addSchema);
if (!body) return c.json({ error: "Invalid cart item." }, 400);
const menu = await getActiveMenu();
const flavor = menu.flavors.find((item) => item.slug === body.slug);
const box = BOX_SIZES.find((item) => item.size === body.size);
if (!flavor || !box) {
return c.json({ error: "That cookie or box is not on this week's menu." }, 409);
}
const record = await readCart(token);
const line = record.lines.find(
(item) => item.slug === flavor.slug && item.size === box.size,
);
if (line) {
line.quantity = Math.min(line.quantity + body.quantity, 12);
} else {
record.lines.push({ slug: flavor.slug, size: box.size, quantity: body.quantity });
}
await writeCart(token, record);
return present(token, record, menu);
});
PATCH replaces a quantity; DELETE removes a line. Both return the fresh cart. The client never renders a price it invented.
The present() helper turns stored lines into display lines:
const flavor = flavorsBySlug.get(line.slug);
const box = boxesBySize.get(line.size);
if (!flavor || !box) continue;
lines.push({
key: cartLineKey(line.slug, line.size),
slug: flavor.slug,
name: flavor.name,
size: box.size,
boxLabel: box.label,
quantity: line.quantity,
priceCents: box.priceCents,
lineTotalCents: box.priceCents * line.quantity,
color: flavor.color,
accent: flavor.accent,
});
That is also the prune step. A cookie that leaves the menu disappears from the cart instead of becoming an unpriced ghost.
The drawer#
The cookie page's button changes from a disabled stage-3 placeholder to a real action:
async function addToBox(): Promise<void> {
if (!props.flavor || !selectedBox.value || adding.value) return;
adding.value = true;
const success = await add(props.flavor.slug, selectedBox.value.size);
adding.value = false;
if (success) {
added.value = true;
openCart();
}
}
The drawer is a single client component teleported to body. It is rendered only after mount so its modal markup does not fight SSR hydration.
<article v-for="line in cart.lines" :key="line.key" class="cart-line">
<span class="cart-swatch" :style="{ background: line.color }" />
<div class="cart-line-info">
<h3>{{ line.name }}</h3>
<p>{{ line.boxLabel }} · {{ line.size }} cookies</p>
<button :disabled="busy" @click="emit('remove', line)">Remove</button>
</div>
<div class="cart-line-side">
<p>{{ price(line.lineTotalCents) }}</p>
<div class="cart-qty">
<button :disabled="busy || line.quantity <= 1" @click="emit('update', line, line.quantity - 1)">−</button>
<span>{{ line.quantity }}</span>
<button :disabled="busy || line.quantity >= 12" @click="emit('update', line, line.quantity + 1)">+</button>
</div>
</div>
</article>
The current app shows the cart trigger in the menu and cookie headers, opens the drawer after an add, and keeps the count live. Checkout stays disabled. That is the next stage's problem.
Do it yourself#
No migration.
pnpm dev
Open:
http://localhost:5173/
http://localhost:5173/cookies/sorrel-snickerdoodle
http://localhost:5173/preview/4
Add a box, raise the quantity, close the drawer, and refresh. The line should still be there. Remove it and the empty state returns.
Deploy:
void deploy --platform cloudflare
Void provisions the KV namespace and writes the binding during deploy. The D1 migrations are still up to date.
The live stage#
The preview above is /preview/4, embed mode, first cookie. Add a box and the drawer opens inside the iframe. The full app at / shows the cart trigger in the menu header and the same cart on every cookie page.
Stage 3 is still available at /preview/3 with no cart and the add button disabled. That is the point of the stage route: the old stage does not receive later features.
Gotchas#
- Never trust a client price. The API accepts a slug, size, and quantity; the price comes from
BOX_SIZES. - Validate against the active menu. A cookie that is no longer on the menu fails the add and is pruned from stored carts.
- KV is eventually consistent. Two tabs can overwrite each other if they mutate at the same instant. For a single-user, low-stakes cart this is fine; an order transaction belongs in D1.
- The token is not auth. Anyone with the token can edit the cart. Do not put personal data in KV under it.
- localStorage is the session here. Cookies would be more conventional first-party, but third-party cookie blocking makes them unreliable inside the lesson iframe. The token-in-header approach works in both places.
- The drawer is client-only. Teleporting during SSR causes hydration noise; mount it first.
- Do not build checkout early. Stage 5 adds pickup slots, validation, and the D1 order. The disabled checkout button is honest.
Recap#
The box now survives: a KV session, a validated API, server-owned prices, and a live drawer. The app has a cart but not an order.
Next: Pickup + Checkout — pickup locations and slots, form validation, and the first D1 order.