Skip to the code

Send the buy box only what it needs

Each tea's page at Leaf and Kettle, app/teas/[slug]/page.tsx, loads the tea's row with findTea(slug) from @/lib/db and shows it with BuyBox from ./buy-box, a Client Component where customers pick how many to buy. Right now the page hands BuyBox the whole row, and that goes wrong in two ways.

First, the database returns prices as Decimal objects, made from a class. React can only send a Client Component values it knows how to serialize, like strings, numbers, plain objects, and arrays, and an object made from your own class isn't one of them, so Next.js stops with an error. (Here, the buy box shows $NaN instead.)

Second, every prop of a Client Component is written into the page for the browser, whether the component shows it or not. The row has costPrice and supplierEmail, which customers must never see.

Fix the page. Give BuyBox a single prop, tea, a plain object with exactly the four fields it uses: slug, name, price as a number of dollars (5.5, from the Decimal's toNumber()), and stock. Keep the rest: the tea's name in an <h1>, its about text in a paragraph, and notFound() from next/navigation for a tea the shop doesn't sell.

findTea("oolong")
→ { id: 2, slug: "oolong", name: "Oolong tea", about: "Rich and smooth.", price: Decimal(550 cents),
    stock: 3, costPrice: Decimal(210 cents), supplierEmail: "sales@misty-peak.example" }
 
<BuyBox tea={{ slug: "oolong", name: "Oolong tea", price: 5.5, stock: 3 }} />

The app's other files

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

import "server-only";
 
/** A price as the database driver returns it: an object with methods, not a number. */
export class Decimal {
  constructor(readonly cents: number) {}
 
  /** The amount as a number: 550 cents is 5.5. */
  toNumber() {
    return this.cents / 100;
  }
 
  /** The amount as text with `digits` decimals: "5.50". */
  toFixed(digits: number) {
    return this.toNumber().toFixed(digits);
  }
}
 
/** A tea's whole row in the shop's database. */
export type TeaRow = {
  id: number;
  slug: string;
  name: string;
  about: string;
  price: Decimal;
  stock: number;
  /** What the shop pays its supplier. Customers must never see it. */
  costPrice: Decimal;
  /** The supplier's private address. Customers must never see it. */
  supplierEmail: string;
};
 
const rows: TeaRow[] = [
  { id: 1, slug: "green", name: "Green tea", about: "Light and fresh.", price: new Decimal(400), stock: 30, costPrice: new Decimal(130), supplierEmail: "orders@hillside-gardens.example" },
  { id: 2, slug: "oolong", name: "Oolong tea", about: "Rich and smooth.", price: new Decimal(550), stock: 3, costPrice: new Decimal(210), supplierEmail: "sales@misty-peak.example" },
  { id: 3, slug: "mint", name: "Mint tea", about: "Cool and sweet.", price: new Decimal(300), stock: 0, costPrice: new Decimal(60), supplierEmail: "hello@riverside-herbs.example" },
];
 
/** The tea's whole row, or undefined when the shop doesn't sell it. */
export async function findTea(slug: string): Promise<TeaRow | undefined> {
  return rows.find((row) => row.slug === slug);
}

app/teas/[slug]/buy-box.tsx, read-only. Import it as @/app/teas/[slug]/buy-box.

"use client";
 
import { useState } from "react";
 
export type BuyBoxTea = { slug: string; name: string; price: number; stock: number };
 
/** How many to buy, up to what's in stock, and what they cost. */
export default function BuyBox({ tea }: { tea: BuyBoxTea }) {
  const [quantity, setQuantity] = useState(1);
  if (tea.stock === 0) return <p>Sold out</p>;
 
  return (
    <div>
      <p>
        {quantity} × ${tea.price.toFixed(2)} = ${(tea.price * quantity).toFixed(2)}
      </p>
      <button type="button" disabled={quantity === 1} onClick={() => setQuantity(quantity - 1)}>
        One less
      </button>
      <button type="button" disabled={quantity === tea.stock} onClick={() => setQuantity(quantity + 1)}>
        One more
      </button>
      {tea.stock < 5 && <p>Only {tea.stock} left</p>}
    </div>
  );
}

What the tests check

  1. shows the tea, with a buy box that adds up the price
    await renderServer(<Page params={params({ slug: "oolong" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Oolong tea" })).toBeInTheDocument();
    expect(screen.getByText("Rich and smooth.")).toBeInTheDocument();
    expect(screen.getByText("1 × $5.50 = $5.50")).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "One more" }));
    expect(screen.getByText("2 × $5.50 = $11.00")).toBeInTheDocument();
    expect(screen.getByText("Only 3 left")).toBeInTheDocument();
    
  2. gives the buy box one plain object with the four fields it uses
    const buyBoxProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === BuyBox) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    const boxes = await buyBoxProps(<Page params={params({ slug: "oolong" })} />);
    expect(boxes.length).toBe(1);
    expect(Object.keys(boxes[0])).toEqual(["tea"]);
    expect(boxes[0].tea).toEqual({ slug: "oolong", name: "Oolong tea", price: 5.5, stock: 3 });
    expect(Object.getPrototypeOf(boxes[0].tea)).toBe(Object.prototype);
    expect(typeof boxes[0].tea.price).toBe("number");
    
  3. never sends the cost price or the supplier's email
    const buyBoxProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === BuyBox) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    for (const slug of ["green", "oolong", "mint"]) {
      const sent = JSON.stringify(await buyBoxProps(<Page params={params({ slug })} />));
      expect(sent).not.toMatch(/costPrice|supplierEmail|cents|\.example/);
    }
    
  4. works the same for every tea, sold out or not
    const buyBoxProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === BuyBox) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    const [green] = await buyBoxProps(<Page params={params({ slug: "green" })} />);
    expect(green.tea).toEqual({ slug: "green", name: "Green tea", price: 4, stock: 30 });
    await renderServer(<Page params={params({ slug: "green" })} />);
    await user.click(screen.getByRole("button", { name: "One more" }));
    await user.click(screen.getByRole("button", { name: "One more" }));
    expect(screen.getByText("3 × $4.00 = $12.00")).toBeInTheDocument();
    cleanup();
    await renderServer(<Page params={params({ slug: "mint" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Mint tea" })).toBeInTheDocument();
    expect(screen.getByText("Sold out")).toBeInTheDocument();
    
  5. calls notFound() for a tea the shop doesn't sell
    expect(await accessErrorOf(() => renderServer(<Page params={params({ slug: "coffee" })} />))).toBe(404);
    

Learn more

app/teas/[slug]/page.tsxSaved 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).