Most Next.js caching bugs I have shipped had the same shape. The page worked on my machine, the build was green, and a week later someone wrote in to say the site was showing them something that was no longer true. A price that had changed. A review that never appeared. A "3 left" badge on a book that had sold out on Tuesday.
Next.js 16 changed how caching works, and I think for the better. With Cache Components turned on, nothing is cached unless you say so, and the framework refuses to build a page that would block on data you forgot to think about. That second part is the interesting one. It turns a whole class of "works on my machine" bugs into build errors, and the error messages are good enough to learn from.
This tutorial is built around that. You start with a small bookshop called Shelf that has no caching at all, you let Next.js yell at you, and you fix it one error at a time until the build is green and every page is a partial prerender. Then the second half flips it around. You get a finished copy of the same shop with four bugs planted in it, a ticket queue written the way customers actually write tickets, and a feature request. That half is meant to feel like the take-home or live debugging round a lot of teams now run instead of algorithm puzzles.
Everything here is runnable. Each project has a box that opens it in StackBlitz, which runs a real Next.js dev server inside your browser, so you can follow along without installing anything. Every terminal output quoted below was copied from a real run of these exact projects on Next.js 16.4.6, not written from memory.
How to use the runnable boxes
Each box has two buttons. "Run it in StackBlitz" opens the project in a new tab, installs packages and starts npm run dev. The first boot takes about a minute. "Browse the code here" shows the files inline without running them, which is handy when you just want to look something up.
A few things I learned getting this to work, so you don't trip on them:
- Use a desktop Chromium browser (Chrome, Edge, Brave). StackBlitz only fully supports its WebContainers there.
- The projects run
next dev --webpack, not Turbopack. Inside the browser, Next.js runs on its WebAssembly build, and that build does not support Turbopack. If you see "Turbopack is not supported on this platform", the dev command lost its flag. - They pin TypeScript 6.0.3. TypeScript 7 ships a native Go binary, which can't run in a browser sandbox. (If you want the story behind that, I wrote up the TypeScript 7 migration separately.)
npm run buildandnpm run startare what tell the truth about caching. You can run them in the StackBlitz terminal, but they are slow there. For the interview round I'd use StackBlitz's download option and run the project locally with Node 20.9 or newer.
The mental model: three kinds of content
Before touching code, here is the whole idea in one table. With cacheComponents on, every piece of a page falls into one of three buckets, and the build sorts them for you.
| What it is | How you write it | Where it ends up |
|---|---|---|
| Static | Plain JSX, imports, pure computation | Baked into the static shell at build time |
| Cached | An async function or component with 'use cache' |
Also in the static shell, refreshed on the schedule cacheLife gives it or when you invalidate its cacheTag |
| Request-time | Anything reading cookies(), headers(), searchParams, uncached I/O |
Streamed in per request, behind a <Suspense> fallback that ships in the shell |
The static shell is HTML that can sit on a CDN. A visitor gets it instantly, and the request-time holes stream into it as they resolve. Next.js calls this Partial Prerendering, and in the build output it shows up as a little half-filled circle, ◐. By the end of the build-along every route in Shelf will have one.
The rule the framework enforces is simple to say and annoying to live with at first: if a component waits on uncached or request-time data, it must either be cached or sit inside a <Suspense> boundary. Otherwise the build fails. There is an escape hatch, export const instant = false, which allows a route to block, but I don't use it anywhere here and I'd treat it as a last resort.
If Partial Prerendering is new to you, the older PPR explainer covers the concept from the Next 15 days. The API surface has changed a lot since, so trust this page for the details.
Meet Shelf
Shelf is deliberately small. Four books, a fake database, a cookie cart, reviews, and an admin form that pretends to be a CMS webhook.
The files you'll touch:
| File | What it does |
|---|---|
lib/db.ts |
An in-memory "database". Every call sleeps for 150 to 400 ms and logs a [db] line, so you can see exactly when the database is hit. |
lib/data.ts |
The read functions pages call: getBooks, getBook, getReviews, getStock. In the starter they are plain async functions. |
lib/cart.ts |
Reads and writes the cart cookie. |
app/layout.tsx |
Header with a cart count badge. |
app/page.tsx |
Home page: a hero and a grid of books. |
app/books/[slug]/page.tsx |
Book page: details, live stock, add to cart, reviews, review form. |
app/cart/page.tsx |
Cart lines, total, checkout. |
app/actions.ts |
Server Actions for the cart, checkout and reviews. |
app/api/price/route.ts |
A Route Handler standing in for a CMS webhook that changes prices. |
The config already has Cache Components on:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
partialPrefetching is worth a sentence. The Next.js docs say to set it explicitly, because leaving it unset logs a warning, and it will be on by default in the next major version. It controls how <Link> prefetches routes, and it also changes one rule about dynamic route params, which bites us in step 4.
The fake database is the part I'd steal for your own experiments. Here's a slice of it:
// lib/db.ts (excerpt)
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
export async function dbListBooks(): Promise<Book[]> {
await sleep(400)
console.log('[db] list books')
return store.books.map((b) => ({ ...b }))
}
That sleep matters more than it looks. During a prerender, Next.js treats any work that doesn't finish right away (a timer, a network call, a real database query) as uncached I/O. A fake database that returned instantly would hide every problem we're about to find.
Step 1: let the guard rails talk
Start the dev server and open /, a book page, /cart and /admin. Every page renders and returns 200. The terminal disagrees. Here is what it printed for the home page:
[db] list books
GET / 200 in 696ms (next.js: 164ms, application-code: 533ms)
Error: Route "/": Next.js encountered uncached data during prerendering.
`fetch(...)` or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] Cache the data access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at dbListBooks (lib\db.ts:91:9)
at getBooks (lib\data.ts:4:21)
at BookGrid (app\page.tsx:18:31)
at HomePage (app\page.tsx:12:7)
Read the stack from the bottom. HomePage renders BookGrid, which calls getBooks, which calls dbListBooks, which waits on a timer. The message mentions fetch and connection(), but our code uses neither. The wording is generic; the stack trace is what points at the real line.
And /cart gets a different message, because the problem there is a cookie, not slow data:
Error: Route "/cart": Next.js encountered runtime data during prerendering.
`cookies()`, `headers()`, `params`, or `searchParams` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime
at readCart (lib\cart.ts:27:34)
at CartLink (app\layout.tsx:32:30)
at RootLayout (app\layout.tsx:21:13)
Notice what's missing from that second list of fixes. There's no [cache] option. You can't cache a cookie read into a shared cache, because a cookie belongs to one visitor. That difference between "uncached data" and "runtime data" is the whole lesson in miniature.
Checkpoint The cart badge lives in the layout, so every page reads the cookie. Why did dev only complain about the cookie on /cart?
Dev reports one problem per route, the first one it hits. On /, /admin and the book page, the uncached database read came first, so that's what you saw. On /cart the page content was already behind a <Suspense> boundary, so the layout's cookie read was the first problem left. Fix the obvious error and a new one can appear on the same route. That is normal, and it's why I lean on the build more than on dev.
Now run the build.
Generating static pages using 9 workers (0/12) ...
Error: Route "/_not-found": Next.js encountered uncached or runtime data during prerendering.
`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at nav (<anonymous>)
at header (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running `next dev`, then open "/_not-found" in your browser to investigate the error.
- Rerun the production build with `next build --debug-prerender` to generate better stack traces.
Error occurred prerendering page "/_not-found". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /_not-found/page: /_not-found, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
This one confused me the first time. There is no /_not-found in the app folder. It's the built-in 404 page, and it gets prerendered with your root layout around it. The stack, nav inside header inside body, points right at the cart badge in the layout. The build also stops at the first failing route, so you fix one thing, rebuild, and see the next.
Step 2: put the cookie behind Suspense
The cart badge needs the cookie, and the cookie only exists at request time. So the badge goes in a boundary with a fallback that looks almost the same:
// app/layout.tsx (metadata export omitted)
import Link from 'next/link'
import { Suspense } from 'react'
import { readCart } from '@/lib/cart'
import './globals.css'
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en">
<body>
<header className="site-header">
<Link href="/" className="logo">
Shelf
</Link>
<nav>
<Link href="/">Books</Link>
{/* The cart count reads a cookie, so it streams in at request time.
The fallback keeps the header in the static shell. */}
<Suspense fallback={<Link href="/cart">Cart</Link>}>
<CartLink />
</Suspense>
<Link href="/admin">Admin</Link>
</nav>
</header>
<main>{children}</main>
</body>
</html>
)
}
async function CartLink() {
const cart = await readCart()
const count = Object.values(cart).reduce((sum, qty) => sum + qty, 0)
return (
<Link href="/cart">
Cart{count > 0 && <span className="badge">{count}</span>}
</Link>
)
}
The fallback is a plain "Cart" link, so the header in the static shell is fully usable before the count arrives. A spinner would have been worse here. Good fallbacks look like the thing they're standing in for.
LayoutProps<'/'> is a global type Next.js generates from your routes. A gotcha: on a fresh checkout tsc --noEmit fails with Cannot find name 'LayoutProps' until you've run next dev, next build or next typegen once.
Rebuild. The error moves:
Error: Route "/admin": Next.js encountered uncached or runtime data during prerendering.
...
Error occurred prerendering page "/admin". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /admin/page: /admin, exiting the build.
Progress. The layout is fine now, and the build has moved on to a page that calls getBooks().
Step 3: cache the book list
The book list is the same for every visitor and changes a few times a day at most. That's exactly what 'use cache' is for:
// lib/data.ts
import { cacheLife, cacheTag } from 'next/cache'
import { dbListBooks } from './db'
// Shared by every visitor, changes a few times a day.
export async function getBooks() {
'use cache'
cacheLife('hours')
cacheTag('books')
return dbListBooks()
}
Three lines, three separate jobs:
'use cache'makes the function's return value cacheable. The arguments, plus any variables the function captures from outside, become the cache key. Here there are none, so there is one entry.cacheLife('hours')says how long that entry is good for. If you leave it out you get thedefaultprofile, and the docs recommend always setting one so the lifetime is visible where you read the code. I agree, mostly because nested caches with implicit lifetimes are miserable to reason about.cacheTag('books')gives the entry a name you can invalidate later. We use it in step 7.
The built-in profiles are worth knowing by heart, because the build output reports them back to you:
| Profile | stale (browser) |
revalidate (server) |
expire |
|---|---|---|---|
default |
5 minutes | 15 minutes | never |
seconds |
30 seconds | 1 second | 1 minute |
minutes |
5 minutes | 1 minute | 1 hour |
hours |
5 minutes | 1 hour | 1 day |
days |
5 minutes | 1 day | 1 week |
weeks |
5 minutes | 1 week | 30 days |
max |
5 minutes | 30 days | 1 year |
revalidate is when the server starts refreshing the entry in the background while still serving the old one. expire is when it gives up on the old one and makes the next request wait for fresh data. stale is how long the browser's router reuses what it already has without asking; Next.js never lets it go below 30 seconds, so prefetched links stay usable.
One threshold to remember: a cache with an expire under 5 minutes, which among the presets means only seconds, is too short to bake into a prerender. It becomes a dynamic hole instead and needs a <Suspense> around it like any other request-time data.
Rebuild again. / and /admin both pass now, because both only needed getBooks(). Next stop:
Error: Route "/books/[slug]": Next.js encountered uncached or runtime data during prerendering.
...
Error occurred prerendering page "/books/the-quiet-compiler". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /books/[slug]/page: /books/the-quiet-compiler, exiting the build.
Step 4: the book page, and the error that only dev catches
The book page reads three things: the book, its reviews and its stock. Two of them are cacheable:
// lib/data.ts (continued)
export async function getBook(slug: string) {
'use cache'
cacheLife('hours')
cacheTag('books', `book-${slug}`)
return dbGetBook(slug)
}
// Reviews change when someone posts one, so they get their own tag.
export async function getReviews(slug: string) {
'use cache'
cacheLife('days')
cacheTag(`reviews-${slug}`)
return dbListReviews(slug)
}
// Stock is never cached. Every request asks the database.
export async function getStock(slug: string) {
return dbGetStock(slug)
}
getBook carries two tags. books lets one webhook refresh every book at once, and book-${slug} would let you refresh a single one. slug is an argument, so each book gets its own entry automatically.
Stock is the interesting one. It changes on every sale, and showing a stale number is exactly the bug customers notice. So it stays uncached. Rebuild after caching the other two and you get the same /books/[slug] error, except the stack now starts at article (<anonymous>). That's the <Stock> component, still waiting on the database outside any boundary.
Checkpoint Should you fix the stock error with 'use cache' and cacheLife('seconds')?
You could, and it would build, because a seconds cache is excluded from the prerender and acts as a dynamic hole. But it buys you almost nothing. Stock still has to be fetched at request time, you've just added a one-second window in which two shoppers can both see "1 left". When data has to be fresh per request, say so honestly with <Suspense> and no cache.
Wrap stock in its own boundary:
{/* Stock changes with every sale, so it is never cached. */}
<Suspense fallback={<p className="stock muted">Checking stock…</p>}>
<Stock slug={slug} />
</Suspense>
And the build passes. Green. Every route shows ◐.
Here's where I'd have stopped a year ago, and I'd have been wrong. The starter's page still begins like this:
export default async function BookPage({ params }: PageProps<'/books/[slug]'>) {
const { slug } = await params
const book = await getBook(slug)
if (!book) notFound()
// ...
}
Start the dev server, open a book, and look at the terminal:
Error: Route "/books/[slug]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
at BookPage (app\books\[slug]\page.tsx:15:20)
> 15 | const { slug } = await params
The build didn't catch this, so what's actually wrong? generateStaticParams returns the four known slugs, and those pages prerender fine. But with partialPrefetching on, Next.js also builds a generic App Shell for /books/[slug], the version it serves instantly for a slug it hasn't seen yet. Awaiting params at the very top means that generic shell has nothing in it. I checked the build output: the App Shell file for [slug] was 0 bytes.
The fix is to pass the params promise down and await it inside a boundary:
// app/books/[slug]/page.tsx
export async function generateStaticParams() {
const books = await getBooks()
return books.map((book) => ({ slug: book.slug }))
}
export default function BookPage({ params }: PageProps<'/books/[slug]'>) {
// Don't await params here. Passing the promise down and awaiting it inside
// <Suspense> lets slugs we didn't prerender get an instant App Shell.
return (
<Suspense fallback={<p className="muted">Loading book…</p>}>
<BookDetails params={params} />
</Suspense>
)
}
async function BookDetails({ params }: Pick<PageProps<'/books/[slug]'>, 'params'>) {
const { slug } = await params
const book = await getBook(slug)
if (!book) notFound()
return (
<article className="book">
<h1>{book.title}</h1>
<p className="muted">by {book.author}</p>
<p>{book.blurb}</p>
<p className="price">{formatPrice(book.price)}</p>
<Suspense fallback={<p className="stock muted">Checking stock…</p>}>
<Stock slug={slug} />
</Suspense>
<form action={addToCart.bind(null, slug)}>
<button type="submit">Add to cart</button>
</form>
<section className="reviews">
<h2>Reviews</h2>
<Reviews slug={slug} />
<ReviewForm slug={slug} />
</section>
</article>
)
}
The page component isn't even async any more. After this change the App Shell file was 1,525 bytes and contained "Loading book…", and the dev error went away. The same structure works in layouts: if a layout needs a param, push the await into a small child component inside <Suspense> instead of doing it at the top.
The lesson I took from this step: a green build is necessary, not sufficient. Leave next dev running in a second terminal and actually read it.
Step 5: read the build output like a diff
Here's the full route table from the finished app:
Route (app) Revalidate Expire
┌ ◐ / 1h 1d
├ ◐ /_not-found
├ ◐ /admin 1h 1d
├ ƒ /api/price
├ /books/[slug]
│ ├ ◐ /books/[slug]
│ ├ ◐ /books/the-quiet-compiler 1h 1d
│ ├ ◐ /books/cache-and-release 1h 1d
│ └ ◐ [+2 more paths]
├ ◐ /cart
└ ◐ /cart/thanks
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
ƒ (Dynamic) server-rendered on demand
A few things worth noticing:
/says1hand1d. Those are therevalidateandexpireof thehoursprofile fromgetBooks(). The route inherits the lifetime of the caches inside it./books/[slug]appears on its own line as well as the four real slugs. That's the App Shell from step 4./cart/thanksis a static thank-you page, yet it's◐too. The layout's cart badge is a dynamic hole on every page. That's fine. The shell is still static; one small piece streams./api/priceisƒ. It's a POST handler, so there is nothing to prerender.
I keep the previous build's table around and diff it after a change. If a route flips from ◐ to ƒ, or its lifetime column changes, something moved a cache or a request-time read, and I want to know which.
Step 6: prove it in production mode
Dev mode re-renders everything and replays cached console.log lines with an inverted Cache label in front of them, which makes it easy to think the database was hit when it wasn't. To see what really happens, run npm run build && npm run start and watch the [db] lines.
Here's what I measured with curl against next start on my laptop:
| Request | Status | Time to first byte | [db] lines logged |
|---|---|---|---|
GET /, first |
200 | 136 ms | none |
GET /, second |
200 | 10 ms | none |
GET /books/the-quiet-compiler, first |
200 | 50 ms | get stock |
GET /books/the-quiet-compiler, second |
200 | 6.5 ms | get stock |
The home page never touches the database. The book list was fetched once, at build time. The book page hits the database for stock on every request and nothing else. Stock is the only thing we asked to be live, and it's the only thing that's live.
(One thing I can't fully explain: on every book page request the log showed [db] get stock twice, not once. My guess is a second render pass Cache Components does, but I haven't confirmed it, so treat that as a guess. The stock read is cheap here; in a real app I'd wrap it in React's cache() to dedupe it within a request.)
You can also look straight at the prerendered file. .next/server/app/books/the-quiet-compiler.html contains the book title, the seeded review and the text "Checking stock…", but not the stock number. The live response streams the number in after the shell, as a hidden chunk React swaps into place:
<div hidden id="S:1"><p class="stock low">Only <!-- -->3<!-- --> left</p></div>
That's Partial Prerendering in one line. The shell went out first; the hole filled in a moment later.
Step 7: writes, and why updateTag exists
Reading is half the story. The moment someone posts a review, the cached getReviews for that book is wrong. Here's the review Server Action in the finished app:
// app/actions.ts (excerpt)
'use server'
import { updateTag } from 'next/cache'
import { after } from 'next/server'
import { dbAddReview } from '@/lib/db'
export type ReviewState = { error?: string; ok?: boolean }
export async function addReview(
slug: string,
_prev: ReviewState,
formData: FormData,
): Promise<ReviewState> {
const name = String(formData.get('name') ?? '').trim() || 'Anonymous'
const text = String(formData.get('text') ?? '').trim()
const rating = Number(formData.get('rating') ?? 5)
if (text.length < 3) return { error: 'Write at least a few words.' }
if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
return { error: 'Pick a rating from 1 to 5.' }
}
await dbAddReview({ slug, name, rating, text })
// Expire the reviews for this book now, so the author sees their own review
// on the very next render instead of a stale list.
updateTag(`reviews-${slug}`)
after(() => {
console.log(`[audit] review added to ${slug} by ${name}`)
})
return { ok: true }
}
The form is a small client component using useActionState(addReview.bind(null, slug), {}), which gives you the returned state and a pending flag.
updateTag is the read-your-own-writes tool. It expires the tag immediately, so the next render waits for fresh data instead of serving the old list. When I posted a review, the server log went:
[db] add review the-quiet-compiler
[db] get stock the-quiet-compiler
[db] list reviews the-quiet-compiler
[audit] review added to the-quiet-compiler by Ana
The write, then a re-render of the page in the same response (stock, plus the reviews, which were refetched because their tag had just expired), then the audit line. after() runs its callback once the response is finished, which is why the audit log comes last. It's the right home for logging and analytics you don't want slowing the user down.
There are two rules to burn in. updateTag only works inside a Server Action, and that restriction is the point: it's meant for "the person who just clicked must see their change". For everything else there's revalidateTag.
Checkpoint What would the reviewer see if the action called revalidateTag(reviews-${slug}, 'max') instead?
Their own review would be missing on that render. With the 'max' profile, revalidateTag marks the data stale and serves the old version while it refreshes in the background, so the person who just posted sees the stale list once. Everyone after them sees the new one. That's great for a CMS edit nobody is staring at, and it reads as a bug to someone who just hit "Post".
Step 8: webhooks get stale-while-revalidate
Prices in Shelf change from outside the app, through a webhook. The /admin page has a plain HTML form that posts to the same Route Handler a CMS would call. Route Handlers can't use updateTag, so this is revalidateTag's home:
// app/api/price/route.ts
import { revalidateTag } from 'next/cache'
import { dbSetPrice } from '@/lib/db'
export async function POST(request: Request) {
const form = await request.formData()
const slug = String(form.get('slug') ?? '')
const price = Number(form.get('price'))
if (!slug || !Number.isFinite(price) || price <= 0) {
return new Response('Send a slug and a positive price.', { status: 400 })
}
if (!(await dbSetPrice(slug, price))) {
return new Response(`No book called "${slug}".`, { status: 404 })
}
// A webhook is not a Server Action, so updateTag() is not allowed here.
// revalidateTag with 'max' marks the books stale: the next visitor still
// gets the old page instantly while a fresh one renders in the background.
revalidateTag('books', 'max')
return Response.redirect(new URL('/', request.url), 303)
}
I tested this against next start with curl (if you want to fire webhooks by hand, the cURL command builder saves some typing), changing The Quiet Compiler from $24 to $30 and then loading the home page three times:
HTTP/1.1 303 See Other
[db] set price the-quiet-compiler = 30
GET / #1 price=$24.00 log: [db] list books
GET / #2 price=$30.00 log: (none)
GET / #3 price=$30.00
That's stale-while-revalidate, exactly as documented. The first visitor after the webhook got the old page instantly, and their request kicked off the refresh (that's the list books line). The second visitor got the new price. Nobody waited.
If a webhook really needs the old data gone before anyone sees it, for a price error, say, the docs give you revalidateTag('books', { expire: 0 }), which makes the next request block on fresh data. One more thing the docs point out: the revalidation is triggered by requests, not by the revalidateTag call. Pages using the tag refresh as people visit them, not all at once.
Step 9: per-visitor data that still uses the cache
The cart is the most personal page on the site, and it still uses the shared cache. The cookie read happens in a component inside <Suspense>, and the slugs it finds get passed into the cached getBook:
// app/cart/page.tsx (excerpt)
async function CartContents() {
// The cart lives in a cookie, so this part runs per request.
const cart = await readCart()
const entries = Object.entries(cart)
if (entries.length === 0) {
return (
<p>
Your cart is empty. <Link href="/">Browse books</Link>
</p>
)
}
// The slug comes from the cookie, but getBook(slug) is still cached:
// runtime values passed as arguments just become part of the cache key.
const lines = await Promise.all(
entries.map(async ([slug, qty]) => ({ slug, qty, book: await getBook(slug) })),
)
const total = lines.reduce((sum, line) => sum + (line.book?.price ?? 0) * line.qty, 0)
// ...render lines, total and the checkout form
}
This is the pattern the docs recommend over everything else: read request data outside the cached scope, pull out the plain values you need, and pass them in as arguments. My test cart with two copies of The Quiet Compiler rendered The Quiet Compiler × 2 and Total: $60.00. That total uses the $30 price from the webhook in step 8, which is the books tag doing its job inside a per-visitor page.
There's also 'use cache: private', which lets a cached function read cookies directly and keeps the result out of shared server caches. The docs frame it as the option for when refactoring to pass values in isn't practical, and I've followed that advice; Shelf doesn't need it.
Checkout is the last action. It decrements stock, clears the cookie, logs an audit line with after(), and redirects. The log for buying two copies:
[db] take stock the-quiet-compiler x2
[audit] checkout: {"the-quiet-compiler":2}
Stock isn't cached anywhere, so there's nothing to invalidate. The book page shows the new number on the next request by design. Hold that thought, because it's about to matter.
Here's the finished app, if you want to compare against your version:
Part two: the debugging round
Hiring has shifted a lot in the last two years. A growing number of teams have swapped the algorithm round for something closer to the job: here is a codebase you didn't write, here are some bug reports, you can use your usual tools (often including an AI assistant), talk us through it. I think it's a better test, and it rewards a specific skill that tutorials rarely practice, which is forming a hypothesis from a symptom before you touch code.
So here's one. The project below is the finished Shelf with four bugs planted in it, plus one feature request. Open TICKETS.md first.
How I'd run it on yourself:
- Give yourself 60 minutes for all five. That's tight on purpose.
- Before opening any file for a ticket, write one sentence saying what you think is wrong. Then go and check. Being wrong is fine; guessing nothing is the habit interviewers watch for.
- Reproduce under
npm run build && npm run start. Two of these bugs never show up in dev in a way you'd notice. - If you use an AI assistant, make it show you the evidence (a log line, a status code, a diff in behavior), not just a patch. "It compiles now" isn't a fix.
Here are the tickets as the customers wrote them, shortened. Hints and full solutions are folded below each one. Open them only after you've had a real go.
SHELF-101: "My review disappeared"
I wrote a review for Cache and Release and hit "Post review". It isn't on the page. I refreshed a few times and the page still only shows Hannah's review.
Support adds that the review is in the database and there's nothing in the error logs.
Hint Where to look
The review was saved, so the write path works. Something is supposed to tell the cache that this book's reviews changed. Compare the string that names the cache entry with the string used to expire it, character by character.
Solution A tag that doesn't match
getReviews tags its entry with `reviews:${slug}` (a colon) while addReview calls updateTag(`reviews-${slug}`) (a hyphen). updateTag on a tag nobody uses is a silent no-op, so the old list stays cached for its full days lifetime. When I reproduced it, the server logged [db] add review cache-and-release and the audit line, but no list reviews, which is the giveaway: nothing was refetched.
export async function getReviews(slug: string) {
'use cache'
cacheLife('days')
- cacheTag(`reviews:${slug}`)
+ cacheTag(`reviews-${slug}`)
return dbListReviews(slug)
}
The longer-term fix is to stop typing tag strings twice. A tiny tags.ts with export const reviewsTag = (slug: string) => reviews-${slug}`` used in both places makes this bug impossible.
SHELF-102: "Home page says Only 3 left for a book that is sold out"
A customer bought the last three copies of The Quiet Compiler this morning. Its book page correctly says "Sold out", but the home page still shows the orange "Only 3 left" badge, and it was still there after lunch.
Hint Where to look
The book page gets stock one way and the home page gets it another. Find where the home page's number comes from, and ask which cacheLife it lives under.
Solution Live data frozen inside a cache
Someone "helpfully" enriched getBooks() with stock so the grid could show a badge:
export async function getBooks() {
'use cache'
cacheLife('hours')
cacheTag('books')
const books = await dbListBooks()
return Promise.all(
books.map(async (book) => ({ ...book, stock: await dbGetStock(book.slug) })),
)
}
Everything a cached function reads is frozen into its output, so the stock numbers are now cached for an hour and baked into the home page's static shell. Checkout never touches the books tag (and shouldn't). In my repro the book page said Sold out while the home page said Only 3 left on two requests in a row.
The fix is to keep stock out of the cached function and give each card its own small dynamic hole. The grid stays in the static shell; only the badges stream.
// app/page.tsx
<Link href={`/books/${book.slug}`} className="card">
<h2>{book.title}</h2>
<p className="muted">{book.author}</p>
<p className="price">{formatPrice(book.price)}</p>
<Suspense fallback={null}>
<StockBadge slug={book.slug} />
</Suspense>
</Link>
async function StockBadge({ slug }: { slug: string }) {
const left = await getStock(slug)
if (left === 0) return <p className="stock sold-out">Sold out</p>
if (left <= 3) return <p className="stock low">Only {left} left</p>
return null
}
After the fix the home badge read Sold out right after checkout. The general rule: when you add 'use cache', look at every value the function reads and ask if each one can be wrong for revalidate seconds without anyone minding.
SHELF-103: "Price changes from the CMS never show up"
When I change a price in the CMS, the webhook delivery log shows
500 Internal Server Errorfor every call to/api/price, and the site keeps showing the old price.
Hint Where to look
A 500 with an empty body means the handler threw. Run it under next start, post the admin form, and read the server log. The error message names the fix.
Solution The wrong invalidation API for the context
The handler calls updateTag('books'). My repro returned HTTP/1.1 500 Internal Server Error and the log said:
[db] set price the-quiet-compiler = 30
⨯ Error: updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag
Notice the order. The database write succeeded before the throw, so the price changed in storage and nothing was invalidated. That's arguably worse than failing early, and worth saying out loud in an interview: in a real system you'd want the write and the invalidation to fail or succeed together, or a retry to be safe.
-import { updateTag } from 'next/cache'
+import { revalidateTag } from 'next/cache'
...
- updateTag('books')
+ revalidateTag('books', 'max')
After the fix the webhook returned 303 and the new price appeared on the second page load, the stale-while-revalidate pattern from step 8.
SHELF-104: "Cart page broken once you add something"
The cart page is fine when it's empty, but as soon as I add a book and open it, my cart never shows up, so I can't check out.
Support adds that /cart still returns 200 and that next build passes.
Hint Where to look
A page that returns 200 but shows nothing inside its Suspense boundary usually means the boundary's content threw while streaming. The empty cart works because it returns early. Look at what renders only when the cart has items, and follow its calls all the way down.
Solution A cookie read hiding inside a cached component
A new free-shipping message was added as a cached component:
async function CartTotal() {
'use cache'
cacheLife('minutes')
const cart = await readCart()
// ...total and free-shipping note
}
readCart() calls cookies(). Request APIs aren't allowed anywhere in a cached scope's call stack, even behind a helper. The server log said:
⨯ Error: Route "/cart": `cookies()` can't be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache
Why did the build pass? CartTotal only renders after CartContents has awaited the cookie, and during the prerender that cookie read suspends, so the prerender never reaches CartTotal. I checked the other placement too: with <CartTotal /> as a direct sibling inside the page's boundary, next build fails with the same error. The Next.js docs warn about exactly this: on a dynamically rendered path it "can pass next build and fail under next start".
The fix is the step 9 pattern: read the cookie outside, pass the value in.
- <CartTotal />
+ <CartTotal cart={cart} />
...
-async function CartTotal() {
+// The cart is read outside and passed in, so it becomes part of the cache key.
+async function CartTotal({ cart }: { cart: Cart }) {
'use cache'
cacheLife('minutes')
- const cart = await readCart()
After the fix one copy showed Total: $18.00 with Spend $32.00 more for free shipping. and three copies showed Total: $54.00 with Free shipping on this order.
SHELF-105: the feature, staff picks
We want to mark a few books as a "Staff pick". I'd like a checkbox on
/adminfor each book. When I save, the home page should show a "Staff pick" label on those books within a second, for me and for everyone else.
The engineering constraint: the home page must stay ◐ with the grid in the static shell. Making it dynamic is not allowed.
Hint Where to start
"Within a second, for everyone" and "stays prerendered" sound like they're in tension. They aren't, if the flag lives in data that's already cached and you pick the invalidation API that doesn't serve stale content even once.
Solution One way to build it
Store staffPick on the book so it's part of getBooks()'s cached output, render the label in the grid, and save it through a Server Action that calls updateTag('books'):
// app/actions.ts
export async function saveStaffPicks(formData: FormData) {
const slugs = formData.getAll('staffPick').map(String)
await dbSetStaffPicks(slugs)
// A Server Action, so updateTag is allowed: the books expire now and the
// very next request, from anyone, renders the home page with fresh data.
updateTag('books')
}
The admin page gets a form with one checkbox per book (name="staffPick" value={book.slug}) and action={saveStaffPicks}. In my run, the first GET / after saving showed the label (the log printed [db] set staff picks notes-from-the-edge and then [db] list books, so that request rendered fresh), and the build table still showed ◐ /.
Why not revalidateTag('books', 'max')? It would show the old grid to the next visitor, which breaks "within a second" if traffic is low. Why not a Route Handler? It could only use revalidateTag('books', { expire: 0 }), which works but throws away the nice property that the person saving gets fresh data in the same response.
The cheat sheet I wish I'd had
Most of what went wrong above fits in a handful of rows. I keep a version of this pinned next to the editor.
| Symptom | Likely cause | Fix |
|---|---|---|
| Build fails with "uncached data during prerendering" | A slow read outside both 'use cache' and <Suspense> |
Cache it if it can be shared, otherwise wrap it in <Suspense> |
| Build fails with "runtime data during prerendering" | cookies(), headers(), params or searchParams outside <Suspense> |
Move the read into a child component inside <Suspense> |
Build fails on /_not-found |
The root layout reads request data | Same as above, in the layout |
| Dev says "URL data during prerendering or a navigation" | await params at the top of a page or layout |
Pass the promise down and await it inside <Suspense> |
cookies() can't be read inside "use cache" |
A helper deep in a cached scope touches request APIs | Read outside, pass plain values in as arguments |
| A user's own change doesn't appear | Tag mismatch, or revalidateTag where updateTag belongs |
Share tag helpers; use updateTag in Server Actions |
| Webhook returns 500 | updateTag in a Route Handler |
revalidateTag(tag, 'max') or { expire: 0 } |
| Live numbers are hours old | Live data read inside a long-lived cache | Keep it out of the cache and stream it |
Where this leaves you
If you did both halves, you now know the part of Next.js 16 that most production bugs come from, and you've practiced the thing interviews are moving toward: reading unfamiliar code, forming a guess from a symptom, and proving the fix with evidence instead of vibes.
Two honest notes before you go. First, I left 'use cache: remote' out of this tutorial on purpose. By default, 'use cache' entries live in memory per server instance, and the docs are clear that on serverless platforms runtime entries often won't survive between requests. Build-time entries still work fine. If you deploy somewhere ephemeral and need runtime caching to stick, that directive and a cache handler are the next thing to read. Second, everything here was checked against Next.js 16.4.6. This API has moved quickly, and I'd re-check node_modules/next/dist/docs before trusting any blog post on it, including this one.
If you want to keep going, the Server Actions guide goes deeper on the mutation side, the Next.js 16 upgrade guide covers moving an existing app over, and the proxy.ts walkthrough covers the other big change in this release.