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
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;
}
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();
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();
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();
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);
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"]);
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 Member prices without caching the member. 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.