Error: Dynamic server usage: Route /x couldn't be rendered statically because it used `headers`.
Next.js · updated 2026-11-05
Printed in next build output, or in server logs, with digest DYNAMIC_SERVER_USAGE while Next.js prerenders App Router routes. Next throws it on purpose to bail out of static rendering; you usually see it because your own code caught and logged it.
Generating static pages (12/24)
Error: Dynamic server usage: Route /account couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error
at q (/app/.next/server/chunks/638.js:1:42915)
at s (/app/.next/server/app/account/page.js:1:3102)
at async getSession (/app/.next/server/app/account/page.js:1:3540) {
description: "Route /account couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error",
digest: 'DYNAMIC_SERVER_USAGE'
}Quick fix
Tell Next.js the route is dynamic: export const dynamic = 'force-dynamic' from the page or layout, or await connection() before the request-specific code. If a try/catch wraps headers(), cookies() or a no-store fetch, call unstable_rethrow(err) first in the catch so Next's own bailout error passes through.
- Note the route and the API named in the message (headers, cookies, searchParams, no-store fetch).
- Search that route's server code, including shared helpers, for try/catch around those calls.
- Call unstable_rethrow(err) as the first line of each such catch.
- If the page should be dynamic, export const dynamic = 'force-dynamic' or await connection().
- If it should stay static, move the request-specific read into a client component or middleware.
- With Cache Components enabled, wrap the dynamic part in <Suspense> instead of using segment config.
- Rebuild and confirm the route shows as dynamic (ƒ) in the build summary.
import { headers } from 'next/headers';
import { unstable_rethrow } from 'next/navigation';
// Opt this route out of static prerendering
export const dynamic = 'force-dynamic';
export default async function AccountPage() {
try {
const h = await headers();
return <p>Country: {h.get('x-country') ?? 'unknown'}</p>;
} catch (err) {
unstable_rethrow(err); // lets Next.js internal errors through
return <p>Could not read the request.</p>;
}
}Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/dynamic-server-usage.md and fix this error in this project.Why it happens
A try/catch swallows the bailout signal
Next.js marks a route as dynamic by throwing a special error from headers(), cookies() and similar APIs during prerendering. A try/catch around that call, or around a helper that makes it, catches the signal; logging it prints this message.
Shared code reads request data
A layout or utility used everywhere (session lookup, locale detection, feature flags) calls cookies() or headers(), so pages you meant to prerender can no longer be static. Auth helpers in libraries often read cookies internally.
Uncached fetch in a static route
fetch with cache: 'no-store' or next: { revalidate: 0 } opts the route into dynamic rendering. The message then names the fetch instead of headers, but the fix is the same decision: dynamic route or cached data.
Segment config that contradicts the code
With dynamic = 'error', the build fails as soon as a dynamic API is used. With 'force-static', headers() and cookies() return empty values, which can hide the problem until production behaves strangely.
Dynamic call in a branch that skipped the build
A cookies() call that only runs for some users or flags never executed during prerendering, so the page was built as static. When that branch runs later during revalidation, Next reports the page changed from static to dynamic at runtime.
Other fixes
- Read request data in middleware (proxy.ts in Next 16) and rewrite to a path segment, so each variant can still be prerendered.
- Move per-user UI into a client component that fetches after load, keeping the surrounding page static.
- Call auth or session helpers only from dynamic routes, route handlers or server actions.
Same error, other wording
- Error: Dynamic server usage: Route /x couldn't be rendered statically because it used `cookies`.
- Error: Page changed from static to dynamic at runtime /x, reason: headers
- Error: Dynamic server usage: cookies
Let your coding agent catch the next one
Next.js throws this during the build and catches it itself, so unless your own code catches and reports it Runheed doesn't record it. What it does record is the exceptions your running server code throws (route handlers, server rendering, API errors and background jobs) with the stack trace and the breadcrumbs before them, and serves those errors to Claude Code, Cursor or any MCP client.
Setup for Next.js or Vercel Functions, then have your agent fix and resolve it.
Related errors
- An error occurred in the Server Components render. The specific message is omitted in...
- Hydration failed because the server rendered HTML didn't match the client. As a result...
- Module not found: Can't resolve 'fs'
More in React and Next.js rendering
- ResizeObserver loop completed with undelivered notifications.Browser
- ReferenceError: window is not definedNext.js
- Error: Event handlers cannot be passed to Client Component props.Next.js
- Only plain objects, and a few built-ins, can be passed to Client Components from Server...Next.js
- Route "/orders/[id]" used `params.id`. `params` should be awaited before using its...Next.js
- Error: NEXT_REDIRECTNext.js
- Error: NextRouter was not mounted.Next.js
- Invalid src prop (https://cdn.example.com/p/42.jpg) on `next/image`, hostname...Next.js
- TypeError: Failed to parse URL from /api/ordersNext.js
- Too many re-renders. React limits the number of renders to prevent an infinite loop.Next.js
- useSearchParams() should be wrapped in a suspense boundary at page "/search".Next.js
- You're importing a module that depends on `useState` into a React Server Component...Next.js
- Objects are not valid as a React child (found: object with keys {id, name, total}). If...Next.js
- Element type is invalid: expected a string (for built-in components) or a class/function...Next.js
- Failed to find Server Action "7f3a9c2e5d1b4a6f8c0e2d7b9a1c3e5f7d9b0a2c4e". This request...Next.js
- ChunkLoadError: Loading chunk 4512 failed. (error...Next.js
Other error topics
- Error: getaddrinfo ENOTFOUND api.example.comNetwork and HTTP
- ConnectionResetError: [Errno 104] Connection reset by peerNetwork and HTTP
- Error: 429 You exceeded your current quota, please check your plan and billing details.Network and HTTP
- error: relation "todo" does not existDatabases
- sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due...Databases
- [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379Databases
- Error: Cannot find module 'x'Imports and modules
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Imports and modules
- ImportError: libGL.so.1: cannot open shared object file: No such file or directoryImports and modules
- TypeError: unhashable type: 'list'Undefined, None and type errors
- panic: assignment to entry in nil mapUndefined, None and type errors
- TypeError: items is not iterableUndefined, None and type errors
- TypeError: Object of type datetime is not JSON serializableJSON, parsing and validation
- SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSONJSON, parsing and validation
- ZodError: [ { "expected": "string", "code": "invalid_type", "path": [ "email" ]...JSON, parsing and validation
- CredentialsProviderError: Could not load credentials from any providersMemory, async and the process
- RecursionError: maximum recursion depth exceededMemory, async and the process
- MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error...Memory, async and the process
- Bad Request: No valid session ID providedMCP servers and clients
- Error executing tool get_orderMCP servers and clients
- McpError: MCP error -32001: Request timed outMCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Next.js: Dynamic Server Error, Next.js: dynamic segment config, Next.js: headers()
Spotted a mistake? Email hello@greatwork.company. About Runheed.