Skip to the code

Member prices without caching the member

The tea page at Leaf and Kettle, app/teas/[slug]/page.tsx, shows a tea and the price for whoever is looking: silver members pay 10% less and gold members 20% less. Its TeaDetails component is cached with "use cache", and it reads the session cookie to find the member. Next.js stops the page with an error there: a cached component can't read cookies(), because what it returns is shared with everyone who asks with the same arguments. Fix the split.

Export TeaDetails({ slug, tier }), a cached Server Component that gets the member's tier, "guest", "silver", or "gold", as a prop and reads nothing from the request. It keeps its "use cache", cacheTag("tea:<slug>"), and cacheLife("max"), and renders an <article> with the tea's name in an <h1>, its description, and Price: $9.60 for that tier, written with dollars(priceFor(tea.price, tier)) from @/lib/teas.

Everything about the visitor stays outside the cache, in a component of its own inside the page's <Suspense>. It reads the session cookie, finds the member with findMember(token) from @/lib/members, and renders the greeting, Welcome back, Ana. for a member or Sign in for member prices. for a guest, then <TeaDetails> with the slug and the member's tier, or "guest".

No session cookie            → Sign in for member prices.   Oolong tea … Price: $12.00
session=token-ana (gold)     → Welcome back, Ana.           Oolong tea … Price: $9.60
session=token-ben (silver)   → Welcome back, Ben.           Oolong tea … Price: $10.80

The app's other files

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

export type Tier = "guest" | "silver" | "gold";
export type Tea = { slug: string; name: string; description: string; price: number };
 
/** The shop's teas, prices in cents: a stand-in for its database. */
export const teas: Tea[] = [
  { slug: "green", name: "Green tea", description: "Fresh and grassy, from Shizuoka.", price: 800 },
  { slug: "oolong", name: "Oolong tea", description: "Roasted, with a honeyed finish.", price: 1200 },
];
 
export async function getTeaRecord(slug: string): Promise<Tea | undefined> {
  return teas.find((tea) => tea.slug === slug);
}
 
/** What a tier pays, in cents: silver members get 10% off, gold members 20%. */
export function priceFor(price: number, tier: Tier): number {
  const off = tier === "gold" ? 0.2 : tier === "silver" ? 0.1 : 0;
  return Math.round(price * (1 - off));
}
 
/** "$9.60" for 960 cents. */
export const dollars = (cents: number) => `$${(cents / 100).toFixed(2)}`;

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

export type Member = { id: string; name: string; tier: "silver" | "gold" };
 
/** Signed-in members by session token, the value of the `session` cookie: a stand-in for the session store. */
const sessions = new Map<string, Member>([
  ["token-ana", { id: "u_ana", name: "Ana", tier: "gold" }],
  ["token-ben", { id: "u_ben", name: "Ben", tier: "silver" }],
  ["token-cal", { id: "u_cal", name: "Cal", tier: "gold" }],
]);
 
/** The member a session token belongs to, or null. */
export async function findMember(token: string): Promise<Member | null> {
  return sessions.get(token) ?? null;
}

What the tests check

  1. a guest sees the regular price and an invitation to sign in
    const visit = (session) => withRequest({ cookies: session ? { session } : {} }, () => renderServer(<Page params={params({ slug: "oolong" })} />));
    const details = async (props) => {
      try {
        return await TeaDetails(props);
      } catch (error) {
        throw new Error("TeaDetails must run with no request at all, as a cached component does, but it threw: " + error.message);
      }
    };
    await visit();
    expect(screen.getByText("Sign in for member prices.")).toBeInTheDocument();
    expect(screen.getByRole("heading", { level: 1, name: "Oolong tea" })).toBeInTheDocument();
    expect(screen.getByText("Roasted, with a honeyed finish.")).toBeInTheDocument();
    expect(screen.getByText("Price: $12.00")).toBeInTheDocument();
    
  2. a member is greeted by name and sees their tier's price
    const visit = (session) => withRequest({ cookies: session ? { session } : {} }, () => renderServer(<Page params={params({ slug: "oolong" })} />));
    const details = async (props) => {
      try {
        return await TeaDetails(props);
      } catch (error) {
        throw new Error("TeaDetails must run with no request at all, as a cached component does, but it threw: " + error.message);
      }
    };
    await visit("token-ana");
    expect(screen.getByText("Welcome back, Ana.")).toBeInTheDocument();
    expect(screen.getByText("Price: $9.60")).toBeInTheDocument();
    cleanup();
    await visit("token-ben");
    expect(screen.getByText("Welcome back, Ben.")).toBeInTheDocument();
    expect(screen.getByText("Price: $10.80")).toBeInTheDocument();
    
  3. TeaDetails takes the tier as a prop and needs no request
    const visit = (session) => withRequest({ cookies: session ? { session } : {} }, () => renderServer(<Page params={params({ slug: "oolong" })} />));
    const details = async (props) => {
      try {
        return await TeaDetails(props);
      } catch (error) {
        throw new Error("TeaDetails must run with no request at all, as a cached component does, but it threw: " + error.message);
      }
    };
    render(await details({ slug: "oolong", tier: "gold" }));
    expect(screen.getByRole("heading", { level: 1, name: "Oolong tea" })).toBeInTheDocument();
    expect(screen.getByText("Price: $9.60")).toBeInTheDocument();
    cleanup();
    render(await details({ slug: "green", tier: "guest" }));
    expect(screen.getByRole("heading", { level: 1, name: "Green tea" })).toBeInTheDocument();
    expect(screen.getByText("Price: $8.00")).toBeInTheDocument();
    
  4. two gold members get the very same article, with nothing about them in it
    const visit = (session) => withRequest({ cookies: session ? { session } : {} }, () => renderServer(<Page params={params({ slug: "oolong" })} />));
    const details = async (props) => {
      try {
        return await TeaDetails(props);
      } catch (error) {
        throw new Error("TeaDetails must run with no request at all, as a cached component does, but it threw: " + error.message);
      }
    };
    const first = await visit("token-ana");
    const article = first.container.querySelector("article");
    expect(article).not.toBe(null);
    expect(article).not.toHaveTextContent("Ana");
    const html = article.outerHTML;
    cleanup();
    const second = await visit("token-cal");
    expect(screen.getByText("Welcome back, Cal.")).toBeInTheDocument();
    expect(second.container.querySelector("article").outerHTML).toBe(html);
    
  5. TeaDetails starts with "use cache" and is cached under the tea's tag for max
    const visit = (session) => withRequest({ cookies: session ? { session } : {} }, () => renderServer(<Page params={params({ slug: "oolong" })} />));
    const details = async (props) => {
      try {
        return await TeaDetails(props);
      } catch (error) {
        throw new Error("TeaDetails must run with no request at all, as a cached component does, but it threw: " + error.message);
      }
    };
    const expectUseCache = (fn, name) => {
      if (!/\)\s*(=>\s*)?\{\s*(["'])use cache\2/.test(String(fn))) throw new Error(name + ' should start its body with "use cache", so Next.js caches what it returns');
    };
    expectUseCache(TeaDetails, "TeaDetails");
    await details({ slug: "green", tier: "silver" });
    expect(cache.tags).toEqual(["tea:green"]);
    expect(cache.lives).toEqual(["max"]);
    

Learn more

app/teas/[slug]/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).