Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js cacheComponents: 'used uncached or runtime data' build error

Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.

~5 min readNext.js
#Next.js#React#Caching#Troubleshooting
A static shell panel with a cyan cut-out hole streaming data, headline CACHE COMPONENTS

Introduction & Quick Summary

Symptom. With Cache Components enabled, next build stops on a route that worked in development:

code
Error: Route "/products/[id]": 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. 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"` - [block] Set `export const instant = false` to allow a blocking route

Cause. cacheComponents: true changes what a build means. Next.js now prerenders a static shell for every route and refuses to guess which parts are request-time. Any read of cookies(), headers(), params, searchParams, connection(), or an uncached database call outside a <Suspense> boundary leaves nothing to prerender, so the build fails instead of shipping a slow page.

Fix. Pick one of the three answers per data access: stream it, cache it, or admit the route is blocking.

tsx
// app/products/[id]/page.tsx import { Suspense } from "react"; import { ProductDetail } from "./product-detail"; export default async function Page({ params }: PageProps<"/products/[id]">) { const { id } = await params; // request-time read, must be inside Suspense or blocking return ( <Suspense fallback={<p>Loading product…</p>}> <ProductDetail id={id} /> </Suspense> ); }
ts
// the expensive, stable part is a cache function instead of a request-time read import { cacheLife, cacheTag } from "next/cache"; export async function getProduct(id: string) { "use cache"; cacheLife("hours"); cacheTag(`product:${id}`); return db.product.findUnique({ where: { id } }); }

Core Mechanics, Signatures & Reproducible Setup

Cache Components is the completion of the partial prerendering idea: a route is split into a static shell and dynamic holes. The shell is what a CDN can serve without touching your database; the holes stream in per request. For that split to be valid, the compiler has to know where the boundary is, and the only syntax that expresses it is <Suspense> plus explicit caching.

Reproduce it in a fresh app instead of guessing:

bash
npx create-next-app@latest cc-lab --ts --app cd cc-lab # next.config.ts
ts
import type { NextConfig } from "next"; const nextConfig: NextConfig = { cacheComponents: true }; export default nextConfig;
tsx
// app/page.tsx — fails the build export default async function Page() { const theme = (await cookies()).get("theme")?.value ?? "light"; return <main data-theme={theme}>hello</main>; }

Adding a Suspense boundary around the part that reads the cookie is enough to make the shell prerenderable again:

tsx
import { Suspense } from "react"; import { cookies } from "next/headers"; async function Themed() { const theme = (await cookies()).get("theme")?.value ?? "light"; return <div data-theme={theme}>hello</div>; } export default function Page() { return ( <Suspense fallback={<div>hello</div>}> <Themed /> </Suspense> ); }

Two supporting rules come with it. revalidateTag now takes a cache profile as a second argument, and the single-argument form is a type error:

ts
import { revalidateTag } from "next/cache"; // after a mutation revalidateTag(`product:${id}`, "max");

And a route that genuinely cannot stream declares itself blocking rather than fighting the model:

tsx
export const instant = false;

Key Comparison Table

Which of the three answers fits which access:

Data accessStreams with SuspenseWorks under "use cache"Blocking route
cookies() / headers()yesnoyes
params / searchParamsyesnoyes
fetch with cache: "force-cache"yesyesyes
Database read via ORMyesyesyes
connection()yesnoyes
Current user session lookupyesnoyes
Cache profileRevalidate windowTypical use
secondsabout 1 secondnear-real-time dashboards
minutesabout 1 minutefeeds, comment counts
hoursabout 1 hourcatalog pages
daysabout 1 daymarketing and docs
weeksabout 1 weekrarely changing reference data
maxeffectively indefinite until taggedstatic configuration

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The error names the route, not the line

The message reports the route because the offending read can be several components deep. Search the segment for request-time APIs before you restructure anything:

bash
grep -rn "cookies()\|headers()\|searchParams\|connection()" app/products

A read inside a helper called by a Server Component is still outside <Suspense> unless a boundary sits between the two. Wrapping the page's outermost element in <Suspense> fixes the build and also removes the stream, so wrap the smallest part that needs the request-time value.

2. "use cache" cannot wrap request-time values

A cache function is shared across users, so it cannot read a cookie. The common wrong fix is to cache the whole page and lose personalization:

ts
async function getCart() { "use cache"; // user-specific data must not be cached this way const userId = (await cookies()).get("uid")?.value; return db.cart.findMany({ where: { userId } }); }

Split it: read the cookie outside, cache the expensive query by its argument.

ts
async function getCart(userId: string) { "use cache"; cacheTag(`cart:${userId}`); return db.cart.findMany({ where: { userId } }); }

The cacheTag is what makes invalidation possible, and the tag should include the id so two users do not evict each other.

3. instant = false is a decision, not a workaround

A blocking route is prerendered per request, which means no static shell and no CDN hit. That is correct for an authenticated checkout or a payment callback, and wrong for anything else. Reach for it when the route's first byte always depends on the session, and leave a comment saying so, because the next engineer will otherwise "optimize" it back into a build failure.

tsx
// app/account/page.tsx export const instant = false; // session-dependent, never cached

4. Route handlers and metadata images

Route handlers that read request are dynamic by nature; under Cache Components they need to opt in rather than being silently dynamic:

ts
// app/api/report/route.ts export const instant = false; export async function GET(request: Request) { const url = new URL(request.url); return Response.json({ q: url.searchParams.get("q") }); }

The same applies to opengraph-image.tsx and icon.tsx, whose params are now promises. Awaiting them inside the image function is fine; reading them in a helper that runs before the boundary is not.

5. Client components and the CSR bailout

useSearchParams() in a Client Component still fails a prerender with the older bailout message unless it sits under <Suspense>. Under Cache Components the two failures are easy to confuse, so read the first line: missing-suspense-with-csr-bailout is the client-side one, and it is fixed in the component tree, not with instant = false:

tsx
// app/search/page.tsx import { Suspense } from "react"; import { Filters } from "./filters"; export default function Page() { return ( <Suspense fallback={null}> <Filters /> </Suspense> ); }

6. Invalidation after a Server Action

A mutation should invalidate with the same tag the read used, and the profile argument decides how long the regenerated entry lives:

ts
"use server"; import { revalidateTag } from "next/cache"; export async function updatePrice(id: string, price: number) { await db.product.update({ where: { id }, data: { price } }); revalidateTag(`product:${id}`, "max"); }

Calling revalidateTag with one argument compiles under JavaScript and fails type checking under TypeScript, which is how many teams discover the change only after a deploy. Test the JSON payload your action returns with the JSON formatter before blaming the cache.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Enabling cacheComponents on an app full of cookies() reads. Expect one build error per route; budget a day, not an hour.
  • Wrapping the whole page in <Suspense>. The build passes and every page becomes a blank shell with a spinner, which is worse for SEO than the blocking route.
  • Caching personalized data with "use cache". It compiles and serves one user's data to everyone. Tag per user or do not cache.
  • Forgetting the second argument to revalidateTag. Type error in TypeScript, silent no-op expectations in JavaScript.
  • Assuming export const dynamic still controls anything. Route segment config for caching is replaced by instant and the cache boundaries.
  • Reading params in a layout without awaiting. Layouts are pages for this rule; the promise must be awaited before use.
  • Blaming Node. Cache Components needs Node.js 20.9 or later and Turbopack, which Next.js 16 uses by default; an old CI image fails before your code does.

Check which build a route ended up in with the status code reference when a deploy serves a cached shell where you expected a 200 per user.

Reference: Cache Components and revalidateTag in the Next.js documentation.

Official references

primary documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.