Commit f797ac65 authored by Delba de Oliveira's avatar Delba de Oliveira

Create page-variations.mdx

parent 55046e23
---
title: Building variations of the same page
description: Learn how to create page variations with route params, prerender them with generateStaticParams, and add conditional dynamic content.
nav_title: Page variations
---
Product pages, blog posts, user profiles, etc. These pages share the same layout and components, but display different content based on URL route params.
This guide shows you how to create variations of the same page with [route params](/docs/app/api-reference/file-conventions/dynamic-routes) and [Cache Components](/docs/app/getting-started/cache-components), prerender a subset of them at [build time](/docs/app/glossary#build-time), and add conditional dynamic content without breaking prerendering.
## Example
As an example, we'll build a product detail page that displays product information based on a URL slug.
We'll start by creating the route, then prerender pages at build time, and finally add a conditional "In Demand" badge that shows live activity data for each product.
You can find the resources used in this example here:
- [Demo](https://cache-components-page-variations.labs.vercel.dev/products)
- [Code](https://github.com/vercel-labs/cache-components-pages-variations)
### Step 1: Create variations with route params
Create a dynamic route segment by wrapping the folder name in square brackets:
```bash filename="Terminal"
app/products/[slug]/page.tsx
```
The value in the brackets is the route param. Next.js passes it to the page component as a prop, which you can use to fetch the matching product data.
```tsx filename="app/products/[slug]/page.tsx"
import { notFound } from 'next/navigation'
import { getProduct } from '@/app/products/data'
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await getProduct(slug)
if (!product) notFound()
return (
<>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>${product.price}</p>
</>
)
}
```
The `getProduct` function fetches product data and caches the result with [`'use cache'`](/docs/app/api-reference/directives/use-cache):
```tsx filename="app/products/data.ts"
export async function getProduct(slug: string): Promise<Product> {
'use cache'
const response = await fetch(
`https://next-recipe-api.vercel.dev/products/${slug}`
)
return response.json()
}
```
Visiting `/products/shorts` passes `"shorts"` as the slug. The page fetches and renders that product's data. Visiting `/products/shoes` renders a different product using the same components.
Even though the data is cached, the page still depends on `params`, which can only be resolved when a request arrives. If we run [`next build`](/docs/app/api-reference/cli/next#next-build-options), the route is marked as dynamic:
```bash filename="Terminal"
Route (app)
├ ƒ /products/[slug]
└ ○ /_not-found
ƒ (Dynamic) server-rendered on demand
```
The framework doesn't know which slugs exist ahead of time. Every request triggers a fresh render. To prerender these pages, we need to tell Next.js which param values to expect.
### Step 2: Prerender variations with generateStaticParams
Export a [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) function that returns an array of param objects. Each object matches the shape of the route segment:
```tsx filename="app/products/[slug]/page.tsx"
import { notFound } from 'next/navigation'
import { getProduct, getProducts } from '@/app/products/data'
export async function generateStaticParams() {
const products = await getProducts()
return products.map((product) => ({ slug: product.slug }))
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await getProduct(slug)
if (!product) notFound()
return (
<>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>${product.price}</p>
</>
)
}
```
This tells the framework which param values to prerender at build time. For each returned object, Next.js renders the page and caches the output.
For large catalogs with thousands of products, prerendering every page at build time would slow down deployments. A common strategy is to prerender a subset, like the most popular products:
```tsx filename="app/products/[slug]/page.tsx"
export async function generateStaticParams() {
const products = await getProducts({ orderBy: 'popularity', take: 50 })
return products.map((product) => ({ slug: product.slug }))
}
```
Products not on the list are rendered on demand when the first visitor requests them. The result is cached for future visitors.
If we run `next build` again, the route is now static:
```bash filename="Terminal"
Route (app)
├ ○ /products/[slug]
└ ○ /_not-found
○ (Static) prerendered as static content
```
The page is fully prerendered. The `notFound()` call handles slugs that don't match any product, returning a 404 response.
### Step 3: Add conditional dynamic content
Sometimes, you may want to add dynamic content without opting the entire page out of prerendering.
For example, let's add a "In Demand" badge based on live sales activity.
```tsx filename="app/products/ui.tsx"
import { getActivity } from '@/app/products/data'
export async function InDemandBadge({ slug }: { slug: string }) {
const { inDemand } = await getActivity(slug)
if (!inDemand) return null
return <div>In demand</div>
}
```
The `getActivity` function fetches data without `'use cache'`, so it always returns fresh data. The component returns `null` when the product is not in demand.
Wrap the `<InDemandBadge>` component in a [`<Suspense>`](/docs/app/glossary#suspense-boundary) boundary:
```tsx filename="app/products/[slug]/page.tsx"
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getProduct, getProducts } from '@/app/products/data'
import { InDemandBadge } from '@/app/products/ui'
export async function generateStaticParams() {
const products = await getProducts()
return products.map((product) => ({ slug: product.slug }))
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await getProduct(slug)
if (!product) notFound()
return (
<>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>${product.price}</p>
<Suspense>
<InDemandBadge slug={slug} />
</Suspense>
</>
)
}
```
> **Good to know:** This `<Suspense>` boundary has no `fallback` slot. The badge may return `null`, so an empty fallback avoids rendering an unnecessary skeleton.
With this change, the route becomes [partially prerendered](/docs/app/glossary#partial-prerendering-ppr). If we run `next build`:
```bash filename="Terminal"
Route (app)
├ ◐ /products/[slug]
└ ○ /_not-found
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
```
At build time, the product name, description, and price are prerendered for each variant. At request time, the badge slot resolves: either streaming in the "In Demand" badge, or rendering nothing.
## Next steps
You now know how to create page variations with route params, prerender them with `generateStaticParams`, and add conditional dynamic content with Suspense.
Next, learn how to:
- [Revalidate cached data](/docs/app/getting-started/caching-and-revalidating)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment