Commit eeb0a2b7 authored by Jimmy Lai's avatar Jimmy Lai

Polish export fallback docs

parent e3891d82
...@@ -165,19 +165,20 @@ module.exports = nextConfig ...@@ -165,19 +165,20 @@ module.exports = nextConfig
During `next build`, Next.js uses [vary params](/docs/app/api-reference/functions/generate-static-params) to determine which parts of each route depend on which dynamic params. It then renders a fallback shell per dynamic route: During `next build`, Next.js uses [vary params](/docs/app/api-reference/functions/generate-static-params) to determine which parts of each route depend on which dynamic params. It then renders a fallback shell per dynamic route:
- **Param-independent layouts and components** (those that don't read the dynamic param) render fully as Server Components at build time. - **Param-independent layouts and components** (those that don't read the dynamic param) render fully as Server Components at build time.
- **Param-dependent components** (those that `await params`) suspend at the nearest [Suspense boundary](/docs/app/api-reference/components/suspense), showing your `loading.tsx` or `<Suspense fallback>` UI. - **Param-dependent boundaries** suspend at the nearest [Suspense boundary](/docs/app/api-reference/components/suspense), showing your `loading.tsx` or `<Suspense fallback>` UI.
Wrap param-dependent content in a Suspense boundary so the fallback shell can show meaningful loading UI: For `output: 'export'`, the most ergonomic shape is a shared Server Component shell with a Client Component leaf for paths you did not prerender with `generateStaticParams`. Wrap that client leaf in a Suspense boundary so the fallback shell can show meaningful loading UI:
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
import { Suspense } from 'react' import { Suspense } from 'react'
import { BlogPostClient } from './blog-post-client'
export default function Page({ params }: PageProps<'/blog/[slug]'>) { export default function Page() {
return ( return (
<main> <main>
<Sidebar /> {/* Renders fully in the shell (doesn't read slug) */} <Sidebar /> {/* Renders fully in the shell (doesn't read slug) */}
<Suspense fallback={<PostSkeleton />}> <Suspense fallback={<PostSkeleton />}>
<BlogPost params={params} /> {/* Shows skeleton until slug resolves */} <BlogPostClient />
</Suspense> </Suspense>
</main> </main>
) )
...@@ -186,22 +187,49 @@ export default function Page({ params }: PageProps<'/blog/[slug]'>) { ...@@ -186,22 +187,49 @@ export default function Page({ params }: PageProps<'/blog/[slug]'>) {
```jsx filename="app/blog/[slug]/page.js" switcher ```jsx filename="app/blog/[slug]/page.js" switcher
import { Suspense } from 'react' import { Suspense } from 'react'
import { BlogPostClient } from './blog-post-client'
export default function Page({ params }) { export default function Page() {
return ( return (
<main> <main>
<Sidebar /> {/* Renders fully in the shell (doesn't read slug) */} <Sidebar /> {/* Renders fully in the shell (doesn't read slug) */}
<Suspense fallback={<PostSkeleton />}> <Suspense fallback={<PostSkeleton />}>
<BlogPost params={params} /> {/* Shows skeleton until slug resolves */} <BlogPostClient />
</Suspense> </Suspense>
</main> </main>
) )
} }
``` ```
```tsx filename="app/blog/[slug]/blog-post-client.tsx" switcher
'use client'
import { useParams } from 'next/navigation'
export function BlogPostClient() {
const { slug } = useParams<{ slug: string }>()
return <Post slug={slug} />
}
```
```jsx filename="app/blog/[slug]/blog-post-client.js" switcher
'use client'
import { useParams } from 'next/navigation'
export function BlogPostClient() {
const { slug } = useParams()
return <Post slug={slug} />
}
```
> **Good to know**: A Suspense boundary lets Next.js emit the fallback shell at build time, but it does not create a runtime server request later. For unknown params in `output: 'export'`, request-specific data must still cross into a Client Component.
#### Combining with `generateStaticParams` #### Combining with `generateStaticParams`
If you export `generateStaticParams`, the returned params are fully prerendered at build time. Any other param values fall back to the shared shell. This lets you prerender your most popular pages while still supporting the long tail: If you export `generateStaticParams`, the returned params are fully prerendered at build time, which lets you keep using Server Components at build time for those known paths. Any other param values fall back to the shared shell. In other words, the same route can use both fully prerendered params and fallback-rendered unknown params:
```tsx filename="app/blog/[slug]/page.tsx" ```tsx filename="app/blog/[slug]/page.tsx"
// These slugs get full static HTML at build time // These slugs get full static HTML at build time
...@@ -222,12 +250,12 @@ For example, `/docs/[section]/[page]` is matched before `/docs/[...slug]`, so `/ ...@@ -222,12 +250,12 @@ For example, `/docs/[section]/[page]` is matched before `/docs/[...slug]`, so `/
To serve unenumerated params on a static host, configure the host's 404 or error document to serve `_fallback.html` from the export output: To serve unenumerated params on a static host, configure the host's 404 or error document to serve `_fallback.html` from the export output:
| Host | Configuration | | Host | Configuration |
| --------------- | ---------------------------------------------------- | | --------------- | -------------------------------------------------- |
| Nginx | `try_files $uri $uri/ /_fallback.html` | | Nginx | `try_files $uri $uri.html $uri/ /_fallback.html` |
| Apache | `ErrorDocument 404 /_fallback.html` | | Apache | `ErrorDocument 404 /_fallback.html` |
| S3 + CloudFront | Custom error response: 404 → `/_fallback.html` (200) | | S3 + CloudFront | Custom error response: 403/404 → `/_fallback.html` |
| GitHub Pages | Rename `_fallback.html` to `404.html` | | GitHub Pages | Copy `_fallback.html` to `404.html` |
When a user visits an unenumerated route, the host serves `_fallback.html`. The Next.js client router then discovers the correct fallback shell and renders the page with param-dependent content loading on the client. When a user visits an unenumerated route, the host serves `_fallback.html`. The Next.js client router then discovers the correct fallback shell and renders the page with param-dependent content loading on the client.
...@@ -256,6 +284,12 @@ server { ...@@ -256,6 +284,12 @@ server {
With `trailingSlash: true`, the same config works because prerendered routes are emitted as `/route/index.html` and unknown paths still fall back to `/_fallback.html`. With `trailingSlash: false`, keep the `try_files $uri $uri.html $uri/ /_fallback.html;` order so prerendered flat files are served before the fallback bootstrap. With `trailingSlash: true`, the same config works because prerendered routes are emitted as `/route/index.html` and unknown paths still fall back to `/_fallback.html`. With `trailingSlash: false`, keep the `try_files $uri $uri.html $uri/ /_fallback.html;` order so prerendered flat files are served before the fallback bootstrap.
#### Deployment tips
- **S3 + CloudFront**: If your S3 origin returns `403` for missing files, configure CloudFront custom error responses for both `403` and `404` to serve `/_fallback.html`. Use a `200` response code if you want SPA-style hard navigations for unknown params.
- **GitHub Pages**: Keep `_fallback.html` as the canonical export artifact, then copy it to `404.html` as part of your deploy step. GitHub Pages uses `404.html` as its static fallback entrypoint.
- **First paint**: `/_fallback.html` is a bootstrap document, not the final page. The first meaningful UI should come from the resolved fallback route shell, so prefer neutral loading states over route-specific content in that phase.
#### Server and client boundaries #### Server and client boundaries
Fallback routes in `output: 'export'` do not have a runtime server request. For unenumerated paths, request-specific APIs and unresolved fallback params are only available on the client. Fallback routes in `output: 'export'` do not have a runtime server request. For unenumerated paths, request-specific APIs and unresolved fallback params are only available on the client.
...@@ -285,6 +319,7 @@ export default async function Page() { ...@@ -285,6 +319,7 @@ export default async function Page() {
> **Good to know**: > **Good to know**:
> >
> - Param-dependent content for fallback routes renders on the client, so use client-side fetching patterns like `fetch`, SWR, or React Query in those parts of the tree. > - Param-dependent content for fallback routes renders on the client, so use client-side fetching patterns like `fetch`, SWR, or React Query in those parts of the tree.
> - Prefer `generateStaticParams` for SEO-critical or frequently visited routes, then let other paths use the export fallback shell.
> - Direct requests for unenumerated params may initially return a 404 status from the static host before the fallback shell loads. SEO-sensitive pages should be listed in `generateStaticParams`. > - Direct requests for unenumerated params may initially return a 404 status from the static host before the fallback shell loads. SEO-sensitive pages should be listed in `generateStaticParams`.
> - This mode does not provide ISR. Rebuilding is still required to promote a fallback path to a fully prerendered page. > - This mode does not provide ISR. Rebuilding is still required to promote a fallback path to a fully prerendered page.
> - Route names starting with `__fallback` are reserved and cannot be used with this feature. > - Route names starting with `__fallback` are reserved and cannot be used with this feature.
......
...@@ -160,6 +160,8 @@ All params are runtime data. Param access must be wrapped by Suspense fallback U ...@@ -160,6 +160,8 @@ All params are runtime data. Param access must be wrapped by Suspense fallback U
> **Good to know**: You can also use [`loading.tsx`](/docs/app/api-reference/file-conventions/loading) for page-level fallback UI. > **Good to know**: You can also use [`loading.tsx`](/docs/app/api-reference/file-conventions/loading) for page-level fallback UI.
> **Good to know**: When using [`output: 'export'`](/docs/app/guides/static-exports), the component that consumes unknown params should typically be a Client Component. That keeps the shared shell static while the long-tail route resolves on the client.
```tsx filename="app/blog/[slug]/page.tsx" ```tsx filename="app/blog/[slug]/page.tsx"
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -291,7 +293,15 @@ async function PrivatePost({ slug }: { slug: string }) { ...@@ -291,7 +293,15 @@ async function PrivatePost({ slug }: { slug: string }) {
} }
``` ```
When using [`output: 'export'`](/docs/app/guides/static-exports) for App Router dynamic routes with `cacheComponents: true`, `generateStaticParams` is optional. Next.js emits a shared fallback shell for the dynamic route, prerenders any param-independent layouts or Server Components at build time, and resolves param-dependent content on the client. If you still export `generateStaticParams`, those params are fully prerendered and the rest use the fallback shell. When using [`output: 'export'`](/docs/app/guides/static-exports) for App Router dynamic routes with `cacheComponents: true`, `generateStaticParams` is optional. Next.js emits a shared fallback shell for the dynamic route, prerenders any param-independent layouts or Server Components at build time, and resolves param-dependent content on the client. If you still export `generateStaticParams`, those params are fully prerendered so you can keep using Server Components at build time for the paths you know ahead of time, and the rest use the fallback shell. The same route can do both at once: prerender the params you return and fall back for the params you do not return.
For the best ergonomics in `output: 'export'`:
- Keep shared layout and shell content in Server Components.
- Move param reads and request-specific data for paths you did not prerender into Client Components.
- Use Suspense to show loading UI while the client resolves those paths.
> **Good to know**: In `output: 'export'`, a Suspense boundary makes the shell prerenderable, but it does not create a runtime server request. Unknown params still need a Client Component boundary if they depend on request-time data.
## Examples ## Examples
......
...@@ -311,10 +311,16 @@ When using [Cache Components](/docs/app/getting-started/caching) with dynamic ro ...@@ -311,10 +311,16 @@ When using [Cache Components](/docs/app/getting-started/caching) with dynamic ro
For server deployments, `generateStaticParams` must return **at least one param**. Empty arrays cause a [build error](/docs/messages/empty-generate-static-params). This allows Cache Components to validate your route doesn't incorrectly access `cookies()`, `headers()`, or `searchParams` at runtime. For server deployments, `generateStaticParams` must return **at least one param**. Empty arrays cause a [build error](/docs/messages/empty-generate-static-params). This allows Cache Components to validate your route doesn't incorrectly access `cookies()`, `headers()`, or `searchParams` at runtime.
When using [`output: 'export'`](/docs/app/guides/static-exports) with App Router dynamic routes, `generateStaticParams` becomes optional when `cacheComponents: true` is enabled. If you omit it, Next.js emits a fallback shell for the route and resolves param-dependent content on the client. If you provide it, the returned params are prerendered and all other params use the fallback shell. When using [`output: 'export'`](/docs/app/guides/static-exports) with App Router dynamic routes, `generateStaticParams` becomes optional when `cacheComponents: true` is enabled. If you omit it, Next.js emits a fallback shell for the route and resolves param-dependent content on the client. If you provide it, the returned params are prerendered so you can keep using Server Components at build time for the paths you know ahead of time, and all other params use the fallback shell. The same route can mix both behaviors: prerendered params from `generateStaticParams` and fallback rendering for params you did not return.
When multiple dynamic route patterns share the same static prefix in `output: 'export'`, the fallback shell still follows normal App Router route specificity. For example, if both `/docs/[section]/[page]` and `/docs/[...slug]` exist, params returned by `generateStaticParams` for the specific route are prerendered as usual, while unknown params still fall back and match the most specific route first. When multiple dynamic route patterns share the same static prefix in `output: 'export'`, the fallback shell still follows normal App Router route specificity. For example, if both `/docs/[section]/[page]` and `/docs/[...slug]` exist, params returned by `generateStaticParams` for the specific route are prerendered as usual, while unknown params still fall back and match the most specific route first.
For the best authoring ergonomics in `output: 'export'`:
- Return the params you care about most for SEO or fast first loads.
- Let other paths use the export fallback shell.
- Keep param-dependent request data in Client Components for paths you did not prerender.
> **Good to know**: If you don't know the actual param values at build time, you can return a placeholder param (e.g., `[{ slug: '__placeholder__' }]`) for validation, then handle it in your page with `notFound()`. However, this prevents build time validation from working effectively and may cause runtime errors. > **Good to know**: If you don't know the actual param values at build time, you can return a placeholder param (e.g., `[{ slug: '__placeholder__' }]`) for validation, then handle it in your page with `notFound()`. However, this prevents build time validation from working effectively and may cause runtime errors.
See the [dynamic routes section](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components) for detailed walkthroughs. See the [dynamic routes section](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components) for detailed walkthroughs.
......
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