Skip to the code

Checkout steps that remember progress in a cookie

Leaf and Kettle's checkout has three pages, /checkout/address, /checkout/delivery, and /checkout/review. Write their Server Actions in app/checkout/actions.ts. Until the order is placed, the customer's progress lives in a checkout cookie, so a reload, the Back button, or a second tab doesn't lose it.

The cookie's value is JSON, { address, delivery }, with whatever has been saved so far. Set it with httpOnly: true, secure: true, sameSite: "lax", path: "/checkout", since only the checkout pages need it and their Server Actions are posted to them, and an hour's maxAge, in seconds. Each step keeps what the cookie already holds and adds its own part. A cookie that isn't a JSON object counts as nothing saved.

saveAddress(previous, formData) reads name, street, city, and postcode, each trimmed. For each empty one, the error is Enter your name., Enter your street., Enter your city., or Enter your postcode.; return { errors } with all of them, and set nothing. Otherwise save the address and redirect to /checkout/delivery.

saveDelivery(previous, formData): without a valid address in the cookie, redirect to /checkout/address. The delivery field must be standard or express, or it returns { errors: { delivery: "Choose standard or express delivery." } }. Otherwise save it and redirect to /checkout/review.

placeOrder() is the review page's Place order button. The cookie is the customer's to edit, so trust nothing in it. Read it again: if its address isn't valid, meaning one of the four fields isn't a string with something besides spaces, redirect to /checkout/address; if its delivery isn't exactly standard or express, to /checkout/delivery.

Then total the cart from getCart() in @/lib/cart, quantity × unitPrice cents for each line, plus DELIVERY_FEES[delivery] from @/lib/orders; anything else in the cookie, a total included, is ignored. Call createOrder({ address, delivery, total }) with only the address's four fields, delete the cookie on the path it was set on (on any other path, the browser keeps it), and redirect to /orders/<id>.

saveAddress  → checkout={"address":{"name":"Ana","street":"1 Leaf Lane",…}} → /checkout/delivery
saveDelivery → checkout={"address":{…},"delivery":"express"}              → /checkout/review
placeOrder   → createOrder({ address, delivery: "express", total: 1750 })  // 2 × 400 + 500 + 450
             → checkout deleted on path /checkout                          → /orders/o_1

The app's other files

lib/cart.ts, read-only. Import it as @/lib/cart.

export type CartLine = { slug: string; name: string; quantity: number; unitPrice: number };
 
/** The customer's cart, prices in cents: a stand-in for the shop's database. */
export const cart: CartLine[] = [
  { slug: "green", name: "Green tea", quantity: 2, unitPrice: 400 },
  { slug: "oolong", name: "Oolong tea", quantity: 1, unitPrice: 500 },
];
 
export async function getCart(): Promise<CartLine[]> {
  return cart.map((line) => ({ ...line }));
}

lib/orders.ts, read-only. Import it as @/lib/orders.

export type Address = { name: string; street: string; city: string; postcode: string };
export type Delivery = "standard" | "express";
 
/** What each delivery costs, in cents. */
export const DELIVERY_FEES: Record<Delivery, number> = { standard: 0, express: 450 };
 
export type Order = { id: string; address: Address; delivery: Delivery; total: number };
 
/** Every order placed: a stand-in for the shop's database. */
export const orders: Order[] = [];
 
export async function createOrder(details: Omit<Order, "id">): Promise<Order> {
  const order = { id: `o_${orders.length + 1}`, ...details };
  orders.push(order);
  return { ...order };
}

What the tests check

  1. saveAddress keeps the address in the checkout cookie, then moves on to delivery
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    await step(undefined, async (request) => {
      const where = await redirectOf(() => saveAddress(blank, formData({ name: " Ana ", street: "1 Leaf Lane", city: "Kettleby ", postcode: "KT1 2AB" })));
      expect(where.url).toBe("/checkout/delivery");
      const cookie = saved(request);
      expect(JSON.parse(cookie.value)).toEqual({ address });
      const { httpOnly, secure, sameSite, path, maxAge } = cookie;
      expect({ httpOnly, secure, sameSite, path, maxAge }).toEqual({ httpOnly: true, secure: true, sameSite: "lax", path: "/checkout", maxAge: 3600 });
    });
    
  2. saveAddress returns an error for every empty field and sets no cookie
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    await step(undefined, async (request) => {
      const state = await saveAddress(blank, formData({ name: "Ana", street: "   ", city: "" }));
      expect(state).toEqual({ errors: { street: "Enter your street.", city: "Enter your city.", postcode: "Enter your postcode." } });
      expect(request.setCookies).toEqual([]);
    });
    
  3. saveDelivery adds the choice to what the cookie holds, and going back keeps it
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    await step({ address }, async (request) => {
      const where = await redirectOf(() => saveDelivery(blank, formData({ delivery: "express" })));
      expect(where.url).toBe("/checkout/review");
      expect(JSON.parse(saved(request).value)).toEqual({ address, delivery: "express" });
      expect(saved(request).path).toBe("/checkout");
    });
    // The customer goes back and changes the city: the delivery choice stays.
    await step({ address, delivery: "express" }, async (request) => {
      await redirectOf(() => saveAddress(blank, formData({ ...address, city: "Teaford" })));
      expect(JSON.parse(saved(request).value)).toEqual({ address: { ...address, city: "Teaford" }, delivery: "express" });
    });
    
  4. saveDelivery sends a customer without an address back, and checks the choice
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    for (const cookie of [undefined, "{oops", "[1, 2]", { address: { ...address, city: " " } }]) {
      await step(cookie, async (request) => {
        const where = await redirectOf(() => saveDelivery(blank, formData({ delivery: "standard" })));
        expect(where.url).toBe("/checkout/address");
        expect(request.setCookies).toEqual([]);
      });
    }
    await step({ address }, async (request) => {
      expect(await saveDelivery(blank, formData({ delivery: "teleport" }))).toEqual({ errors: { delivery: "Choose standard or express delivery." } });
      expect(request.setCookies).toEqual([]);
    });
    
  5. placeOrder totals the cart on the server, deletes the cookie, and shows the order
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    await step({ address: { ...address, admin: true }, delivery: "express", total: 1 }, async (request) => {
      const where = await redirectOf(placeOrder);
      expect(where.url).toBe("/orders/o_1");
      const cookie = saved(request);
      expect(cookie.value).toBe("");
      expect(cookie.path).toBe("/checkout");
      expect(cookie.maxAge === 0 || cookie.expires?.getTime() === 0).toBe(true);
    });
    expect(orders).toEqual([{ id: "o_1", address, delivery: "express", total: 1750 }]);
    
  6. placeOrder trusts nothing in the cookie
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    const cases = [
      [undefined, "/checkout/address"],
      ["not json", "/checkout/address"],
      [{ address: { ...address, name: "" }, delivery: "standard" }, "/checkout/address"],
      [{ address: { ...address, postcode: 12345 }, delivery: "standard" }, "/checkout/address"],
      [{ address: "1 Leaf Lane", delivery: "standard" }, "/checkout/address"],
      [{ address }, "/checkout/delivery"],
      [{ address, delivery: "teleport" }, "/checkout/delivery"],
      [{ address, delivery: "constructor" }, "/checkout/delivery"],
    ];
    for (const [cookie, url] of cases) {
      const where = await step(cookie, () => redirectOf(placeOrder));
      expect(where.url).toBe(url);
    }
    expect(orders).toEqual([]);
    
  7. a whole checkout, carrying the cookie from step to step
    const address = { name: "Ana", street: "1 Leaf Lane", city: "Kettleby", postcode: "KT1 2AB" };
    const blank = { errors: {} };
    const step = (cookie, work) =>
      withRequest({ kind: "action", cookies: cookie === undefined ? {} : { checkout: typeof cookie === "string" ? cookie : JSON.stringify(cookie) } }, work);
    const saved = (request) => {
      const cookie = request.setCookies.find((item) => item.name === "checkout");
      if (!cookie) throw new Error("The action didn't set the checkout cookie.");
      return cookie;
    };
    let cookie;
    await step(undefined, async (request) => {
      await redirectOf(() => saveAddress(blank, formData(address)));
      cookie = saved(request).value;
    });
    await step(cookie, async (request) => {
      await redirectOf(() => saveDelivery(blank, formData({ delivery: "standard" })));
      cookie = saved(request).value;
    });
    const where = await step(cookie, () => redirectOf(placeOrder));
    expect(where.url).toBe("/orders/o_1");
    expect(orders[0]).toEqual({ id: "o_1", address, delivery: "standard", total: 1300 });
    

Learn more

app/checkout/actions.tsSaved in this browser

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).