Next.js cacheComponents: uncached data during prerender fix
Introduction & Quick Summary Symptom. With Cache Components enabled, next build stops on a route that worked in development: 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:…
Next.js introduced cacheComponents: true to enable partial prerendering by splitting routes into static shells and dynamic holes. However, this feature can cause issues when data is accessed outside the Suspense boundary, resulting in an uncached or runtime data error during prerendering. The error occurs when `fetch()`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` are accessed outside of `Suspense`, preventing the route from being prerendered.
To fix this issue, developers have three options: streaming, caching, or admitting the route as blocking. Streaming involves using `Suspense` with a fallback component to load data request-time. Caching can be achieved by leveraging the `use cache` hook, marking cacheable data with `use cache`, specifying a cache life, and a cache tag. Lastly, if the route genuinely cannot stream, developers can declare it as blocking by setting `export const instant = false;`.
The fix provided in the source code demonstrates how to use `Suspense` to handle the cookie read by surrounding the data access with a `Suspense` boundary. This allows the shell to be prerenderable again, as shown in the example of the `Themed` component. By following one of these three approaches, developers can ensure their Next.js applications can handle data access correctly and prevent build failures.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.