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.

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:
// 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:
// 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>;
}// 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:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = { cacheComponents: true };
export default nextConfig;// 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:
| Intent | Next 14 | Next 15 | Next 16 with cacheComponents |
|---|---|---|---|
| Read a cookie | cookies().get() (sync) | (await cookies()).get() | Same, inside <Suspense> |
| Read a header | headers().get() (sync) | await headers() | Same, inside <Suspense> |
searchParams | plain object | Promise prop | Promise prop into <Suspense> |
| Force dynamic | dynamic = 'force-dynamic' | Same | await connection(), or a <Suspense> hole |
| Cache a function | unstable_cache() | unstable_cache() | 'use cache' + cacheLife() |
| Revalidate a route | revalidate = 60 | revalidate = 60 | cacheLife('minutes') |
Control fetch caching | fetchCache | fetchCache | 'use cache' around the fetch |
| Tag and purge | next: { tags } | Same | cacheTag() + revalidateTag() |
The errors and what each one is really asking for:
| Error | Trigger | Fix |
|---|---|---|
Dynamic server usage: … used cookies | Cookie read during static generation | Wrap the reader in <Suspense> |
Route segment config "dynamic" is not compatible | export const dynamic plus cacheComponents | Delete the export, use connection() |
next-request-in-use-cache | cookies() inside a 'use cache' scope | Read outside, pass as an argument |
Filling a cache during prerender timed out (50s) | Runtime promise reaches a cached component | Await the value before entering the cache |
DynamicServerError from setTimeout | Dynamic API outside the request's async context | Await in the original call stack |
| Unexpected full-page dynamic render | searchParams awaited at page top | Await in a child component |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Metadata that reads a cookie
generateMetadata runs during static generation, so reading cookies() there makes the whole route dynamic even when the body is static:
export async function generateMetadata() {
return { title: 'Dashboard' }; // no cookie read here
}
// the cookie-dependent UI streams in its own boundary insteadIf 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:
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:
// 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:
// 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:
// 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:
// 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-dynamicto silence the warning. It defeats the static shell and is a build error undercacheComponents. Use<Suspense>first;connection()only when the whole route is request-bound. - Forgetting to await
params. In Next 15+paramsis a promise; destructuring it synchronously yieldsundefinedfields — no error, just empty pages. - Assuming
fetchis cached. Since 15,fetchis uncached by default, so a route that relied on implicit caching becomes slower and dynamic-looking until'use cache'is added. unstable_cacheafter 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
webpackfunction innext.config.tsis ignored and a plugin that fixed asset paths stops applying. - Reading
headers()in a client component.next/headersis 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 toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Server Actions: Swallowed Redirects and Body Limits
redirect() throws, so a try/catch swallows the navigation; the action body parser has a 1 MB limit; and useActionState cannot hold an Error. Fixes for all three.
Supabase SSR on Next.js: Stale Sessions and Lock Timeouts
The session flips between signed-in and signed-out because the refreshed token is written to a cookie store that no longer exists. Adapter, proxy and lock fixes.
Next.js Standalone in Docker: Missing CSS and sharp Module Errors
output standalone copies server.js only, so /_next/static and public are missing and every page renders unstyled. The image and copy fixes, plus the sharp native binding error.
Next.js 16 Upgrade: Async Params, proxy.ts, and Turbopack Build Breaks
The codemod gets you most of the way; the rest is async request APIs, a webpack config Turbopack refuses, and a renamed middleware file that silently stops running.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.