Skip to the code

An order page only its customer can open

Leaf and Kettle's customers see each of their orders at /account/orders/<id>, and order ids are numbers handed out one after another: 1001, 1002, 1003. Anyone signed in can type the next number into the address bar. Write app/account/orders/[id]/page.tsx so that only the customer who placed an order can see it. The bug it must not have is called an insecure direct object reference (IDOR): a page that trusts the id in the URL to pick a record, without asking whose record it is.

Start with verifySession() from @/lib/dal, before anything else. It returns { userId } for a signed-in customer and redirects everyone else to /sign-in, so a guest never causes a database lookup.

Then load the order with getOrder(id) from @/lib/orders, which returns any order by its id, whoever placed it. When there's no such order, or its customerId isn't the visitor's userId, call notFound(): the same 404 for both, so trying ids tells nobody which orders exist.

For the customer's own order, show an <h1> like Order 1001, a list with an item for each line like 2 × Green tea, a paragraph Total: $8.00, and a paragraph Deliver to 4 Willow Lane, Bath.

Export generateMetadata too, with a title like Order 1001 (delivered). Next.js calls it on its own, not through the page, so it needs the same check. Write the check once, in a function both of them call.

Cookie: session=token-ana
/account/orders/1001   → Order 1001, 2 × Green tea, Total: $8.00, title "Order 1001 (delivered)"
/account/orders/1002   → 404 (Ben's order)
/account/orders/9999   → 404 (no such order)
no session cookie      → redirect("/sign-in"), and getOrder is never called

The app's other files

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

import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
 
/** Live sessions: the token in the `session` cookie, and whose it is. */
const sessions = new Map([
  ["token-ana", "u_ana"],
  ["token-ben", "u_ben"],
]);
 
/** The signed-in customer, from the `session` cookie. Anyone else is redirected to /sign-in. */
export const verifySession = cache(async (): Promise<{ userId: string }> => {
  const token = (await cookies()).get("session")?.value;
  const userId = token ? sessions.get(token) : undefined;
  if (!userId) redirect("/sign-in");
  return { userId };
});

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

export type OrderLine = { name: string; quantity: number };
export type Order = {
  id: string;
  customerId: string;
  status: "placed" | "shipped" | "delivered";
  lines: OrderLine[];
  totalCents: number;
  address: string;
};
 
/** Every order, whoever placed it: a stand-in for the shop's database. */
export const orders: Order[] = [
  { id: "1001", customerId: "u_ana", status: "delivered", lines: [{ name: "Green tea", quantity: 2 }], totalCents: 800, address: "4 Willow Lane, Bath" },
  {
    id: "1002",
    customerId: "u_ben",
    status: "shipped",
    lines: [
      { name: "Oolong tea", quantity: 1 },
      { name: "Mint tea", quantity: 3 },
    ],
    totalCents: 1600,
    address: "12 Harbour Road, Leith",
  },
  { id: "1003", customerId: "u_ana", status: "placed", lines: [{ name: "Mint tea", quantity: 1 }], totalCents: 350, address: "4 Willow Lane, Bath" },
];
 
/** Every id getOrder was asked for, in order: the tests read it. */
export const lookups: string[] = [];
 
/** The order with this id, whoever placed it, or undefined when there's none. */
export async function getOrder(id: string): Promise<Order | undefined> {
  lookups.push(id);
  const order = orders.find((entry) => entry.id === id);
  return order && { ...order, lines: order.lines.map((line) => ({ ...line })) };
}

What the tests check

  1. shows each customer their own order
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    await openOrder("token-ana", "1001");
    expect(screen.getByRole("heading", { level: 1, name: "Order 1001" })).toBeInTheDocument();
    expect(lines()).toEqual(["2 × Green tea"]);
    expect(screen.getByText("Total: $8.00")).toBeInTheDocument();
    expect(screen.getByText("Deliver to 4 Willow Lane, Bath")).toBeInTheDocument();
    cleanup();
    await openOrder("token-ben", "1002");
    expect(screen.getByRole("heading", { level: 1, name: "Order 1002" })).toBeInTheDocument();
    expect(lines()).toEqual(["1 × Oolong tea", "3 × Mint tea"]);
    expect(screen.getByText("Total: $16.00")).toBeInTheDocument();
    
  2. answers 404 for another customer's order
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    expect(await accessErrorOf(() => openOrder("token-ben", "1001"))).toBe(404);
    expect(await accessErrorOf(() => openOrder("token-ben", "1003"))).toBe(404);
    expect(await accessErrorOf(() => openOrder("token-ana", "1002"))).toBe(404);
    
  3. answers the same 404 for an order that doesn't exist
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    for (const id of ["9999", "1004", "abc"]) {
      expect(await accessErrorOf(() => openOrder("token-ana", id))).toBe(404);
    }
    
  4. sends a guest to sign in before looking anything up
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    for (const token of [null, "token-forged"]) {
      expect((await redirectOf(() => openOrder(token, "1001"))).url).toBe("/sign-in");
      expect((await redirectOf(() => openOrder(token, "9999"))).url).toBe("/sign-in");
    }
    expect(lookups).toEqual([]);
    
  5. generateMetadata titles the customer's own order
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    expect((await titleOf("token-ana", "1003")).title).toBe("Order 1003 (placed)");
    expect((await titleOf("token-ben", "1002")).title).toBe("Order 1002 (shipped)");
    
  6. generateMetadata keeps other customers' orders to itself
    const as = (token, work) => withRequest({ cookies: token ? { session: token } : {} }, work);
    const openOrder = (token, id) => as(token, () => renderServer(<Page params={params({ id })} />));
    const titleOf = (token, id) => as(token, () => generateMetadata({ params: params({ id }) }));
    const lines = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    expect(await accessErrorOf(() => titleOf("token-ben", "1001"))).toBe(404);
    expect(await accessErrorOf(() => titleOf("token-ana", "9999"))).toBe(404);
    expect((await redirectOf(() => titleOf(null, "1002"))).url).toBe("/sign-in");
    expect(lookups).not.toContain("1002");
    

Learn more

app/account/orders/[id]/page.tsxSaved 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).