Leaf and Kettle keeps a visitor's cart in a cookie, so a cart needs no account and no database. The tea list renders an Add to cart button for each tea, and the header shows Cart (3); pages read the cart with getCart() from @/lib/cart. Write the Server Actions that change it, in app/cart/actions.ts: addToCart(slug), changeQuantity(slug, quantity), and removeFromCart(slug). Each answers { error: null }, or { error } with a message for the customer, and changes nothing when it answers an error, unless it says otherwise below.
The cookie is named cart (CART_COOKIE), and its value is JSON: an array with one { "slug": "green", "quantity": 2 } per tea, in the order the teas were first added. Nothing else goes in it, not names and not prices: those come from getTea(slug) in @/lib/teas. Set it httpOnly, with sameSite: "lax", path: "/", and a maxAge of 30 days, in seconds. When the cart becomes empty, delete the cookie.
The cookie comes from the browser, so read it as untrusted: a cookie that's missing, isn't JSON, or isn't an array is an empty cart, and any entry that isn't an object with a string slug and a whole-number quantity of at least 1 is dropped. Keep only slug and quantity of each entry you keep.
addToCart(slug) adds one of the tea. A tea getTea doesn't know answers We don't sell that tea., and a tea with no stock Mint tea is sold out. A cart holds at most MAX_PER_TEA (10) of a tea, or its stock when that's lower: at the limit, set the quantity to the limit (an edited cookie may say 99) and answer You can buy up to 3 of Oolong tea.
changeQuantity(slug, quantity) sets the quantity of a tea in the cart. Anything but a whole number of 0 or more answers Choose a whole number of teas.; 0 takes the tea out; more than the limit sets the limit and answers the same message as addToCart; and a tea that has sold out since it was added is taken out, answering its sold-out message. A tea that isn't in the cart, or that getTea doesn't know, changes nothing. removeFromCart(slug) takes the tea out. Setting or deleting a cookie in a Server Action makes Next.js render the page again with the answer, so the header's count follows by itself.
Add Green tea, Add Oolong tea, Add Green tea
→ Set-Cookie: cart=[{"slug":"green","quantity":2},{"slug":"oolong","quantity":1}]; Path=/; Max-Age=2592000; HttpOnly; SameSite=lax
→ Cart (3)
addToCart("mint") → { error: "Mint tea is sold out." }
changeQuantity("oolong", 7) → quantity 3, { error: "You can buy up to 3 of Oolong tea." }
removeFromCart("green"), removeFromCart("oolong") → the cart cookie is deleted
lib/teas.ts, read-only. Import it as @/lib/teas.
export type Tea = { slug: string; name: string; price: number; stock: number };
const teas: Tea[] = [
{ slug: "green", name: "Green tea", price: 4, stock: 30 },
{ slug: "mint", name: "Mint tea", price: 3, stock: 0 },
{ slug: "oolong", name: "Oolong tea", price: 5.5, stock: 3 },
{ slug: "jasmine", name: "Jasmine green", price: 5, stock: 12 },
];
/** Every tea, in the shop's order. */
export async function getTeas(): Promise<Tea[]> {
return teas.map((tea) => ({ ...tea }));
}
/** The tea with this slug, or undefined when the shop doesn't sell it. */
export async function getTea(slug: string): Promise<Tea | undefined> {
const tea = teas.find((entry) => entry.slug === slug);
return tea && { ...tea };
}
lib/cart.ts, read-only. Import it as @/lib/cart.
import { cookies } from "next/headers";
import { getTea } from "@/lib/teas";
/** The cookie that holds the cart. */
export const CART_COOKIE = "cart";
/** The most of one tea a cart can hold. */
export const MAX_PER_TEA = 10;
export type CartItem = { slug: string; name: string; price: number; quantity: number };
/** The visitor's cart, for pages to show: each valid line of the cookie whose tea the shop sells, with its name and price. */
export async function getCart(): Promise<CartItem[]> {
let lines: unknown;
try {
lines = JSON.parse((await cookies()).get(CART_COOKIE)?.value || "[]");
} catch {
return [];
}
if (!Array.isArray(lines)) return [];
const items: CartItem[] = [];
for (const line of lines) {
if (!line || typeof line.slug !== "string" || !Number.isInteger(line.quantity) || line.quantity < 1) continue;
const tea = await getTea(line.slug);
if (tea) items.push({ slug: tea.slug, name: tea.name, price: tea.price, quantity: line.quantity });
}
return items;
}
app/cart-count.tsx, read-only. Import it as @/app/cart-count.
import { getCart } from "@/lib/cart";
export default async function CartCount() {
const cart = await getCart();
const count = cart.reduce((sum, item) => sum + item.quantity, 0);
return <p>Cart ({count})</p>;
}
app/teas/add-to-cart-button.tsx, read-only. Import it as @/app/teas/add-to-cart-button.
"use client";
import { useState, useTransition } from "react";
import { addToCart } from "@/app/cart/actions";
export default function AddToCartButton({ slug, name }: { slug: string; name: string }) {
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
return (
<>
<button
type="button"
aria-label={`Add ${name} to cart`}
disabled={isPending}
onClick={() =>
startTransition(async () => {
const result = await addToCart(slug);
setError(result.error);
})
}
>
Add to cart
</button>
{error && <span role="alert">{error}</span>}
</>
);
}
app/teas/page.tsx, read-only. Import it as @/app/teas/page.
import CartCount from "@/app/cart-count";
import { getTeas } from "@/lib/teas";
import AddToCartButton from "./add-to-cart-button";
export default async function TeasPage() {
const teas = await getTeas();
return (
<>
<header>
<CartCount />
</header>
<main>
<h1>Our teas</h1>
<ul>
{teas.map((tea) => (
<li key={tea.slug}>
{tea.name} <AddToCartButton slug={tea.slug} name={tea.name} />
</li>
))}
</ul>
</main>
</>
);
}
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withRequest({}, async (request) => {
await renderServer(<Page />);
expect(screen.getByText("Cart (0)")).toBeInTheDocument();
await addOn("Green tea");
const { httpOnly, sameSite, path, maxAge } = cartCookie(request) ?? {};
expect({ httpOnly, sameSite, path, maxAge }).toEqual({ httpOnly: true, sameSite: "lax", path: "/", maxAge: 2592000 });
expect(lines(request)).toEqual([{ slug: "green", quantity: 1 }]);
// Next.js renders the page again with the new cookie, in the same response.
cleanup();
await renderServer(<Page />);
expect(screen.getByText("Cart (1)")).toBeInTheDocument();
await addOn("Oolong tea");
await addOn("Green tea");
expect(lines(request)).toEqual([{ slug: "green", quantity: 2 }, { slug: "oolong", quantity: 1 }]);
cleanup();
await renderServer(<Page />);
expect(screen.getByText("Cart (3)")).toBeInTheDocument();
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withCart(inCart([{ slug: "oolong", quantity: 1 }, { slug: "green", quantity: 2 }]), async (request) => {
expect(await addToCart("green")).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 1 }, { slug: "green", quantity: 3 }]);
expect(await addToCart("jasmine")).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 1 }, { slug: "green", quantity: 3 }, { slug: "jasmine", quantity: 1 }]);
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withRequest({}, async (request) => {
await renderServer(<Page />);
await addOn("Mint tea");
expect(screen.getByRole("alert")).toHaveTextContent("Mint tea is sold out.");
expect(await addToCart("coffee")).toEqual({ error: "We don't sell that tea." });
expect(await addToCart("constructor")).toEqual({ error: "We don't sell that tea." });
expect(request.setCookies).toEqual([]);
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withCart({}, async (request) => {
for (let i = 0; i < 3; i++) expect(await addToCart("oolong")).toEqual({ error: null });
expect(await addToCart("oolong")).toEqual({ error: "You can buy up to 3 of Oolong tea." });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 3 }]);
});
await withCart(inCart([{ slug: "green", quantity: 10 }]), async () => {
expect(await addToCart("green")).toEqual({ error: "You can buy up to 10 of Green tea." });
});
// An edited cookie: 99 is cut to the limit.
await withCart(inCart([{ slug: "green", quantity: 99 }]), async (request) => {
expect(await addToCart("green")).toEqual({ error: "You can buy up to 10 of Green tea." });
expect(lines(request)).toEqual([{ slug: "green", quantity: 10 }]);
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withCart(inCart([{ slug: "green", quantity: 2 }, { slug: "oolong", quantity: 1 }]), async (request) => {
expect(await changeQuantity("green", 5)).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "green", quantity: 5 }, { slug: "oolong", quantity: 1 }]);
expect(await changeQuantity("oolong", 7)).toEqual({ error: "You can buy up to 3 of Oolong tea." });
expect(lines(request)).toEqual([{ slug: "green", quantity: 5 }, { slug: "oolong", quantity: 3 }]);
for (const wrong of [2.5, -1, "3", null]) expect(await changeQuantity("green", wrong)).toEqual({ error: "Choose a whole number of teas." });
expect(await changeQuantity("jasmine", 2)).toEqual({ error: null });
expect(await changeQuantity("green", 0)).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 3 }]);
});
await withCart(inCart([{ slug: "green", quantity: 1 }, { slug: "mint", quantity: 2 }]), async (request) => {
expect(await changeQuantity("mint", 1)).toEqual({ error: "Mint tea is sold out." });
expect(lines(request)).toEqual([{ slug: "green", quantity: 1 }]);
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
for (const broken of ["not json", '{"green":2}', "null", "42"]) {
await withCart(inCart(broken), async (request) => {
expect(await addToCart("green")).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "green", quantity: 1 }]);
});
}
const edited = [{ slug: "green", quantity: "2" }, { slug: "oolong", quantity: 1, price: 0 }, { slug: 5, quantity: 1 }, null, { slug: "jasmine", quantity: 0 }, { slug: "mint", quantity: 1.5 }];
await withCart(inCart(edited), async (request) => {
expect(await addToCart("jasmine")).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 1 }, { slug: "jasmine", quantity: 1 }]);
});
const cartCookie = (request) => request.setCookies.find((cookie) => cookie.name === "cart");
const lines = (request) => {
const cookie = cartCookie(request);
if (!cookie) throw new Error("The action didn't set the cart cookie.");
return JSON.parse(cookie.value);
};
const inCart = (value) => ({ cart: typeof value === "string" ? value : JSON.stringify(value) });
// Server Actions run with the browser's cookies: here, the cart given.
const withCart = (cookies, work) => withRequest({ kind: "action", cookies }, work);
const addOn = async (name) => {
await user.click(screen.getByRole("button", { name: "Add " + name + " to cart" }));
await flush();
};
await withCart(inCart([{ slug: "green", quantity: 2 }, { slug: "oolong", quantity: 1 }]), async (request) => {
expect(await removeFromCart("green")).toEqual({ error: null });
expect(lines(request)).toEqual([{ slug: "oolong", quantity: 1 }]);
expect(await removeFromCart("oolong")).toEqual({ error: null });
const cookie = cartCookie(request);
expect(cookie.value).toBe("");
expect(cookie.path ?? "/").toBe("/");
expect(cookie.maxAge === 0 || (cookie.expires !== undefined && new Date(cookie.expires).getTime() <= 0)).toBe(true);
expect(await getCart()).toEqual([]);
});
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with A cart kept in a cookie. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.