Lesson 15 +10 XP

Dynamic Rendering & Static Extraction

Dynamic Rendering & Static Extraction

Next.js provides route segment configuration options that allow developers to explicitly control how a page is rendered, cached, or optimized during build and runtime.

Segment Configuration Options

You can export configuration constants directly from any page.tsx, layout.tsx, or route.ts file:

// app/dashboard/page.tsx
export const dynamic = 'force-dynamic';
export const dynamicParams = true;
export const revalidate = 0;
export const fetchCache = 'force-no-store';

export default async function DashboardPage() {
  return <div>Live Analytics Dashboard</div>;
}

1. export const dynamic

Controls the rendering behavior of a route segment:

  • 'auto' (Default): Next.js automatically decides static vs dynamic based on dynamic functions and fetch options.
  • 'force-dynamic': Forces dynamic rendering on every request (equivalent to SSR). Disables static caching.
  • 'force-static': Forces static rendering. cookies(), headers(), and uncached fetch calls will return empty values or defaults.
  • 'error': Forces static rendering and throws a build error if any component uses dynamic functions or uncached data.

2. Static Site Generation with generateStaticParams

For dynamic routes like app/posts/[slug]/page.tsx, you can pre-generate specific routes at build time using generateStaticParams:

// app/posts/[slug]/page.tsx
import db from '@/lib/db';

// Pre-render these dynamic paths at build time!
export async function generateStaticParams() {
  const posts = await db.post.findMany({ select: { slug: true } });
  return posts.map((post) => ({
    slug: post.slug,
  }));
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  return <article>Post content for {slug}</article>;
}

Dynamic Segment Configuration Reference

Variable NameAllowed ValuesDefaultPurpose
dynamic'auto', 'force-dynamic', 'force-static', 'error''auto'Route rendering strategy override
dynamicParamstrue, falsetrueControls handling of ungenerated generateStaticParams paths
revalidatefalse, 0, or number (seconds)falseSegment cache revalidation interval
runtime'nodejs', 'edge''nodejs'Defines execution runtime environment

TL;DR

  • Override route rendering rules with export const dynamic = 'force-dynamic' | 'force-static'.
  • Use generateStaticParams to pre-render dynamic routes (e.g. [slug]) at build time.
  • Set export const dynamicParams = false to return a 404 for paths not returned by generateStaticParams.
  • Set export const runtime = 'edge' to run route segments on Edge Vercel workers.