Skip to lesson content

PROJECT 6 · LESSON 18 OF 18

Place orders and manage fulfillment

Combine authenticated checkout, consistent stock updates and order history.

  • transactions
  • idempotency
  • trusted prices
  • order snapshots
  • deployment

Your workspace: edushop

Continue from lesson 17: Manage products and stock as an administrator. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

Checkout is where browser choices become a durable order. The browser can request products and quantities, but the server must decide the current price, available stock and customer identity. This lesson also handles the case where the same request arrives twice.

The cart submits IDs and quantities, never an authoritative price or user ID. The server reloads products and calculates the total. Store product names and prices in the order so future catalog edits do not rewrite purchase history.

A transaction makes stock deductions and order insertion succeed together. If one line is unavailable, the entire transaction rolls back. The order ID includes the verified user and a request token; retrying that token cannot create a second order.

This is a simulated checkout with no tax, shipping, payment collection, cancellation or refunds. Before real commerce, add payment-provider confirmation, verified customer contact details, operational monitoring and business-specific checkout rules.

Establish the trusted inputs

The submitted cart contains IDs and quantities, plus a request token. The action derives userId from requireUser, parses the cart as untrusted JSON, and validates its shape, line count, unique IDs and integer quantities. A caller can edit hidden inputs or browser storage; all those paths meet the same server checks.

The server reads each active product and its current price. A browser-supplied price is not accepted. The order stores product name, unit price and quantity as a snapshot so changing tomorrow’s catalog does not rewrite yesterday’s order.

This demo accepts the server’s current price at submission and explains that prices are checked again. A real checkout can add a versioned quote and require renewed confirmation when prices, tax or shipping change. That is an additional product rule, not something a client total enforces.

Use a transaction for an all-or-nothing operation

Each findOneAndUpdate combines the active-product condition, enough-stock condition and decrement into one operation. Two buyers cannot both satisfy stock>=1 and each subtract from a single remaining unit as if it were still available.

An order may contain several lines. The surrounding transaction groups every deduction and the order insertion. If a later product lacks stock, throwing aborts the transaction so earlier deductions are rolled back. Without that grouping, a failed multi-item checkout could consume inventory without creating its order.

Transactions require MongoDB Atlas or a correctly configured replica set. A standalone local MongoDB server may support ordinary CRUD yet reject this transaction. Also keep external side effects such as charging a payment card out of a retryable transaction callback. This tutorial collects no payment.

Understand idempotency through a repeated request

Disabling a button improves the UI but cannot prevent a network retry or direct repeated request. The token identifies this checkout attempt, and the server combines it with the verified user ID to form the order _id. MongoDB’s unique _id constraint prevents two orders with that same identity.

Inside the transaction, an existing order with that ID returns without another deduction. Concurrent retries can still collide, so the error path checks whether the intended order already exists. If it does, the action reports the existing successful outcome rather than making a second order.

The guarantee is scoped to the same token. A new page visit can create a new token and therefore a new order. The browser must preserve an attempt’s token when retrying it; do not describe this as deduplicating all future purchases of identical items.

Separate customer history from administration

Customer order history filters on the session user ID. The admin order list and fulfillment action require requireAdmin. Marking placed as fulfilled changes fulfillment status only; it does not charge a customer or deduct stock again.

Before releasing a learner app, run the ownership and last-unit tests against a learning database. A successful build proves code compilation, not working credentials, transaction support or correct operational configuration. Payments, refunds, shipping, verified email and audit requirements remain beyond this simulated store.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. An authenticated customer submits cart IDs, quantities and the same attempt token on retries.

  2. The server validates the request and opens a database transaction.

  3. Each active product is checked and decremented; current names and prices are captured.

  4. The order is inserted atomically with those deductions, or the whole transaction rolls back.

  5. A replay of the same token returns the existing order, and customer history reads it under the owner filter.

Work a two-item transaction by hand

  1. Notebook has stock 3 at 24900 paise. Lamp has stock 0 at 89900 paise. The cart requests one of each.
  2. The notebook update can tentatively decrement stock, but the lamp update has no match because stock is insufficient.
  3. The action throws inside the transaction. The notebook deduction rolls back and no order is stored.
  4. Now stock one lamp and retry: both deductions and the order can commit together. Total is 114800 paise, or ₹1,148.00. Replaying the same token does not deduct either item again.

3. Build it, one file at a time

  1. Continue from lesson 17. Add the checkout action, component and order pages. Replace the cart page and navigation.
  2. Sign in as a customer, add a product, open /cart, and place a demo order. Follow View your order.
  3. As an administrator visit /admin/orders and mark the order fulfilled. Reopen the customer history.
  4. Set a product to stock 1. In two browser profiles attempt to buy its last unit. At most one order should succeed. Confirm a failed multi-item order did not deduct stock from its other lines.
  5. Run npm run typecheck and npm run build. For a preview deployment, configure the learning database URI, database name, auth secret and the preview origin as BETTER_AUTH_URL. Seed that database once. Repeat account and permission checks on the preview.
Terminal
npm run typecheck
npm run build

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

app/checkout/actions.ts

This performs a complete simulated checkout as one authenticated, retry-safe database operation.

app/checkout/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { client, db } from "@/lib/db";
import { inventory } from "@/lib/store";
import { requireUser } from "@/lib/session";
import type { CartLine } from "@/lib/cart";
export type Order = {
  _id: string;
  userId: string;
  items: { productId: string; name: string; quantity: number; price: number }[];
  total: number;
  status: "placed" | "fulfilled";
  createdAt: Date;
};
export type OrderResult = { message: string; orderId?: string };
export async function placeOrder(
  _previous: OrderResult,
  data: FormData,
): Promise<OrderResult> {
  const user = await requireUser();
  const token = String(data.get("token") ?? "");
  const raw = String(data.get("lines") ?? "");
  if (!/^[0-9a-f-]{36}$/i.test(token) || raw.length > 10000)
    return { message: "Invalid checkout request." };
  let lines: CartLine[];
  try {
    const parsed: unknown = JSON.parse(raw);
    if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > 50)
      throw new Error();
    const seen = new Set<string>();
    for (const line of parsed) {
      if (
        !line ||
        typeof line.productId !== "string" ||
        line.productId.length > 100 ||
        !Number.isInteger(line.quantity) ||
        line.quantity < 1 ||
        line.quantity > 10 ||
        seen.has(line.productId)
      )
        throw new Error();
      seen.add(line.productId);
    }
    lines = parsed;
  } catch {
    return { message: "Check cart quantities and try again." };
  }
  const orderId = `${user.id}:${token}`;
  const orders = db.collection<Order>("orders");
  const session = client.startSession();
  try {
    await session.withTransaction(async () => {
      // A retry with the same key returns the already-created order.
      if (await orders.findOne({ _id: orderId, userId: user.id }, { session }))
        return;
      const items: Order["items"] = [];
      for (const line of lines) {
        const product = await inventory.findOneAndUpdate(
          { id: line.productId, active: true, stock: { $gte: line.quantity } },
          { $inc: { stock: -line.quantity } },
          { session, returnDocument: "before" },
        );
        if (!product) throw new Error("STOCK_CHANGED");
        items.push({
          productId: product.id,
          name: product.name,
          price: product.price,
          quantity: line.quantity,
        });
      }
      await orders.insertOne(
        {
          _id: orderId,
          userId: user.id,
          items,
          total: items.reduce(
            (sum, item) => sum + item.price * item.quantity,
            0,
          ),
          status: "placed",
          createdAt: new Date(),
        },
        { session },
      );
    });
  } catch (error) {
    // Concurrent retries may meet the unique _id constraint after one succeeds.
    const existing = await orders
      .findOne({ _id: orderId, userId: user.id })
      .catch(() => null);
    if (!existing)
      return {
        message:
          error instanceof Error && error.message === "STOCK_CHANGED"
            ? "Stock changed or a product is unavailable. Refresh and review your cart."
            : "Order could not be placed. Check the database connection and replica-set configuration, then retry.",
      };
  } finally {
    await session.endSession();
  }
  revalidatePath("/", "layout");
  return { message: "Demo order placed. No payment was taken.", orderId };
}

Read the code

  1. requireUser supplies identity. The action validates the token and parsed line array before opening a transaction; duplicate IDs and out-of-range quantities are rejected.
  2. Each conditional findOneAndUpdate requires an active product with enough stock and returns its previous values for the order snapshot. A failure throws inside the transaction so all deductions roll back.
  3. The order ID combines the verified user and request token. Looking up that ID and relying on its uniqueness makes a replay return the existing order rather than decrementing stock twice.
  4. The result is a demo order, not payment confirmation. Errors return safe feedback, the session is ended in finally, and successful output is revalidated.

components/checkout.tsx

This submits the cart and a stable checkout-attempt token, and reports the server’s result.

components/checkout.tsx
"use client";
import Link from "next/link";
import { useActionState, useState } from "react";
import { useCart } from "./cart-provider";
import { placeOrder } from "@/app/checkout/actions";
export default function Checkout({ token }: { token: string }) {
  const { lines, ready, clear } = useCart();
  const [requestToken] = useState(token);
  const [state, action, pending] = useActionState(placeOrder, { message: "" });
  return (
    <form action={action}>
      <h2>Place a demo order</h2>
      <p>
        Sign in before ordering. Prices and availability are checked again on
        the server. No payment is collected.
      </p>
      <input type="hidden" name="token" value={requestToken} />
      <input type="hidden" name="lines" value={JSON.stringify(lines)} />
      <button disabled={!ready || !lines.length || pending || !!state.orderId}>
        {pending ? "Placing order…" : "Place demo order"}
      </button>
      <p role="status">{state.message}</p>
      {state.orderId && (
        <>
          <Link href="/orders">View your order</Link>
          <p>
            <button type="button" onClick={clear}>
              Clear purchased cart
            </button>
          </p>
          <p>Start a fresh visit to the cart page for your next order.</p>
        </>
      )}
    </form>
  );
}

Read the code

  1. The token is captured in state so rerenders of this mounted checkout do not silently replace its attempt identity. A new visit can still create a new attempt.
  2. Hidden fields serialize cart choices and the token. These fields are untrusted; the server action validates them and retrieves authoritative prices.
  3. The button is disabled during restoration, empty carts, pending requests and confirmed success. Those UI rules supplement database idempotency instead of replacing it.
  4. Clearing the cart is an explicit post-success action. Visiting order history does not depend on browser cart contents because orders are stored on the server.

app/cart/page.tsx

This server page supplies current catalog facts to the interactive cart.

app/cart/page.tsx
import { randomUUID } from "node:crypto";
import { getProducts } from "@/lib/store";
import CartContents from "@/components/cart-contents";
import Checkout from "@/components/checkout";
export const dynamic = "force-dynamic";
export default async function CartPage() {
  return (
    <>
      <CartContents products={await getProducts()} />
      <Checkout token={randomUUID()} />
    </>
  );
}

Read the code

  1. getProducts runs in the server-only data layer and returns plain values for CartContents.
  2. CartContents owns browser interactions through the provider; the page does not read localStorage.
  3. The route is dynamic so visits can read current catalog data.
  4. randomUUID creates a checkout-attempt token for this render. Checkout captures that token while mounted and submits it with the cart for duplicate-request protection.

app/orders/page.tsx

This renders a customer’s durable order history from saved snapshots.

app/orders/page.tsx
import { db } from "@/lib/db";
import { requireUser } from "@/lib/session";
import { money } from "@/lib/money";
import type { Order } from "@/app/checkout/actions";
export default async function OrdersPage() {
  const user = await requireUser();
  const orders = await db
    .collection<Order>("orders")
    .find({ userId: user.id })
    .sort({ createdAt: -1 })
    .limit(50)
    .toArray();
  return (
    <>
      <h1>Your orders</h1>
      {!orders.length && <p>No orders yet.</p>}
      {orders.map((order) => (
        <article key={order._id}>
          <h2>Order {order._id.split(":").at(-1)}</h2>
          <p>
            {order.status} · {order.createdAt.toISOString()}
          </p>
          <ul>
            {order.items.map((item) => (
              <li key={item.productId}>
                {item.name} × {item.quantity} —{" "}
                {money(item.price * item.quantity)}
              </li>
            ))}
          </ul>
          <strong>{money(order.total)}</strong>
        </article>
      ))}
    </>
  );
}

Read the code

  1. requireUser identifies the current customer and the query filters userId on the server. Another customer’s orders never enter the rendered list.
  2. Item names and prices come from the order itself, preserving what was ordered even after catalog changes.
  3. The date is shown as an ISO timestamp to keep this example explicit about its stored time. The list cap is a teaching simplification, not pagination.

app/admin/orders/actions.ts

This changes fulfillment status only for an administrator.

app/admin/orders/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { requireAdmin } from "@/lib/admin";
import { db } from "@/lib/db";
import type { Order } from "@/app/checkout/actions";
export async function fulfillOrder(data: FormData) {
  await requireAdmin();
  const id = String(data.get("id") ?? "");
  if (!id || id.length > 200) return;
  await db
    .collection<Order>("orders")
    .updateOne(
      { _id: id, status: "placed" },
      { $set: { status: "fulfilled" } },
    );
  revalidatePath("/admin/orders");
  revalidatePath("/orders");
}

Read the code

  1. requireAdmin executes inside the action. A hidden order ID selects the requested record but grants no permission.
  2. The filter requires status=placed and $set changes it to fulfilled. Repeating the operation does not subtract stock or create another order.
  3. The two order views are revalidated afterward. This operation does not collect a payment or issue a refund.

app/admin/orders/page.tsx

This provides the administrator’s cross-customer order view.

app/admin/orders/page.tsx
import { requireAdmin } from "@/lib/admin";
import { db } from "@/lib/db";
import { money } from "@/lib/money";
import type { Order } from "@/app/checkout/actions";
import { fulfillOrder } from "./actions";
export default async function AdminOrders() {
  await requireAdmin();
  const orders = await db
    .collection<Order>("orders")
    .find({})
    .sort({ createdAt: -1 })
    .limit(100)
    .toArray();
  return (
    <>
      <h1>Manage orders</h1>
      {!orders.length && <p>No orders yet.</p>}
      {orders.map((order) => (
        <article key={order._id}>
          <h2>{order._id}</h2>
          <p>
            {money(order.total)} · {order.status}
          </p>
          <ul>
            {order.items.map((item) => (
              <li key={item.productId}>
                {item.name} × {item.quantity}
              </li>
            ))}
          </ul>
          {order.status === "placed" && (
            <form action={fulfillOrder}>
              <input type="hidden" name="id" value={order._id} />
              <button>Mark fulfilled</button>
            </form>
          )}
        </article>
      ))}
    </>
  );
}

Read the code

  1. requireAdmin protects the read before querying orders. Unlike customer history, this query intentionally includes all customers.
  2. Only placed orders display the fulfillment form. The action still verifies permission independently even though the page hid controls for other states.
  3. Saved item details explain the order contents without reconstructing them from the current catalog.

app/layout.tsx

This keeps one cart provider above all of the store’s consumers.

app/layout.tsx
import type { ReactNode } from "react";
import Link from "next/link";
import { CartProvider } from "@/components/cart-provider";
import CartLink from "@/components/cart-link";
import "./globals.css";
export const metadata = {
  title: "EduShop",
  description: "My Next.js learning project",
};
export default function Layout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <CartProvider>
          <nav>
            <Link href="/">Home</Link>
            <Link href="/products">Products</Link>
            <CartLink />
            <Link href="/account">Account</Link>
            <Link href="/orders">Orders</Link>
          </nav>
          <main>{children}</main>
        </CartProvider>
      </body>
    </html>
  );
}

Read the code

  1. The root layout remains a Server Component and wraps navigation and children in CartProvider.
  2. CartLink consumes shared state, while ordinary Links navigate between routes. The provider owns the interactive state; the layout still owns the document.
  3. Passing children through a client provider does not require importing all server page modules into that client module. Preserve this composition boundary.

4. Run it and check your result

  • Only signed-in customers can place orders or read their own history.
  • Changing a product price afterward does not alter existing order totals.
  • Replaying the same checkout token produces one order and one stock deduction.
  • A customer cannot fulfill an order; an administrator can.
  • A failed checkout leaves all stock unchanged.

5. Predict, change and observe

In two isolated customer sessions, try to buy the last unit of the same product. Also retry a successful request using its original token.

Compare your prediction with the expected result

What you should observe

At most one last-unit order succeeds. Replaying its original token does not create another order.

Why it happens

The stock condition handles competing buyers. The unique attempt identity handles duplicate delivery of one buyer’s request. They solve different problems and both need verification.

6. Troubleshoot with evidence

A common mistake

Transactions need Atlas or a configured replica set. Disabling the submit button alone does not prevent duplicate orders; the database must enforce uniqueness.

Ordinary CRUD works but checkout fails with a transaction error.

Likely cause: The database is a standalone instance or lacks transaction support in its configuration.

Check and correct: Use the learning Atlas cluster or a configured replica set; do not remove the transaction and claim equivalent consistency.

An old order’s total changes after a product edit.

Likely cause: History is being reconstructed from current catalog prices.

Check and correct: Render the saved order item names and prices. Product IDs link identity, not the historical price.

7. Practice and explain it back

Your independent task

Add persistent user carts as a separate feature: store only product IDs and quantities under the session user ID; define and test how a guest cart merges on login.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why is a pending button insufficient to prevent duplicate orders?

Requests can be retried or sent directly outside the current button state. A stable request identity and database uniqueness enforce the rule on the server.

What does a transaction add beyond an atomic stock decrement?

It makes all item deductions and the order insertion one unit. A failure on any line rolls back earlier work instead of leaving a partial checkout.

Does a successful order here mean payment succeeded?

No. This is an explicitly simulated order flow. A payment integration needs verified provider confirmation and its own retry-safe state transitions.