Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 72 ยท Projects

Project: A Storefront with Cart

Build a small Next.js storefront: product pages with ISR, a cookie cart, server-side pricing, a checkout action and search, with runnable Node stand-ins.

An online store is a stress test for everything you know about Next.js, because it needs two opposite things at once. Product pages must be fast and cacheable, because thousands of visitors see the same page. Carts and checkout must be personal and correct, because they involve one visitor's items and real money. The whole design of a storefront is about keeping those two worlds apart.

In this project we plan a small store with product pages that use Incremental Static Regeneration (ISR), a cart stored in a cookie, a checkout Server Action that never trusts the browser's prices, and a search page. You will read the real code, and run three Node.js stand-ins: the cart logic, the cache-versus-price problem, and the search ranking. It combines Static Generation and generateStaticParams, Revalidating Data, Cookies and Headers and Server Actions.

Real or stand-in? The Next.js code is real, in read-only blocks, because this site cannot run a Next.js server, a database or a payment provider. The three runnable examples are plain Node.js stand-ins with a fake clock and an in-memory catalog. They implement the same rules as the real code, so you can see exactly what the rules do.

The shape of a storefront

Four parts of the store

Catalog Product pages, built ahead and refreshed with ISR.
Cart Lives in a cookie. Personal and dynamic.
Checkout A Server Action that re-checks everything.
Search Driven by the URL, rendered on the server.
1 / 2
flowchart LR
    V["Visitor"] --> CDN["CDN"]
    CDN -->|"/products/mug (cached, ISR)"| P["Product page"]
    V -->|"/cart, /checkout (never cached)"| S["Next.js server"]
    S --> D["Database"]
    P -.->|"rebuilt in the background"| D

Product pages come from the cache. Cart and checkout always run on the server.

Project structure

TEXT
app/
  layout.tsx
  page.tsx                       # home, featured products
  products/[slug]/page.tsx       # product page with ISR
  search/page.tsx                # search with ?q=
  cart/page.tsx                  # reads the cart cookie (dynamic)
  checkout/page.tsx              # form for the checkout action
  api/cart/count/route.ts        # tiny endpoint for the header badge
  actions.ts                     # addToCart, updateQuantity, placeOrder
lib/
  catalog.ts                     # product queries
  cart.ts                        # read, write and price the cart cookie
  orders.ts                      # create an order in one transaction

Product pages with ISR

A product changes rarely, but it does change: a price, a photo, the stock level. ISR (Incremental Static Regeneration) gives you the best of both: the page is served from the cache like static HTML, and Next.js rebuilds it in the background after a time you choose. Visitors never wait for a database query.

TSX
// app/products/[slug]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getProductBySlug, getPopularSlugs } from '@/lib/catalog';
import { AddToCartForm } from './add-to-cart-form';

export const revalidate = 3600; // rebuild in the background at most once per hour

type Props = { params: Promise<{ slug: string }> };

export async function generateStaticParams() {
  const slugs = await getPopularSlugs(100);
  return slugs.map((slug) => ({ slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProductBySlug(slug);
  if (!product) return {};
  return { title: product.name, description: product.summary };
}

export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const product = await getProductBySlug(slug);
  if (!product) notFound();

  return (
    <article>
      <h1>{product.name}</h1>
      <p>{(product.price / 100).toFixed(2)} USD</p>
      <p>{product.summary}</p>
      <AddToCartForm productId={product.id} />
    </article>
  );
}

Read it with caching in mind. revalidate = 3600 turns on ISR for the page. generateStaticParams builds the 100 most popular products at deploy time. Because dynamicParams defaults to true, any other product is rendered the first time someone asks for it and cached from then on, so a catalog of 100,000 products does not need a 100,000-page build. And the page reads no cookies or headers. This is the most important rule of the whole project: a single cookies() call here would make the page dynamic and throw away the cache (see Static vs Dynamic Rendering). That is why the header's cart badge is not rendered by the server on this page. It is a tiny Client Component that fetches /api/cart/count, an uncached Route Handler, after the page loads. The same pattern keeps public pages cacheable on this very site.

If your project uses Cache Components (the "use cache" directive from The use cache Directive and Cache Components), you would cache the product query with cacheLife('hours') and cacheTag('product-' + id) instead of using revalidate. The design is the same: cache the catalog, keep the cart separate.

The cache has a price problem

ISR means the page can show a price that is up to an hour old. That is fine for presentation, but it must never be the price you charge. The next stand-in plays this out with a fake clock. A product page is built at time 0, the admin raises the price at 30 seconds, and visitors keep seeing the old price until the page is rebuilt. The checkout function re-prices from the database and refuses to charge a total the customer has not seen. Then the second half shows the fix: on-demand revalidation right after the admin saves.

Node.js Stale pages, honest checkout, on-demand revalidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first half shows the two facts to hold on to. A stale page is served instantly to the visitor at 65 seconds, and the rebuilt page only reaches the visitor after that. Meanwhile the checkout at 40 seconds noticed that the customer's expected total did not match the database and stopped, instead of silently charging more. The second half shows that when the price changes through your admin screen, a call to revalidatePath or revalidateTag (see Revalidating Data) makes the very next visitor see the new page. Use the time-based revalidate as a safety net and on-demand revalidation for changes you control.

Where should a cart live? You have three options: in the browser (localStorage), in the database tied to a session, or in a cookie. A cookie cart is the simplest that works well with Server Components, because the server can read it on every request. It has a size limit of about 4 KB, so it must store only ids and quantities, never names, images or prices. Anything else is looked up on the server.

TypeScript
// lib/cart.ts
import 'server-only';
import { cookies } from 'next/headers';
import { z } from 'zod';
import { getProductsByIds } from './catalog';

const CartSchema = z
  .array(z.object({ id: z.string().max(40), qty: z.number().int().min(1).max(10) }))
  .max(20);

export type CartLine = z.infer<typeof CartSchema>[number];

export async function readCart(): Promise<CartLine[]> {
  const store = await cookies();
  const raw = store.get('cart')?.value;
  if (!raw) return [];
  try {
    const parsed = CartSchema.safeParse(JSON.parse(raw));
    return parsed.success ? parsed.data : [];
  } catch {
    return [];
  }
}

export async function writeCart(lines: CartLine[]) {
  const store = await cookies();
  store.set('cart', JSON.stringify(lines), {
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    path: '/',
    maxAge: 60 * 60 * 24 * 30,
  });
}

export async function priceCart(lines: CartLine[]) {
  const products = await getProductsByIds(lines.map((l) => l.id));
  const detailed = lines.flatMap((line) => {
    const product = products.find((p) => p.id === line.id);
    return product ? [{ ...line, name: product.name, unit: product.price, total: product.price * line.qty }] : [];
  });
  const subtotal = detailed.reduce((sum, l) => sum + l.total, 0);
  const shipping = subtotal === 0 || subtotal >= 5000 ? 0 : 499;
  const tax = Math.round(subtotal * 0.08);
  return { lines: detailed, subtotal, shipping, tax, total: subtotal + shipping + tax };
}

Read the three functions as three promises. readCart returns only valid data: a cookie is user input, so a tampered or corrupted one becomes an empty cart instead of an error. writeCart sets the cookie with httpOnly (no script can read it), sameSite: 'lax' and secure in production, exactly as in Cookies and Headers. And priceCart is the only place that turns a cart into money, using prices from the database. Money is held as integer cents: 0.1 + 0.2 is not 0.3 in floating point, and a shop cannot have that.

The first stand-in is the same logic without any framework. It parses and validates a cookie, adds items under stock limits, prices the cart on the "server", and shows what happens to a cookie that the customer edited by hand.

Node.js Cart cookie: validate, add, price, resist tampering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the tampered case line by line. The price: 1 the customer slipped in is ignored, because parseCart never reads a price. The unknown product and the string 'junk' are dropped. The two p-mug lines are merged into one line of 5, and the tote's quantity of 99 is clamped to the stock of 3. The key is Object.hasOwn: a naive id in CATALOG check would accept 'constructor', which exists on every object. A cart that survives hostile input is the first half of a safe checkout.

Adding to the cart

The "Add to cart" button is a small form that calls a Server Action. The action validates, checks stock against the database, updates the cookie and returns a state for the form to display:

TypeScript
// app/actions.ts
'use server';

import { z } from 'zod';
import { redirect } from 'next/navigation';
import { getProductById } from '@/lib/catalog';
import { readCart, writeCart, priceCart } from '@/lib/cart';
import { createOrder } from '@/lib/orders';

const AddSchema = z.object({
  productId: z.string().max(40),
  qty: z.coerce.number().int().min(1).max(10),
});

export async function addToCart(previous: { error: string | null }, formData: FormData) {
  const parsed = AddSchema.safeParse({ productId: formData.get('productId'), qty: formData.get('qty') });
  if (!parsed.success) return { error: 'Please choose a quantity from 1 to 10.' };

  const product = await getProductById(parsed.data.productId);
  if (!product) return { error: 'That product no longer exists.' };

  const lines = await readCart();
  const current = lines.find((l) => l.id === product.id)?.qty ?? 0;
  const qty = current + parsed.data.qty;
  if (qty > Math.min(10, product.stock)) return { error: 'Not enough stock for that quantity.' };

  await writeCart([...lines.filter((l) => l.id !== product.id), { id: product.id, qty }]);
  return { error: null };
}

Note the shape: validate, look up the truth, change the cookie. The form sends only productId and qty. After the action succeeds, the small cart badge component refreshes its count by fetching /api/cart/count again, or listens to an event that the form dispatches. Neither of these touches the cached product page.

The cart page is where the cookie is read on the server, so it is dynamic by nature:

TSX
// app/cart/page.tsx
import Link from 'next/link';
import { readCart, priceCart } from '@/lib/cart';

export default async function CartPage() {
  const cart = await priceCart(await readCart());

  if (cart.lines.length === 0) {
    return <p>Your cart is empty. <Link href="/">Keep shopping</Link></p>;
  }

  return (
    <>
      <h1>Your cart</h1>
      <ul>
        {cart.lines.map((l) => (
          <li key={l.id}>{l.name} x {l.qty}: {(l.total / 100).toFixed(2)}</li>
        ))}
      </ul>
      <p>Total: {(cart.total / 100).toFixed(2)} USD</p>
      <Link href="/checkout">Checkout</Link>
    </>
  );
}

Every number here comes from priceCart, which uses the database. If a product was deleted since the visitor added it, priceCart simply leaves it out.

Checkout

Checkout is the most security-sensitive code in the project, so it is deliberately boring. The form posts customer details and the total the customer saw. The action then recalculates everything from the database and compares:

TypeScript
// app/actions.ts (continued)
const CheckoutSchema = z.object({
  email: z.string().email(),
  name: z.string().trim().min(1).max(80),
  address: z.string().trim().min(5).max(200),
  expectedTotal: z.coerce.number().int().nonnegative(),
});

export async function placeOrder(previous: { error: string | null }, formData: FormData) {
  const parsed = CheckoutSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { error: parsed.error.issues[0].message };

  const cart = await priceCart(await readCart());
  if (cart.lines.length === 0) return { error: 'Your cart is empty.' };

  if (cart.total !== parsed.data.expectedTotal) {
    return { error: 'Prices changed. Please review your order and try again.' };
  }

  const result = await createOrder({
    customer: { email: parsed.data.email, name: parsed.data.name, address: parsed.data.address },
    lines: cart.lines,
    total: cart.total,
  });
  if (!result.ok) return { error: result.message }; // for example: out of stock

  await writeCart([]);
  redirect('/orders/' + result.orderId + '/thanks');
}

createOrder in lib/orders.ts runs one database transaction: it reduces the stock of each product only if enough is left (a conditional update, so two buyers cannot both take the last item), then inserts the order and its lines. If any step fails, nothing is saved. Paying is the next step. With a provider such as Stripe, you create a Checkout Session on the server and redirect the customer to the provider's page, and mark the order paid when the provider's webhook (a Route Handler) confirms the payment. Never mark an order paid because the browser says so. A real store also needs rate limiting on this action (see Observability and Scaling) and a signed-in user or a guest order token.

Note the last two lines of the action. redirect goes last, and outside any try/catch, because it works by throwing (see Optimistic UI and Refreshing After Mutations).

A search page is a Server Component driven by the URL, like the table in Project: An Admin Dashboard:

TSX
// app/search/page.tsx
import Link from 'next/link';
import { searchProducts } from '@/lib/catalog';

type Props = { searchParams: Promise<{ q?: string; category?: string; sort?: string }> };

export const metadata = { robots: { index: false } }; // search result pages should not be indexed

export default async function SearchPage({ searchParams }: Props) {
  const { q = '', category, sort } = await searchParams;
  const results = await searchProducts({ q: q.slice(0, 100), category, sort });

  return (
    <>
      <h1>{q ? 'Results for "' + q + '"' : 'All products'}</h1>
      {results.length === 0 && <p>No products found. Try fewer words.</p>}
      <ul>
        {results.map((p) => (
          <li key={p.id}><Link href={'/products/' + p.slug}>{p.name}</Link></li>
        ))}
      </ul>
    </>
  );
}

React escapes q when it renders, so printing it in the heading is safe. The limit of 100 characters keeps absurd queries away from the database. For a small catalog a database LIKE or full-text query is enough. For a large one you would add a search engine such as Meilisearch or Algolia, which does typo tolerance and ranking for you.

The last stand-in is a tiny search engine with the ideas that engines are built on: split text into words, give each field a weight (name matches count more than description matches), require every query word to match something, then apply category, price and sort parameters from the URL.

Node.js Product search: tokens, weights, filters and sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the results for coffee. The mug and the kettle score 3 through their tags, and the backpack scores 1 because the word appears only in its description. Sorting by relevance and then by price puts the cheaper of two equal matches first. The prefix rule makes note find "Notebook" with a name weight of 4, and the category filter keeps the pen out. The empty result shows a helpful message instead of an empty page. The max parameter is checked with Number.isFinite, so a nonsense value cannot break the query.

Before you ship a store

  • Taxes, shipping and legal pages differ by country. Use a payment provider or tax service that handles them.
  • Guest and signed-in carts. Merge the cookie cart into the account cart at login (see Authentication and Sessions).
  • Stock reservations during checkout, and a policy for abandoned carts.
  • Emails after an order, sent from a queue, never inside the request.
  • Monitoring of the checkout path in particular, with traces and alerts (see Observability and Scaling).
  • Product structured data (JSON-LD) so search engines can show prices and availability (see Metadata and SEO).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the product page avoid calling cookies()?

    Any read of request data makes the route render per request. Personal parts such as the cart badge should load separately, leaving the product page cacheable.
  2. 2. What should the cart cookie contain?

    A cookie is small and user-editable. Ids and quantities are enough, and the server must look up prices, names and stock.
  3. 3. A page built with revalidate = 3600 shows a price of 18.00, but the database now says 22.00. What should checkout do?

    The server owns the price. A stale cached page must never decide what is charged, so checkout compares and refuses to continue silently.
  4. 4. Why is money stored as integer cents in the code?

    Binary floating point cannot represent values like 0.1 exactly, so sums drift. Integer cents are exact.
  5. 5. What does a call to revalidatePath or revalidateTag after an admin changes a price achieve?

    On-demand revalidation lets changes you control show up at once, while the time-based revalidate stays as a safety net.

Summary

  • A storefront has two worlds: a cacheable catalog (ISR with revalidate or "use cache") and a personal, dynamic cart and checkout. Keep them apart, and never read cookies in a cacheable page.
  • Store the cart in a cookie as ids and quantities only. Parse it defensively, clamp quantities to stock, and price it on the server in integer cents.
  • A cached page may show an old price, so checkout re-prices from the database and compares it with the total the customer saw.
  • Use on-demand revalidation when you change data yourself, and time-based revalidation as a safety net.
  • Checkout is a Server Action: validate, price, check stock in one transaction, clear the cart, then redirect last. Mark orders paid only from the payment provider's webhook.
  • Search is a Server Component driven by search params, with whitelisted, length-limited input.

Next: Project: Login and Protected Pages