NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Next.js 16.4: fail the build when a page turns dynamic

Next.js 16.4 adds ensureStatic, which makes next build fail when a route would render on every request. Add it to a blog, see each real error, and keep per-visitor bits in the browser.

Updated Nov 18, 20269 min readIntermediatenext 16.4.6 · react 19.3.0 · node 22.22.3

Next.js 16.4 adds ensureStatic, a one-line export that makes next build fail when a route would render on the server for every request. This guide adds it to a small blog, then breaks the blog on purpose so you can see each error and how to fix it.

Why you'd want it: with Cache Components, a route is no longer simply static or dynamic. One page can mix prerendered HTML with parts that render per request. That's flexible, but it also means one cookies() call in a shared layout can quietly turn every blog post into server work. The build still passes, and nothing tells you. ensureStatic turns that silent change into a build error.

You need Node.js 20.9 or later and Next.js 16.4. Everything below ran on Node 22.22.3 with Next.js 16.4.6 and React 19.3.0.

1. Create the app

terminal
npx [email protected] static-guard --yes --no-tailwind
cd static-guard

Since 16.4, create-next-app turns on Cache Components and Partial Prefetching for new apps. --no-tailwind only keeps the example small. The generated config:

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  cacheComponents: true,
  partialPrefetching: true,
};

export default nextConfig;

In an existing app, add those two flags yourself. ensureStatic only works when cacheComponents is on, and the build fails otherwise.

2. Add a blog that is quietly dynamic

Two posts in a JSON file stand in for a database:

content/posts.json
[
  { "slug": "hello-world", "title": "Hello, world", "body": "The first post on this blog." },
  { "slug": "static-by-default", "title": "Static by default", "body": "Why this blog never renders on request." }
]
lib/posts.ts
import { readFile } from 'node:fs/promises'

type Post = { slug: string; title: string; body: string }

async function loadPosts(): Promise<Post[]> {
  const file = await readFile(`${process.cwd()}/content/posts.json`, 'utf8')
  return JSON.parse(file)
}

export async function getPost(slug: string) {
  const posts = await loadPosts()
  return posts.find((post) => post.slug === slug)
}

export async function getSlugs() {
  const posts = await loadPosts()
  return posts.map((post) => post.slug)
}

The post page wraps the part that reads data in <Suspense>, so the rest of the page can still be prerendered:

app/blog/[slug]/page.tsx
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getPost } from '@/lib/posts'

export default function PostPage({ params }: PageProps<'/blog/[slug]'>) {
  return (
    <Suspense fallback={<p>Loading post…</p>}>
      <Post params={params} />
    </Suspense>
  )
}

async function Post({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </article>
  )
}
terminal
npm run build
text
Route (app)
┌ ○ /
├ ○ /_not-found
└   /blog/[slug]
  └ ◐ /blog/[slug]


○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content

The build passes, but ◐ means only the Loading post… fallback is static. The post itself is read and rendered on the server on every request. For content that changes once a month, that's wasted compute.

3. Require static output

Export ensureStatic from the blog layout. A layout covers every route under it, including routes added later:

app/blog/layout.tsx
export const ensureStatic = 'navigation'

export default function BlogLayout({ children }: LayoutProps<'/blog'>) {
  return <main>{children}</main>
}

'navigation' means the complete server-rendered route has to come from prerendered output. Build again:

text
Error: Page "/blog/[slug]": `ensureStatic = "navigation"` requires an exported `generateStaticParams()` function.
Learn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic

A dynamic route has to tell Next.js which params to prerender. Add generateStaticParams() to the page:

app/blog/[slug]/page.tsx
import { getPost, getSlugs } from '@/lib/posts'

export async function generateStaticParams() {
  const slugs = await getSlugs()
  return slugs.map((slug) => ({ slug }))
}

The next build gets further, then stops on the real problem:

text
Error: Route "/blog/[slug]": Next.js encountered uncached or runtime data on a route that must be fully static.

This route is configured to be fully static, but some data requires rendering at request time.

Ways to fix this:
  - [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
  - [remove] Remove the data access
  - [client] Read the data on the client

Learn more: https://nextjs.org/docs/messages/static-route-dynamic

The file read in getPost() isn't cached, so Next.js can only run it per request. Every visitor sees the same post, so cache it with 'use cache':

lib/posts.ts
export async function getPost(slug: string) {
  'use cache'
  const posts = await loadPosts()
  return posts.find((post) => post.slug === slug)
}

getSlugs() doesn't need the directive, because generateStaticParams() only runs at build time.

text
Route (app)
┌ ○ /
├ ○ /_not-found
└   /blog/[slug]
  ├ ◐ /blog/[slug]
  ├ ○ /blog/hello-world
  └ ○ /blog/static-by-default

Both posts are now ○, fully static. The remaining ◐ /blog/[slug] line is the route itself, used for slugs that weren't listed at build time. With 'navigation', the first request for such a slug waits while Next.js generates and stores the full static page.

4. Watch it catch a regression

Months later, someone adds a greeting to the blog layout that reads a cookie:

app/blog/greeting.tsx
import { cookies } from 'next/headers'

export async function Greeting() {
  const name = (await cookies()).get('name')?.value
  return <p>{name ? `Welcome back, ${name}` : 'Welcome'}</p>
}
app/blog/layout.tsx
import { Suspense } from 'react'
import { Greeting } from './greeting'

export const ensureStatic = 'navigation'

export default function BlogLayout({ children }: LayoutProps<'/blog'>) {
  return (
    <main>
      <Suspense fallback={<p>Welcome</p>}>
        <Greeting />
      </Suspense>
      {children}
    </main>
  )
}

Without ensureStatic, this would build fine and turn every post back into ◐. With it, the build fails with the same "uncached or runtime data" error as before. Wrapping the greeting in <Suspense> doesn't help: under 'navigation' there's no later stage for it to stream into.

The default output only shows a component stack (at Suspense, at main). To get the exact line, rerun the build with --debug-prerender:

terminal
npx next build --debug-prerender
text
Learn more: https://nextjs.org/docs/messages/static-route-dynamic
    at Greeting (app/blog/greeting.tsx:4:30)
    at BlogLayout (app/blog/layout.tsx:10:9)
  2 |
  3 | export async function Greeting() {
> 4 |   const name = (await cookies()).get('name')?.value
    |                              ^
  5 |   return <p>{name ? `Welcome back, ${name}` : 'Welcome'}</p>
  6 | }
  7 |

The docs say next dev runs the same check and shows the source location in its error overlay.

5. Fix it without losing static pages

A cookie can't be cached, because it differs per visitor. To keep the greeting, read the cookie in the browser instead. React 19.3 adds browser() for exactly this:

app/blog/greeting.tsx
'use client'

import { use } from 'react'
import { browser } from 'react-dom'

export function Greeting() {
  use(browser('The name cookie is read in the browser.'))

  const name = document.cookie.match(/(?:^|; )name=([^;]*)/)?.[1]
  return <p>{name ? `Welcome back, ${decodeURIComponent(name)}` : 'Welcome'}</p>
}

During prerendering, use(browser()) stops at the nearest <Suspense>, so the static HTML gets the Welcome fallback. The browser then renders the real greeting. The layout doesn't change. npm run build passes again, and both posts stay ○.

Check the production server:

terminal
npx next start -p 3457

In a second terminal:

terminal
curl -s -D - -o /dev/null http://localhost:3457/blog/hello-world
text
HTTP/1.1 200 OK
x-nextjs-cache: HIT
x-nextjs-prerender: 1
x-nextjs-prerender: 1
x-nextjs-stale-time: 300
Cache-Control: s-maxage=900, stale-while-revalidate=31535100

x-nextjs-cache: HIT and x-nextjs-prerender: 1 show the response came from the prerendered page. s-maxage=900 is the 15-minute revalidate time of the default cacheLife profile. Set a name=Ada cookie for localhost:3457 and reload, and the greeting changes to "Welcome back, Ada".

The trade-off: content behind browser() isn't in the HTML, so crawlers that don't run JavaScript only see the fallback. That's fine for a greeting, but not for anything you want indexed.

Child segments can only be stricter

A page under the layout can't loosen the rule. Adding export const ensureStatic = 'shell' to the post page fails the build:

text
Error: Failed to collect configuration for /blog/[slug]
    at ignore-listed frames {
  [cause]: Error: A child segment cannot override a parent segment with a less-constrained `ensureStatic`.
    Parent has: 
      export const ensureStatic = "navigation"
      (from: [project]/app/blog/layout.tsx)
    Child has: 
      export const ensureStatic = "shell"
      (from: [project]/app/blog/[slug]/page.tsx)

A child segment can set a stricter level, never a weaker one. To mark a segment as deliberately dynamic, the reference says to export false, which fails if any parent sets a static level.

Pick the right level

ValueOutput that must be staticChecked at build time
'shell'The App Shell a default <Link> loadsNo
'prefetch'The shell plus per-link prefetches from <Link prefetch>No
'navigation'The complete routeYes, in next dev and next build

'shell' and 'prefetch' only matter with Partial Prefetching. They change what the client requests before a click, so a store can skip rendering a personal cart count for links nobody follows. They don't add build validation: with 'shell' on the layout, the server-side cookie greeting from step 4 built without errors and all three blog routes went back to ◐. If you need a guarantee that fails CI, use 'navigation'.

When not to use it

  • Pages that are personal by design, such as dashboards, carts and account pages. Use <Suspense> and let them stream.
  • Content that must be fresher than five minutes. Short cache lifetimes fail the 'navigation' check.
  • Huge catalogs where first-visit latency matters. You only have to list one set of params, but under 'navigation' the first visitor to an unlisted page waits for the full render instead of getting a streamed shell.

For blogs, docs, marketing pages and other public content, putting ensureStatic = 'navigation' on the layout is a cheap guard. It stops any future change from adding per-request rendering.

Next steps

Related tutorials