Skip to the code

Cancel an order, checked again on the server

Each order's page at Leaf and Kettle, /orders/<id>, is only shown to the customer who placed the order and to staff, and while the order is still placed, it has a Cancel order button. The button's form runs cancelOrder, bound to the order's id with cancelOrder.bind(null, order.id), through useActionState. Write that Server Action in app/actions.ts.

Hiding the button isn't protection. A Server Action is an endpoint: anyone can send it a POST, with any argument, without ever seeing the page. So cancelOrder(orderId) checks everything again on the server, in this order.

Who's asking: getViewer() from @/lib/session reads the session cookie and returns the person signed in, or null. With no one, throw an Error with the message Sign in to cancel an order.

Which order: findOrder(orderId) from @/lib/orders. If there's none, or it's another customer's and the viewer isn't staff (role: "staff"), throw Order not found., the same message for both, so nobody can find out which order ids exist.

Whether it can still be cancelled: an honest customer can run into this one, when the order ships while the page is open, so it's an answer, not an error. If the status isn't placed, return { error: "This order can't be cancelled any more." } and change nothing.

Otherwise set the status with setOrderStatus(order.id, "cancelled"), revalidate both pages that show it, /orders and /orders/<id>, and return { error: null }.

Cookie: session=token-ben
cancelOrder("o_101")   // Ana's order: Ben never saw a button for it
→ Error: Order not found.
 
Cookie: session=token-ana
cancelOrder("o_101") → status "cancelled"
→ revalidatePath("/orders"), revalidatePath("/orders/o_101") → { error: null }

The app's other files

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

import { cookies } from "next/headers";
 
export type Viewer = { id: string; name: string; role: "customer" | "staff" };
 
const people = new Map<string, Viewer>([
  ["u_ana", { id: "u_ana", name: "Ana", role: "customer" }],
  ["u_ben", { id: "u_ben", name: "Ben", role: "customer" }],
  ["u_sam", { id: "u_sam", name: "Sam", role: "staff" }],
]);
 
/** Live sessions: the token in the `session` cookie, and whose it is. */
const sessions = new Map([
  ["token-ana", "u_ana"],
  ["token-ben", "u_ben"],
  ["token-sam", "u_sam"],
]);
 
/** Who sent this request, from the `session` cookie, or null when no one valid is signed in. */
export async function getViewer(): Promise<Viewer | null> {
  const token = (await cookies()).get("session")?.value;
  const userId = token ? sessions.get(token) : undefined;
  return (userId && people.get(userId)) || null;
}

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

export type OrderStatus = "placed" | "shipped" | "cancelled";
export type Order = { id: string; userId: string; status: OrderStatus; items: string };
 
/** What cancelOrder answers: an error an honest customer can meet, or null. */
export type CancelResult = { error: string | null };
 
/** Every order: a stand-in for the shop's database. */
export const orders: Order[] = [
  { id: "o_101", userId: "u_ana", status: "placed", items: "2 × Green tea" },
  { id: "o_102", userId: "u_ana", status: "shipped", items: "1 × Oolong tea" },
  { id: "o_103", userId: "u_ben", status: "placed", items: "3 × Mint tea" },
];
 
export async function findOrder(id: string): Promise<Order | undefined> {
  return orders.find((order) => order.id === id);
}
 
export async function setOrderStatus(id: string, status: OrderStatus) {
  const order = orders.find((entry) => entry.id === id);
  if (order) order.status = status;
}

app/orders/[id]/page.tsx, read-only. Import it as @/app/orders/[id]/page.

import { notFound } from "next/navigation";
import { cancelOrder } from "@/app/actions";
import { findOrder } from "@/lib/orders";
import { getViewer } from "@/lib/session";
import CancelButton from "./cancel-button";
 
export default async function OrderPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const viewer = await getViewer();
  const order = await findOrder(id);
  // Only the customer who placed the order, or staff, may see it.
  if (!viewer || !order || (order.userId !== viewer.id && viewer.role !== "staff")) notFound();
 
  return (
    <main>
      <h1>Order {order.id}</h1>
      <p>
        {order.items}: {order.status}
      </p>
      {order.status === "placed" && <CancelButton cancel={cancelOrder.bind(null, order.id)} />}
    </main>
  );
}

app/orders/[id]/cancel-button.tsx, read-only. Import it as @/app/orders/[id]/cancel-button.

"use client";
 
import { useActionState } from "react";
import type { CancelResult } from "@/lib/orders";
 
export default function CancelButton({ cancel }: { cancel: () => Promise<CancelResult> }) {
  const [state, formAction, pending] = useActionState<CancelResult | null>(() => cancel(), null);
 
  return (
    <form action={formAction}>
      <button type="submit" disabled={pending}>
        Cancel order
      </button>
      {state?.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

What the tests check

  1. the customer can cancel their own placed order, and both pages are revalidated
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    expect(await as("token-ana", () => cancelOrder("o_101"))).toEqual({ error: null });
    expect(statusOf("o_101")).toBe("cancelled");
    expect([...cache.revalidatedPaths].sort()).toEqual(["/orders", "/orders/o_101"]);
    
  2. works from the order page's Cancel order button
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    await openOrder("token-ana", "o_101");
    await as("token-ana", async () => {
      await user.click(screen.getByRole("button", { name: "Cancel order" }));
      await flush();
    });
    expect(statusOf("o_101")).toBe("cancelled");
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    
  3. refuses a request with no session, or a session that doesn't exist
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    await expect(as(null, () => cancelOrder("o_101"))).rejects.toThrow("Sign in to cancel an order.");
    await expect(as("token-forged", () => cancelOrder("o_101"))).rejects.toThrow("Sign in to cancel an order.");
    await expect(as(null, () => cancelOrder("o_999"))).rejects.toThrow("Sign in to cancel an order.");
    expect(statusOf("o_101")).toBe("placed");
    expect(cache.revalidatedPaths).toEqual([]);
    
  4. hides another customer's order, and refuses to cancel it all the same
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    expect(await accessErrorOf(() => openOrder("token-ben", "o_101"))).toBe(404);
    await expect(as("token-ben", () => cancelOrder("o_101"))).rejects.toThrow("Order not found.");
    await expect(as("token-ben", () => cancelOrder("o_102"))).rejects.toThrow("Order not found.");
    await expect(as("token-ben", () => cancelOrder("o_999"))).rejects.toThrow("Order not found.");
    expect(statusOf("o_101")).toBe("placed");
    expect(cache.revalidatedPaths).toEqual([]);
    
  5. staff can cancel any customer's placed order
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    await openOrder("token-sam", "o_103");
    expect(screen.getByRole("button", { name: "Cancel order" })).toBeInTheDocument();
    expect(await as("token-sam", () => cancelOrder("o_103"))).toEqual({ error: null });
    expect(statusOf("o_103")).toBe("cancelled");
    await expect(as("token-sam", () => cancelOrder("o_999"))).rejects.toThrow("Order not found.");
    
  6. a shipped order has no button, and the action won't cancel it, even for staff
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    await openOrder("token-ana", "o_102");
    expect(screen.queryByRole("button", { name: "Cancel order" })).not.toBeInTheDocument();
    expect(await as("token-ana", () => cancelOrder("o_102"))).toEqual({ error: "This order can't be cancelled any more." });
    expect(await as("token-sam", () => cancelOrder("o_102"))).toEqual({ error: "This order can't be cancelled any more." });
    expect(statusOf("o_102")).toBe("shipped");
    expect(cache.revalidatedPaths).toEqual([]);
    
  7. an order that ships while the page is open gets an answer, not an error
    const as = (token, work) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, work);
    const statusOf = (id) => orders.find((order) => order.id === id).status;
    const openOrder = (token, id) => withRequest({ cookies: { session: token } }, () => renderServer(<Page params={params({ id })} />));
    await openOrder("token-ana", "o_101");
    await setOrderStatus("o_101", "shipped");
    await as("token-ana", async () => {
      await user.click(screen.getByRole("button", { name: "Cancel order" }));
      await flush();
    });
    expect(screen.getByRole("alert")).toHaveTextContent("This order can't be cancelled any more.");
    expect(statusOf("o_101")).toBe("shipped");
    

Learn more

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