Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js 16 DynamicServerError: cookies(), headers() and fetchCache

Request-time APIs make a route dynamic, and Next 16 replaced the segment configs with Suspense boundaries and use cache. What to delete and what to wrap.

~4 min readNext.js
#Next.js#React#Caching#SSR
3D illustration of a static page slab with a glowing hole streamed by an amber beam

Introduction & Quick Summary

Symptom. next build fails with Error: Dynamic server usage: Route /dashboard couldn't be rendered statically because it used \cookies`, or a page that used to be static renders on every request. After upgrading to 16 and enabling Cache Components it fails differently: Route segment config "dynamic" is not compatible with `cacheComponents`, or next-request-in-use-cache` when a cached function reads a cookie.

Cause. Next.js 15 made cookies(), headers(), draftMode() and the params/searchParams props asynchronous, and any read of them marks its scope request-bound. Next.js 16 with cacheComponents: true replaces the segment switches (dynamic, revalidate, fetchCache) with use cache, cacheLife and cacheTag, so runtime data belongs inside a <Suspense> boundary while the rest of the route prerenders.

Fix. Decide per route whether it is static, request-bound, or a static shell with a streaming hole. For the third and most common case, move the cookies()/headers() read into its own component and wrap it in <Suspense>; in a cached scope, read the cookie outside and pass the value in. Then delete the leftover segment configs, which are build errors once cacheComponents is on.

Core Mechanics, Signatures & Reproducible Setup

Request-time APIs and their current shapes:

tsx
// next/headers: both are async, both opt the calling scope into request time import { cookies, headers } from 'next/headers'; const theme = (await cookies()).get('theme')?.value ?? 'light'; const ua = (await headers()).get('user-agent') ?? ''; // page props: promises since 15 export default async function Page({ params, searchParams }: PageProps<'/blog/[slug]'>) { const { slug } = await params; const { q } = await searchParams; }

A minimal route that triggers the build error, and the fix:

tsx
// app/dashboard/page.tsx — whole route becomes dynamic import { cookies } from 'next/headers'; export default async function Dashboard() { const token = (await cookies()).get('token')?.value; // build: Dynamic server usage return <p>{token ? 'signed in' : 'signed out'}</p>; }
tsx
// app/dashboard/page.tsx — static shell, dynamic hole import { Suspense } from 'react'; import { cookies } from 'next/headers'; export default function Dashboard() { return ( <main> <h1>Dashboard</h1> <Suspense fallback={<p>Checking session…</p>}> <SessionBadge /> </Suspense> </main> ); } async function SessionBadge() { const token = (await cookies()).get('token')?.value; return <p>{token ? 'signed in' : 'signed out'}</p>; }

Enabling the caching model, and the config to remove with it:

ts
// next.config.ts import type { NextConfig } from 'next'; const nextConfig: NextConfig = { cacheComponents: true }; export default nextConfig;
tsx
// Remove these exports when cacheComponents is on — they are errors now // export const dynamic = 'force-dynamic'; // export const revalidate = 60; // export const fetchCache = 'force-no-store';

Key Comparison Table

How the same intent is expressed across versions:

IntentNext 14Next 15Next 16 with cacheComponents
Read a cookiecookies().get() (sync)(await cookies()).get()Same, inside <Suspense>
Read a headerheaders().get() (sync)await headers()Same, inside <Suspense>
searchParamsplain objectPromise propPromise prop into <Suspense>
Force dynamicdynamic = 'force-dynamic'Sameawait connection(), or a <Suspense> hole
Cache a functionunstable_cache()unstable_cache()'use cache' + cacheLife()
Revalidate a routerevalidate = 60revalidate = 60cacheLife('minutes')
Control fetch cachingfetchCachefetchCache'use cache' around the fetch
Tag and purgenext: { tags }SamecacheTag() + revalidateTag()

The errors and what each one is really asking for:

ErrorTriggerFix
Dynamic server usage: … used cookiesCookie read during static generationWrap the reader in <Suspense>
Route segment config "dynamic" is not compatibleexport const dynamic plus cacheComponentsDelete the export, use connection()
next-request-in-use-cachecookies() inside a 'use cache' scopeRead outside, pass as an argument
Filling a cache during prerender timed out (50s)Runtime promise reaches a cached componentAwait the value before entering the cache
DynamicServerError from setTimeoutDynamic API outside the request's async contextAwait in the original call stack
Unexpected full-page dynamic rendersearchParams awaited at page topAwait in a child component

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

generateMetadata runs during static generation, so reading cookies() there makes the whole route dynamic even when the body is static:

tsx
export async function generateMetadata() { return { title: 'Dashboard' }; // no cookie read here } // the cookie-dependent UI streams in its own boundary instead

If the title genuinely depends on the session, wrap the dependent part in <Suspense> instead; crawlers and prefetchers see the static title.

2. searchParams awaited too high in the tree

Awaiting searchParams at the page level makes the whole route request-bound, so a list page that only needs ?page= loses its static shell:

tsx
export default function Page({ searchParams }: PageProps<'/search'>) { return ( <Suspense fallback={<ResultsSkeleton />}> <Results searchParams={searchParams} /> </Suspense> ); } async function Results({ searchParams }: Pick<PageProps<'/search'>, 'searchParams'>) { const { q } = await searchParams; const rows = await search(q); return <List rows={rows} />; }

3. DynamicServerError from a lost async context

Next's dynamic-API detection relies on async context. Reading a cookie inside setTimeout, in an un-awaited promise chain, or after a fire-and-forget call loses that context, and the error surfaces at build time:

tsx
// Broken: cookies() runs outside the request's call stack function getSession() { return new Promise((resolve) => setTimeout(async () => resolve(await cookies()), 1000)); } // Fixed: read first, pass the value into the timer async function getSession() { const store = await cookies(); const token = store.get('token')?.value; return new Promise((resolve) => setTimeout(() => resolve(token), 1000)); }

4. Cookies inside 'use cache'

A cached function must produce the same output for the same arguments, so request-time APIs are rejected — at build, or on the first dynamic run. Read outside and pass values in:

tsx
// Broken: cached scope reads a request-scoped API async function Cart() { 'use cache'; const userId = (await cookies()).get('uid')?.value; // next-request-in-use-cache return <CartItems userId={userId} />; } // Fixed: cookie read outside, cached work keyed by the value export async function CartWrapper() { const userId = (await cookies()).get('uid')?.value ?? 'guest'; return <CachedCart userId={userId} />; } async function CachedCart({ userId }: { userId: string }) { 'use cache'; cacheLife('minutes'); cacheTag(`cart:${userId}`); return (await getCart(userId)).map((i) => <li key={i.id}>{i.name}</li>); }

5. The build that hangs for 50 seconds

Passing a runtime promise into a 'use cache' component makes the cached render wait for data that cannot exist at build time; after 50 seconds the build reports Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or uncached data were used inside "use cache". Await in the parent and pass a primitive:

tsx
// Broken: promise created outside the cache boundary, awaited inside <CachedCart promise={cookies()} /> // Fixed const token = (await cookies()).get('token')?.value; <CachedCart token={token ?? ''} />

6. Route handlers and server actions still set cookies

cookies().set() is allowed only in a Server Action or a Route Handler, never during rendering, where response headers are already committed. A badge that refreshes a token while rendering throws at runtime even though the build passed:

tsx
// app/actions.ts 'use server'; import { cookies } from 'next/headers'; export async function signIn(formData: FormData) { const store = await cookies(); store.set('token', await exchange(formData), { httpOnly: true, sameSite: 'lax', secure: true, path: '/', }); }

Common Compilation/Runtime Mistakes & Version Gotchas

  • Adding force-dynamic to silence the warning. It defeats the static shell and is a build error under cacheComponents. Use <Suspense> first; connection() only when the whole route is request-bound.
  • Forgetting to await params. In Next 15+ params is a promise; destructuring it synchronously yields undefined fields — no error, just empty pages.
  • Assuming fetch is cached. Since 15, fetch is uncached by default, so a route that relied on implicit caching becomes slower and dynamic-looking until 'use cache' is added.
  • unstable_cache after enabling Cache Components. It is superseded by 'use cache'; mixing the two in one route produces cache misses that look like invalidation bugs.
  • Turbopack as the default bundler. Next 16 builds with Turbopack, so a custom webpack function in next.config.ts is ignored and a plugin that fixed asset paths stops applying.
  • Reading headers() in a client component. next/headers is server-only; a shared file pulls it into a client boundary and the import fails with a misleading module-not-found error.

Related tools. When a build fails after a config change, paste the old and new next.config.ts into the text diff tool to see exactly which segment export disappeared; when the props Next serialises into the RSC payload do not match what the component expects, the JSON formatter makes the payload's shape obvious, and the timestamp tool helps when a stale revalidate/cacheLife window is suspected of serving yesterday's render.

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.