Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: A Small Store with SSR, Cart and Checkout

Build a small Astro store: static product pages, a cart island with Nano Stores, server endpoints, middleware, server islands and a safe checkout flow.

The last project mixes everything from the SSR and integration chapters: mostly static product pages, a cart that lives in the browser, a server API, a login-aware header via a server island, and a checkout endpoint that never trusts the client. It is a learning store: payments are described, not implemented; you would use a provider's hosted checkout in production.

Architecture

flowchart LR
  subgraph Static["Prerendered (CDN)"]
    A["/ and /products/[slug]"]
  end
  subgraph Browser["Browser"]
    B["Cart island<br/>Nano Stores + localStorage"]
  end
  subgraph Server["Server (adapter)"]
    C["server:defer header<br/>(account, cart count)"]
    D["POST /api/checkout"]
    E["Middleware: session"]
  end
  A --> B
  A --> C
  B --> D
  E --> C
  E --> D

Pages are static and cacheable; only the account bits and checkout hit the server.

Step 1: Products as data

TypeScript
// src/content.config.ts
const products = defineCollection({
  loader: file('src/data/products.json'),
  schema: ({ image }) => z.object({
    name: z.string(),
    priceCents: z.number().int().positive(),
    image: image(),
    imageAlt: z.string(),
    description: z.string(),
    stock: z.number().int().min(0),
  }),
});

Prices are integers in cents everywhere: floating point numbers cannot represent money exactly (0.1 + 0.2 !== 0.3).

Product pages use getStaticPaths() and are fully prerendered: fast, cacheable, great SEO. Add JSON-LD Product structured data with name, image, price and availability.

Step 2: The cart island

TypeScript
// src/stores/cart.ts
import { map, computed } from 'nanostores';
import { persistentMap } from '@nanostores/persistent';

export const cart = persistentMap<Record<string, string>>('cart:', {});
// key = product id, value = quantity as string (persistent stores hold strings)

export const cartCount = computed(cart, (c) =>
  Object.values(c).reduce((n, q) => n + Number(q), 0),
);

export function addToCart(id: string) {
  cart.setKey(id, String(Number(cart.get()[id] ?? 0) + 1));
}
export function removeFromCart(id: string) {
  const { [id]: _removed, ...rest } = cart.get();
  cart.set(rest);
}
JSX
// src/components/AddToCart.jsx
import { addToCart } from '../stores/cart';
export default function AddToCart({ id, disabled }) {
  return <button disabled={disabled} onClick={() => addToCart(id)}>Add to cart</button>;
}
ASTRO
<AddToCart client:visible id={product.id} disabled={product.data.stock === 0} />

The cart stores only ids and quantities, never prices. Prices come from the server at checkout.

Step 3: Personalised header with a server island

ASTRO
---
// Header.astro
import AccountMenu from './AccountMenu.astro';
---
<header>
  <a href="/">Shop</a>
  <AccountMenu server:defer>
    <a slot="fallback" href="/login">Log in</a>
  </AccountMenu>
</header>
ASTRO
---
// AccountMenu.astro (runs per request on the server)
const user = Astro.locals.user;
---
{user ? <a href="/account">{user.name}</a> : <a href="/login">Log in</a>}

Every page stays CDN-cached; the little account fragment is fetched with the visitor's cookies.

Step 4: Checkout endpoint that trusts nothing

TypeScript
// src/pages/api/checkout.ts
import type { APIRoute } from 'astro';
import { getEntry } from 'astro:content';
import { z } from 'astro:schema';

export const prerender = false;

const body = z.object({
  items: z.array(z.object({ id: z.string(), qty: z.number().int().min(1).max(20) })).min(1).max(50),
});

export const POST: APIRoute = async ({ request, locals }) => {
  if (!locals.user) return Response.json({ error: 'Log in first' }, { status: 401 });

  const parsed = body.safeParse(await request.json().catch(() => null));
  if (!parsed.success) return Response.json({ error: 'Invalid cart' }, { status: 400 });

  let totalCents = 0;
  const lines = [];
  for (const { id, qty } of parsed.data.items) {
    const product = await getEntry('products', id);
    if (!product) return Response.json({ error: `Unknown product ${id}` }, { status: 400 });
    if (product.data.stock < qty) return Response.json({ error: `Only ${product.data.stock} of ${product.data.name} left` }, { status: 409 });
    totalCents += product.data.priceCents * qty;
    lines.push({ id, qty, unitCents: product.data.priceCents });
  }

  const orderId = await createOrder(locals.user.id, lines, totalCents);
  const url = await createHostedCheckoutSession({ orderId, totalCents }); // payment provider
  return Response.json({ url });
};

Principles to notice:

  1. Re-price on the server. The client's numbers are only ids and quantities.
  2. Validate shape, ranges and existence.
  3. Authenticate inside the endpoint, not just in the UI.
  4. Use a hosted checkout from a payment provider; never handle card numbers yourself.
  5. Confirm payment through the provider's signed webhook, not through the browser redirect.

Step 5: Deploy

Use an adapter for your host, set secrets in the platform, and add the checklist from the deployment lesson. Put Cache-Control: private, no-store on account and checkout responses.

Try it: price a cart safely

The server-side pricing logic: ignore client prices, check stock, compute integer totals and format them.

JS Server-side cart pricing

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

No output.

Try it: the persistent cart store

A stand-in cart store with persistence into a fake localStorage, showing how state survives a reload.

JS Cart store with persistence

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the checkout endpoint ignore prices sent by the browser?

    Anything from the client can be tampered with. Only ids and quantities are accepted; the server re-prices from trusted data.
  2. 2. Why store prices as integer cents?

    Binary floating point cannot represent values like 0.1 exactly, which creates rounding errors in money.
  3. 3. What does the server island in the header achieve?

    Only the small account fragment is rendered per request; the surrounding page remains static and CDN-friendly.
  4. 4. How should payment completion be confirmed?

    A redirect can be faked or never happen. A verified server-to-server webhook is reliable.

Summary

  • Keep catalogue pages static, move only personalised and transactional parts to the server.
  • The cart is client state (ids and quantities); the server owns prices, stock and orders.
  • Authenticate and validate inside every endpoint; use hosted payments and webhooks.
  • Mark private responses no-store and keep secrets in the platform.

Next: Practice: Common Mistakes and Exercises