Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 72 ยท Rendering Strategies

Static Generation and generateStaticParams

Build pages ahead of time in Next.js: generateStaticParams, dynamicParams, nested params, and the static export option with its limits, plus live stand-ins.

A blog with five hundred posts does not need a server to render each post on every visit. The posts do not change between deploys, so Next.js can render all of them once, during next build, and serve the results as files. That is static generation, and it gives you the fastest, cheapest pages you can have.

The catch is that a route like /blog/[slug] is a pattern, not a list of pages. Next.js cannot guess which slugs exist. The function generateStaticParams is how you tell it. This lesson explains that function, what happens to URLs you did not list, how multi-level routes work, and what the static export option does when you want a site that is nothing but files.

Telling Next.js which pages exist

Export generateStaticParams from the page (or layout) of a dynamic segment. It returns an array with one object per page to build, and each object has the segment's name as its key:

TSX
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { getAllPosts, getPost } from '@/lib/posts';

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({ slug: post.slug }));
}

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      <div>{post.body}</div>
    </article>
  );
}

At build time Next.js calls generateStaticParams, then renders the page once for each object it returns. With two posts named hello and second you get two prerendered pages, /blog/hello and /blog/second. In the build report (see Static vs Dynamic Rendering) the route is marked โ—, which means "static HTML produced through generateStaticParams".

From pattern to pages

A pattern /blog/[slug] matches many URLs.
A list generateStaticParams names the real ones.
A build One HTML file per entry.

Add a post, rebuild, get a new page.

1 / 2

Data fetched while building, such as the getPost call, runs at build time for these pages. If a post is edited later, the stored page stays as it was until you rebuild or revalidate it, which Revalidating Data covers.

Nested dynamic segments

A route with several dynamic segments is generated in two ways. You can return every full combination from the deepest segment, or you can generate level by level. In the second style, the child function receives the parent's params, so it only has to say what is inside each parent:

TSX
// app/shop/[category]/layout.tsx
export async function generateStaticParams() {
  return [{ category: 'lamps' }, { category: 'notebooks' }];
}
TSX
// app/shop/[category]/[product]/page.tsx
export async function generateStaticParams({
  params,
}: {
  params: Promise<{ category: string }>;
}) {
  const { category } = await params;
  const products = await getProductsIn(category);
  return products.map((product) => ({ product: product.slug }));
}

Next.js runs the parent first, then the child once per parent, and combines the results. The child never repeats the work of listing categories, and each parent only loads its own products.

What happens to pages you did not list

By default, a URL that matches the pattern but was not generated, for example /blog/brand-new, is rendered on demand the first time someone asks, and then stored for later visitors. This default is controlled by dynamicParams:

TSX
export const dynamicParams = false; // anything not returned by generateStaticParams is a 404
dynamicParams Unlisted URL Good for
true (default) Rendered once on first visit, then stored Large catalogs: build the popular pages, let the rest generate lazily
false 404 Small closed sets, where a typo should never render a page

A neat trick for huge sites is to return only the most visited few hundred pages from generateStaticParams. The build stays fast, popular pages are instant, and everything else is generated the first time it is visited. The first stand-in builds a miniature of this.

Node.js A tiny static builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With dynamicParams on, /blog/third is rendered the first time and served as a stored file the second time. A slug that does not exist at all still gives a 404 because the page calls notFound(), which our stand-in imitates by checking the data. With dynamicParams off, third is a 404 even though the post exists, because it was not listed at build time.

Real or stand-in? The generateStaticParams, dynamicParams and notFound code above is the real Next.js API, shown read-only. The builder is a stand-in: the real build renders React components and writes HTML plus data files under .next, and it stores on-demand pages in its cache rather than in a map.

Static export: a site that is only files

Sometimes you do not want a Node.js server at all. You may host on plain file storage, a CDN or a school server. Setting output: 'export' makes next build write a folder called out containing HTML, JavaScript and assets that any static host can serve:

TSX
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'export',
  images: { unoptimized: true }, // the default image optimizer needs a server
};

export default nextConfig;

After npm run build, upload the out folder. In exchange for this simplicity, every feature that needs a server at request time is unavailable. Next.js reports an error if you use one:

Feature In a static export
Dynamic routes Only the pages listed by generateStaticParams; no on-demand rendering
cookies(), headers(), searchParams on the server Not available (no request)
Route handlers Only GET handlers that read no request data
Server Actions Not supported
Proxy (middleware), redirects, rewrites, custom headers in config Not supported; configure your host instead
ISR and revalidation Not supported: rebuild and redeploy to update
Default image optimization Needs unoptimized: true or a custom loader

The browser still runs your Client Components, so interactive pages, client-side navigation and fetch calls to other servers work fine. The second stand-in checks an app's feature list against these limits.

Node.js Can this app be exported?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A portfolio or documentation site usually exports without changes. A shop with actions and revalidation needs a server, so it should keep the default output (see Building and Deploying).

A few practical tips

  • Keep generateStaticParams fast. It runs during the build, so a slow data source slows every deploy.
  • Return plain strings for params, since URL segments are always strings.
  • Fetch the list and the page data from the same source so a listed slug never renders an empty page.
  • If content changes between deploys, pair static pages with revalidation instead of rebuilding for every edit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does generateStaticParams return?

    Each object describes one set of params, for example { slug: 'hello' }, and Next.js renders the route once per object at build time.
  2. 2. With dynamicParams set to false, what happens when someone opens a URL that was not returned by generateStaticParams?

    dynamicParams false closes the set: only the listed pages exist and everything else is a 404.
  3. 3. Which feature is NOT available with output: 'export'?

    A static export has no server at request time, so Server Actions, request-based APIs, ISR and similar features cannot work.
  4. 4. In a nested route like /shop/[category]/[product], what does the child generateStaticParams receive?

    Next.js runs the parent function first and passes its params to the child, which keeps each level focused on its own segment.

Summary

  • Static generation renders pages during next build so they can be served as plain files.
  • generateStaticParams lists the params for a dynamic route; nested segments can generate level by level using the parent's params.
  • dynamicParams decides what happens to unlisted URLs: render on first visit (default) or return a 404.
  • output: 'export' writes a fully static out folder, but gives up request-time features: Server Actions, ISR, proxy, request-based APIs and the default image optimizer.
  • Build only what is popular and let the rest generate lazily when your catalog is huge.

Next: Streaming with Suspense