The event page query is cached, and even so the first person to open /events/jazz-night sees a skeleton. The reason isn't the data but the address: at build time, Next.js knows the route /events/[slug] exists, but not which slugs are possible. params is still request data, and everything that depends on it is left out of the shell.
generateStaticParams closes that hole: it tells Next.js which values you know, so it generates those pages ahead of time. You'll see what it produces at build time, what happens with the addresses that weren't included, why it can't return an empty list, which status codes you get and how to decide how many pages to generate. With it, the cycle that other models call ISR is complete.
- Making the values known
The function is exported from the page (or a layout) that contains the dynamic segment, and returns an array of objects with its parameters. First, the query for the slugs:
// lib/data/events.ts (addition)
// The upcoming events, to generate their pages in advance
export async function listEventSlugs(limit: number): Promise<string[]> {
const db = await getDb()
const rows = await db
.select({ slug: events.slug })
.from(events)
.where(isCurrent())
.orderBy(...byDate)
.limit(limit)
return rows.map(({ slug }) => slug)
}// app/(public)/events/[slug]/page.tsx (addition; imports listEventSlugs)
const PREBUILT_PAGES = 50
export async function generateStaticParams() {
const slugs = await listEventSlugs(PREBUILT_PAGES)
if (slugs.length === 0) return [{ slug: '__no-events__' }]
return slugs.map((slug) => ({ slug }))
}EventDetailPage, EventContent and RelatedEvents don't change. They still receive params as a promise and await it under their <Suspense>. The difference is that, for those slugs, the promise resolves during prerendering.
- It doesn't use
'use cache'. It runs once, at build time; storing its result adds nothing. io()resolves instantly here too, sogetDb()and the clock inisCurrent()work.- The values are strings, even if they were numbers in the database:
{ id: String(row.id) }. - The object's key is the folder name. With
[slug],slug.
In development it's called when you navigate to the route. At build time, once, before generating the pages. On revalidation it is not called again: the list is a snapshot of when the build ran.
Do the same with the venues, of which there are four:
// app/(public)/venues/[slug]/page.tsx (addition; imports listVenues)
export async function generateStaticParams() {
const venues = await listVenues()
if (venues.length === 0) return [{ slug: '__no-venues__' }]
return venues.map(({ slug }) => ({ slug }))
}
- What the build produces
The next build table grows. This one is approximate and trimmed:
Route (app) Revalidate Expire ┌ ◐ / 15m 1h ├ ○ /_not-found ├ ƒ /api/events/[slug]/availability ├ ƒ /api/suggestions ├ ◐ /events 1d 1w ├ /events/[slug] │ ├ ◐ /events/[slug] │ ├ ◐ /events/riverside-quartet 15m 1h │ ├ ◐ /events/pottery-workshop 15m 1h │ └ [+5 more paths] ├ ◐ /venues 1d 1w └ /venues/[slug] ├ ◐ /venues/[slug] ├ ◐ /venues/mill-theater 15m 1h └ [+3 more paths]
How to read it:
- The row without a symbol is the pattern, and it groups the others.
- The first child, with the same name, is the fallback: the App Shell served for a slug that isn't on the list.
- The rest are generated pages, each with its own shell.
- They're still
◐because of two holes we chose:SiteNoticein the layout and, on the event page, the spots. Without them they'd be○. 15mand1hare imposed by the list of related events, with thelistingsprofile. The event page alone would have an hour and a day.
Compare the first chunk of the response with the one from 04-04:
Before, two skeletons arrived. Now the first chunk brings the title, date, location, description, related events and, if the weather API responded at build time, the forecast; only the holes for the spots and the notice remain. The page heading, which in 04-04 depended on a query, is in the HTML from the first byte. The Navigation Inspector confirms it with Page load.
- The addresses that weren't included
Our list has the next fifty current events. Missing are the later ones, the finished ones, the ones published tomorrow and the ones that never existed. With Cache Components, they're all served: there's no option to reject them (dynamicParams, from the previous model, isn't supported).
sequenceDiagram
participant A as First visit
participant S as Server
participant B as Next visit
A->>S: GET /events/autumn-choir (wasn't on the list)
S-->>A: App Shell: header, skeletons, footer
S->>S: renders with the slug now known
S-->>A: event page and related events, over the same stream
S->>S: in the background, generates and stores the page
B->>S: GET /events/autumn-choir
S-->>B: full shell, from the cache
The first visit receives the fallback instantly and the content right after. Then Next.js upgrades the page: it generates it again knowing the slug, pushes the static boundary as far down as it can and stores it. From then on it behaves as if it had been on the list. The result depends on what it finds:
| The page, with all parameters known… | What's stored |
|---|---|
| Only reads cached data | A fully static page |
Also has holes under <Suspense> |
A shell with its content and those holes |
That behavior requires three things, which AgendaViva meets:
- Exporting
generateStaticParams. Without it, the route is left out of the mechanism: it's rendered on every request, even if its data is cached. That's what was happening until now. - Having partial prefetching enabled (
partialPrefetching: true), which is what allows awaitingparamsinside a<Suspense>and serving the fallback. Without it, the first visit waits for the complete result, andparamsmust be awaited outside any boundary for the page to be stored; if it's inside, the shared fallback is always served. You'll come across projects like that, predating 16.3. - Handling holes well, so that something static is left.
An ordinary link to an event page prefetches the App Shell, which is shared by all of them. With prefetch={true}, on the other hand, it prefetches that URL and brings the upgrade forward to the moment the link becomes visible. Which links deserve it is decided in 10-02.
3.1. Validation only covers the sample
At build time the page is run with the values you provided. Code paths taken only by other values aren't checked:
// Danger: no slug in the sample starts with 'private-'
if (slug.startsWith('private-')) {
const access = (await cookies()).get('access') // Outside a Suspense
// …
}The build passes, and the first visit to a private-… address fails at runtime. If there are branches depending on the value, include one of each kind in the sample.
- Never empty
In the previous model, returning [] meant "generate each page on its first visit". With Cache Components it's a build error, empty-generate-static-params. The reason is the one from the previous section: with no values there's no page to run, and Next.js can't check that the route doesn't read the request where it shouldn't.
One is enough to comply. And what if there's no data at build time, for example in a new environment? The documentation suggests a placeholder value, which is what we do: '__no-events__' doesn't exist, getEventDetails returns null and EventContent calls notFound(). There's no need to handle it separately.
Keep in mind what you lose: with the placeholder, only the "not found" path is validated. If your CI always builds with an empty database, the event page's failures will show up in production. It's one more reason to seed data before building.
- How many pages
Generating them all is tempting with 8 events and absurd with 80,000. Each page costs build time, storage and queries, and many won't be visited before the next deployment. Since the missing ones are generated on their own, the list doesn't have to be complete, but cost-effective:
| Criterion | Example in AgendaViva |
|---|---|
| The most visited | The upcoming events |
| The ones that arrive from outside without warming up | Those shared on social media or in a newsletter |
| Few and fixed | The venues: all of them |
| Representatives of each code path | At least one outdoor event, which renders the forecast |
| Historical archive | None |
Fifty is an arbitrary number and easy to change. Measure: if the build takes minutes longer, there are too many; if after each deployment the logs show lots of first visits to the same event pages, there are too few.
Watch out for one detail: listRelatedEvents, the event page and the forecast are queried for each page. Fifty event pages mean a hundred-odd queries, split among the processes doing the prerendering. With QUERY_DELAY_MS=300 you'll notice; in CI, set it to zero.
5.1. The database at build time
In 05-02 the build started to need data for the home page and the venues. Now it depends on it even more: if the database doesn't respond, there's no list and the build fails; if it responds with data from another environment, pages are generated for someone else's events.
| Strategy | Pros | Cons |
|---|---|---|
| Build against a read replica of production | The shells are correct from the start | Network and credentials in CI; load on the replica |
| PostgreSQL service, migrated and seeded | Isolated and reproducible | The shells contain sample data: for checking only |
| Build in the target environment itself, when deploying | Real data without exposing the database | Deployment takes longer and can fail because of the data |
The usual approach is to use the second to check every change and the first or third for the artifact that gets deployed. We'll come back to this in 11-04 to 11-06. And in every case, the migrations go first.
- Pages that don't exist
In 02-04 we left getting a real 404 for later. Let's gather what we know. A status code can only be set before the response starts:
| Case | Code |
|---|---|
| The URL doesn't match any route | 404 |
notFound() runs while prerendering a URL |
404 |
notFound() runs at request time, after the shell |
200 with noindex |
proxy.ts decides, before the page |
404 (07-02) |
With generateStaticParams, the second row comes into play: for what's prerendered, the decision is made with no response under way. But most nonexistent addresses (a typo, a bot trying names) won't be on the list, and their first visit receives the App Shell with a 200.
And the following visits, once the page has been generated in the background? The documentation states that notFound() returns a 404 when it runs during a prerender; it doesn't detail what's stored if the call happens under a <Suspense>, as on our page. Check it on your version instead of assuming:
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/events/does-not-exist
sleep 2
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/events/does-not-existThere's a variant that removes the uncertainty of the first visit: ensureStatic = 'navigation'. With it, a URL that wasn't included waits for the full page to be generated, instead of receiving a fallback. It requires the route to be entirely static, and ours isn't.
For search engines, a 200 with noindex isn't indexed, and for people the page is the same. If you need the exact code, for analytics or regulatory reasons, the place for it is proxy.ts: a quick check of the slug before rendering. We'll do that in 07-02.
One behavior you do want to anticipate: the absence is stored too. Someone visits an address today that will be published tomorrow; the null entry has carried the event:slug tag since 05-03, and invalidateEvent removes it on publishing. Without that tag, the new event could take an hour to show up. That's also why an event's slug is decided before it's announced.
- Nested routes
AgendaViva doesn't have routes with two parameters, but they're common. Imagine an archive by category and month, /archive/[category]/[month]. There are two ways to provide the values. From the bottom, the page returns all the segments:
// Example only: app/(public)/archive/[category]/[month]/page.tsx
export async function generateStaticParams() {
const combinations = await listCategoriesWithMonths()
return combinations.map(({ category, month }) => ({ category, month }))
}From the top, each level contributes its own. The child function runs once for each value of the parent and receives it, already resolved and without await:
// Example only: app/(public)/archive/[category]/layout.tsx
export function generateStaticParams() {
return CATEGORIES.map((category) => ({ category }))
}
// Example only: app/(public)/archive/[category]/[month]/page.tsx
export async function generateStaticParams({
params: { category },
}: {
params: { category: string }
}) {
const months = await listMonths(category)
return months.slice(0, 3).map((month) => ({ month }))
}A segment can provide values for itself and for those above it, never for those below. The "from the top" approach has an advantage: it generates intermediate fallbacks. With concert and 2028-05 in the sample, these are produced:
| Shell | What's known | Who receives it |
|---|---|---|
/archive/concert/2028-05 |
Everything | That URL |
/archive/concert/[month] |
The category | Any other month of concert |
/archive/[category]/[month] |
Nothing | Categories not included |
Unknown parameters always come last: there's no fallback for "month known, category not". And for them to be of any use, each level must await its own parameter inside its own <Suspense>; if the layout awaits params at the top, its shell is tied to one URL.
With segments that capture several ([...path]), the value is an array: { path: ['help', 'bookings'] }. And generateStaticParams also works in a dynamic Route Handler: it generates its responses at build time, if what it reads is cached.
- The full cycle
What you've put together over these five lessons is known as incremental static regeneration (ISR): static pages that are created and updated without rebuilding. In this model it isn't an option you switch on, but the result of combining pieces:
| Question | Piece |
|---|---|
| Which pages exist ahead of time? | generateStaticParams |
| What do they contain? | What's deterministic and what's cached |
| What's left for the request? | Whatever is under <Suspense> without a cache |
| When are they renewed? | The shortest lifetime among their caches |
| And if a piece of data changes sooner? | Tags |
| And the missing ones? | Fallback, and an upgrade after the first visit |
flowchart LR
A["next build"] --> B["Stored page"]
C["First visit<br/>to a new URL"] --> B
B -- "visit after revalidate" --> D["Served and regenerated behind the scenes"]
B -- "expire with no visits" --> E["The next one waits"]
B -- "updateTag" --> E
B -- "revalidateTag with max" --> D
D --> B
E --> B
F["New deployment"] --> A
When a page is regenerated, the entries that are still valid are reused. If event:jazz-night is invalidated, its page is rebuilt, but the related events and the forecast come out of the cache if they haven't expired. Caching the data separately, rather than the whole page, makes each regeneration cheap.
And the limits, worth keeping in mind when deploying:
- Pages are stored on each instance's disk. In ephemeral containers they're lost on restart, and with several instances each has its own (11-05).
- Each deployment starts with the pages from its own build: what the previous one generated at runtime isn't inherited.
- Regeneration is run by the server that receives the visit, and it counts as compute.
- It doesn't work with static export, which has no server.
Common Mistakes and Tips
- Returning
[]or a value that isn't an array of objects. - Removing
generateStaticParamsbecause "the data is already cached": the route stops being stored. - Returning numbers instead of strings.
- Trying to generate everything. The missing addresses are generated on their own.
- Awaiting
paramsabove the<Suspense>and leaving the fallback tied to one URL. - Looking for
dynamicParams. It isn't supported with Cache Components. - Building against an empty database and believing the event pages have been validated.
- Relying on the 404 code for an address that wasn't prerendered.
- Forgetting to invalidate the absence when publishing a resource whose address was already known.
- Seeing
◐on the generated pages and thinking it didn't work. Look for which hole is left.
Exercises
Exercise 1: tracing a visit
With the sample of 50 events, describe what each visit receives and what ends up stored: (a) /events/jazz-night, included; (b) an event published yesterday, after the deployment, the first time; (c) the same one, an hour later; (d) /events/jazz-nigth, a typo; (e) /events/jazz-night right after its organizer changes the description.
Solution
- (a) The shell with the whole event page, and the spots and the notice streamed in. It was already stored.
- (b) The App Shell, with skeletons, and the event page right after. Then its shell is stored.
- (c) The stored shell. More than 15 minutes have passed, so it's also regenerated behind the scenes; and if the hour had gone by with no visits, because of the
listingsprofile'sexpire, this visit would wait. - (d) The App Shell with a 200 and, streamed, the not-found page with
noindex. Anullentry with theevent:jazz-nigthtag is left behind. - (e) The action called
invalidateEvent: what was stored has expired and the next visit waits for the new event page. The organizer saw it in her action's response.
Exercise 2: guaranteeing the sample
We want the build to always validate the forecast branch, even if none of the upcoming events is outdoors. Change generateStaticParams to include at least one, without duplicates and without failing if there isn't one.
Solution
// lib/data/events.ts
export async function getOutdoorEventSlug(): Promise<string | null> {
const db = await getDb()
const [row] = await db
.select({ slug: events.slug })
.from(events)
.innerJoin(venues, eq(events.venueId, venues.id))
.where(and(isCurrent(), eq(venues.outdoor, true)))
.orderBy(...byDate)
.limit(1)
return row?.slug ?? null
}// app/(public)/events/[slug]/page.tsx
export async function generateStaticParams() {
const [upcoming, outdoor] = await Promise.all([
listEventSlugs(PREBUILT_PAGES),
getOutdoorEventSlug(),
])
const slugs = new Set(upcoming)
if (outdoor) slugs.add(outdoor)
if (slugs.size === 0) return [{ slug: '__no-events__' }]
return Array.from(slugs, (slug) => ({ slug }))
}The Set avoids repeating the page if it was already among the fifty. The project keeps the simple version: the seed data includes an outdoor event, river-tales.
Exercise 3: a two-level route
A documentation site has /docs/[version]/[...path], with 3 versions and 400 pages each. The current version gets 95% of the visits. Design what to generate, with code, and explain what someone receives the first time they open a page from an old version.
Solution
// app/docs/[version]/layout.tsx
export async function generateStaticParams() {
const versions = await listVersions() // ['3', '2', '1']
return versions.map((version) => ({ version }))
}
// app/docs/[version]/[...path]/page.tsx
export async function generateStaticParams({
params: { version },
}: {
params: { version: string }
}) {
const pages = await listPages(version) // [['start'], ['guide', 'routing'], …]
const isCurrentVersion = version === (await getCurrentVersion())
return (isCurrentVersion ? pages : pages.slice(0, 1)).map((path) => ({ path }))
}All 400 pages of the current version are generated, plus one from each old version, which is enough to validate the path and avoid returning an empty list. Whoever opens an old page that wasn't included receives /docs/2/[...path]: with the version 2 header already rendered, if the layout awaits its parameter inside a <Suspense>, and the article streamed in. After that it's stored. Old versions don't change, so their data can take cacheLife('max').
Conclusion
generateStaticParams turns params into known data for the values you choose, and with it the whole event page fits in the shell. The other values receive a shared fallback and are stored after their first visit. It can't return an empty list, because the build validates the route by running it; the sample should cover every code path. The 404 code is only reliable when it's decided before responding. And the sum of known pages, lifetimes, tags and holes is incremental regeneration, with no option to switch it on.
AgendaViva now serves almost all of its public content without making anyone wait. But most of the Next.js code you'll find in other projects was written under different rules. The module closes with The Previous Caching Model and Migrating from It: how to read it, why it behaves the way it does and how to bring it up to date.
