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 }
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>
);
}
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"]);
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();
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([]);
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([]);
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.");
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([]);
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");
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).
I'm here to help with Cancel an order, checked again on the server. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.