diff --git a/docs/01-getting-started/03-react-essentials.mdx b/docs/01-getting-started/03-react-essentials.mdx
index 859f771387f17..b199d7ba1c864 100644
--- a/docs/01-getting-started/03-react-essentials.mdx
+++ b/docs/01-getting-started/03-react-essentials.mdx
@@ -17,7 +17,7 @@ Server and Client Components allow developers to build applications that span th
### Thinking in Server Components
-Similar to how React changed the way we think about building UIs, React Server Components introduce a new mental model for building hybrid applications that leverage the [server and the client](/docs/app/building-your-application/rendering#rendering-environments).
+Similar to how React changed the way we think about building UIs, React Server Components introduce a new mental model for building hybrid applications that leverage the server and the client.
Instead of React rendering your whole application client-side (such as in the case of Single-Page Applications), React now gives you the flexibility to choose where to render your components based on their purpose.
@@ -47,7 +47,7 @@ To make the transition to Server Components easier, all components inside the [A
## Client Components
-Client Components enable you to add client-side interactivity to your application. In Next.js, they are [pre-rendered](/docs/app/building-your-application/rendering#component-level-client-and-server-rendering) on the server and [hydrated](/docs/app/building-your-application/rendering#component-level-client-and-server-rendering) on the client. You can think of Client Components as how components in the [Pages Router](/docs/pages) have always worked.
+Client Components enable you to add client-side interactivity to your application. In Next.js, they are [pre-rendered](/docs/app/building-your-application/rendering) on the server and hydrated on the client. You can think of Client Components as how components in the [Pages Router](/docs/pages) have always worked.
### The "use client" directive
@@ -186,7 +186,7 @@ Behind the scenes, React handles rendering as follows:
- On the client, React renders Client Components and _slots in_ the rendered result of Server Components, merging the work done on the server and client.
- If any Server Components are nested inside a Client Component, their rendered content will be placed correctly within the Client Component.
-> **Good to know**: In Next.js, during the initial page load, both the rendered result of Server Components from the above step and Client Components are [pre-rendered on the server as HTML](/docs/app/building-your-application/rendering#static-and-dynamic-rendering-on-the-server) to produce a faster initial page load.
+> **Good to know**: In Next.js, during the initial page load, both the rendered result of Server Components from the above step and Client Components are [pre-rendered on the server as HTML](/docs/app/building-your-application/rendering) to produce a faster initial page load.
### Nesting Server Components inside Client Components
@@ -345,7 +345,7 @@ Props passed from the Server to Client Components need to be [serializable](http
> **Where is the Network Boundary?**
>
-> In the App Router, the network boundary is between Server Components and Client Components. This is different from the Pages where the boundary is between `getStaticProps`/`getServerSideProps` and Page Components. Data fetched inside Server Components do not need to be serialized as it doesn't cross the network boundary unless it is passed to a Client Component. Learn more about [data fetching](/docs/app/building-your-application/data-fetching#fetching-data-on-the-server) with Server Components.
+> In the App Router, the network boundary is between Server Components and Client Components. This is different from the Pages where the boundary is between `getStaticProps`/`getServerSideProps` and Page Components. Data fetched inside Server Components do not need to be serialized as it doesn't cross the network boundary unless it is passed to a Client Component. Learn more about [data fetching](/docs/app/building-your-application/data-fetching/patterns#fetching-data-on-the-server) with Server Components.
### Keeping Server-Only Code out of Client Components (Poisoning)
@@ -860,4 +860,4 @@ In the above example, both the layout and page need to make database queries. Ea
When fetching data, you may want to share the result of a `fetch` between a `page` or `layout` and some of its children components. This is an unnecessary coupling between the components and can lead to passing `props` back and forth between components.
-Instead, we recommend colocating data fetching alongside the component that consumes the data. [`fetch` requests are automatically deduped](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) in Server Components, so each route segment can request exactly the data it needs without worrying about duplicate requests. Next.js will read the same value from the `fetch` cache.
+Instead, we recommend colocating data fetching alongside the component that consumes the data. [`fetch` requests are automatically memoized](/docs/app/building-your-application/caching#request-memoization) in Server Components, so each route segment can request exactly the data it needs without worrying about duplicate requests. Next.js will read the same value from the `fetch` cache.
diff --git a/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx b/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx
index 54a6a984b4755..cdd6a122a9e48 100644
--- a/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx
@@ -111,7 +111,7 @@ export default function DashboardLayout({
> - You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts.
> - Layouts are [Server Components](/docs/getting-started/react-essentials) by default but can be set to a [Client Component](/docs/getting-started/react-essentials#client-components).
> - Layouts can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information.
-> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) without affecting performance.
+> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/caching#request-memoization) without affecting performance.
> - Layouts do not have access to the current route segment(s). To access route segments, you can use [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) in a Client Component.
> - `.js`, `.jsx`, or `.tsx` file extensions can be used for Layouts.
> - A `layout.js` and `page.js` file can be defined in the same folder. The layout will wrap the page.
diff --git a/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx b/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx
index 1c4d5735ac5ce..b35194032532b 100644
--- a/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx
@@ -2,25 +2,23 @@
title: Linking and Navigating
description: Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook.
related:
- description: Learn more about statically typed links with TypeScript.
links:
+ - app/building-your-application/caching
- app/building-your-application/configuring/typescript
---
-The Next.js router uses [server-centric routing](/docs/app/building-your-application/routing#server-centric-routing-with-client-side-navigation) with [client-side navigation](#how-navigation-works). It supports [instant loading states](/docs/app/building-your-application/routing/loading-ui-and-streaming) and [concurrent rendering](https://react.dev/reference/react/startTransition). This means navigation maintains client-side state, avoids expensive re-renders, is interruptible, and doesn't cause race conditions.
+There are two ways to navigate between routes in Next.js:
-There are two ways to navigate between routes:
-
-- [`` Component](#link-component)
-- [`useRouter` Hook](#userouter-hook)
+- Using the [`` Component](#link-component)
+- Using the [`useRouter` Hook](#userouter-hook)
This page will go through how to use ``, `useRouter()`, and dive deeper into how navigation works.
## `` Component
-`` is a React component that extends the HTML `` element to provide [prefetching](#prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
+`` is a built-in component that extends the HTML `` tag to provide [prefetching](#1-prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
-To use ``, import it from `next/link`, and pass a `href` prop to the component:
+You can use it by importing it from `next/link`, and passing a `href` prop to the component:
```tsx filename="app/page.tsx" switcher
import Link from 'next/link'
@@ -38,11 +36,11 @@ export default function Page() {
}
```
-There are optional props you can pass to ``. See the [API reference](/docs/app/api-reference/components/link) for more information.
+There are other optional props you can pass to ``. See the [API reference](/docs/app/api-reference/components/link) for more.
-## Examples
+### Examples
-### Linking to Dynamic Segments
+#### Linking to Dynamic Segments
When linking to [dynamic segments](/docs/app/building-your-application/routing/dynamic-routes), you can use [template literals and interpolation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to generate a list of links. For example, to generate a list of blog posts:
@@ -62,7 +60,7 @@ export default function PostList({ posts }) {
}
```
-### Checking Active Links
+#### Checking Active Links
You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to determine if a link is active. For example, to add a class to the active link, you can check if the current `pathname` matches the `href` of the link:
@@ -95,15 +93,24 @@ export function Navigation({ navLinks }) {
}
```
-### Scrolling to an `id`
+#### Scrolling to an `id`
+
+The default behavior of `` is to scroll to the top of a new route or to maintain the scroll position for backwards and forwards navigation.
+
+If you'd like to scroll to a specific `id` on navigation, you can append your URL with a `#` hash link or just pass a hash link to the `href` prop. This is possible since `` renders to an `` element.
-The default behavior of `` is to [scroll to the top of the route segment that has changed](#focus-and-scroll-management). When there is an `id` defined in `href`, it will scroll to the specific `id`, similarly to a normal `` tag.
+```jsx
+Settings
+
+// Output
+Settings
+```
## `useRouter()` Hook
-The `useRouter` hook allows you to programmatically change routes inside [Client Components](/docs/getting-started/react-essentials).
+The `useRouter` hook allows you to programmatically change routes.
-To use `useRouter`, import it from `next/navigation`, and call the hook inside your Client Component:
+This hook can only be used inside Client Components and is imported from `next/navigation`.
```jsx filename="app/page.js"
'use client'
@@ -121,70 +128,64 @@ export default function Page() {
}
```
-The `useRouter` provides methods such as `push()`, `refresh()`, and more. See the [API reference](/docs/app/api-reference/functions/use-router) for more information.
+For a full list of `useRouter` methods, see the [API reference](/docs/app/api-reference/functions/use-router).
> **Recommendation:** Use the `` component to navigate between routes unless you have a specific requirement for using `useRouter`.
-## How Navigation Works
+## How Routing and Navigation Works
-- A route transition is initiated using `` or calling `router.push()`.
-- The router updates the URL in the browser's address bar.
-- The router avoids unnecessary work by re-using segments that haven't changed (e.g. shared layouts) from the [client-side cache](#client-side-caching-of-rendered-server-components). This is also referred to as [partial rendering](/docs/app/building-your-application/routing#partial-rendering).
-- If the [conditions of soft navigation](#conditions-for-soft-navigation) are met, the router fetches the new segment from the cache rather than the server. If not, the router performs a [hard navigation](#hard-navigation) and fetches the Server Component payload from the server.
-- If created, [loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming) is shown from the server while the payload is being fetched.
-- The router uses the cached or fresh payload to render the new segments on the client.
+The App Router uses a hybrid approach for routing and navigation. On the server, your application code is automatically code-split by route segments. And on the client, Next.js [prefetches](#1-prefetching) and [caches](#2-caching) the route segments. This means, when a user navigates to a new route, the browser doesn't reload the page, and only the route segments that change re-render - improving the navigation experience and performance.
-### Client-side Caching of Rendered Server Components
+### 1. Prefetching
-> **Good to know**: This client-side cache is different from the server-side [Next.js HTTP cache](/docs/app/building-your-application/data-fetching#caching-data).
+Prefetching is a way to preload a route in the background before the user visits it.
-The new router has an **in-memory client-side cache** that stores the **rendered result** of Server Components (payload). The cache is split by route segments which allows invalidation at any level and ensures consistency across concurrent renders.
+There are two ways routes are prefetched in Next.js:
-As users navigate around the app, the router will store the payload of previously fetched segments **and** [prefetched](#prefetching) segments in the cache.
+- **`` component**: Routes are automatically prefetched as they become visible in the user's viewport. Prefetching happens when the page first loads or when it comes into view through scrolling.
+- **`router.prefetch()`**: The `useRouter` hook can be used to prefetch routes programmatically.
-This means, for certain cases, the router can re-use the cache instead of making a new request to the server. This improves performance by avoiding re-fetching data and re-rendering components unnecessarily.
+The``'s prefetching behavior is different for static and dynamic routes:
-### Invalidating the Cache
+- [**Static Routes**](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default): `prefetch` defaults to `true`. The entire route is prefetched and cached.
+- [**Dynamic Routes**](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering): `prefetch` default to automatic. Only the shared layout down until the first `loading.js` file is prefetched and cached for `30s`. This reduces the cost of fetching an entire dynamic route, and it means you can show an [instant loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for better visual feedback to users.
-[Server Actions](/docs/app/building-your-application/data-fetching/server-actions) can be used to revalidate data on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)).
+You can disable prefetching by setting the `prefetch` prop to `false`.
-### Prefetching
-
-Prefetching is a way to preload a route in the background before it's visited. The rendered result of prefetched routes is added to the router's client-side cache. This makes navigating to a prefetched route near-instant.
-
-By default, routes are prefetched as they become visible in the viewport when using the `` component. This can happen when the page first loads or through scrolling. Routes can also be programmatically prefetched using the `prefetch` method of the [`useRouter()` hook](/docs/app/api-reference/functions/use-router#userouter).
-
-**Static and Dynamic Routes**:
-
-- If the route is static, all the Server Component payloads for the route segments will be prefetched.
-- If the route is dynamic, the payload from the first shared layout down until the first `loading.js` file is prefetched. This reduces the cost of prefetching the whole route dynamically and allows [instant loading states](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for dynamic routes.
+See the [`` API reference](/docs/app/api-reference/components/link) for more information.
> **Good to know**:
>
-> - Prefetching is only enabled in production.
-> - Prefetching can be disabled by passing `prefetch={false}` to ``.
+> - Prefetching is not enabled in development, only in production.
+
+### 2. Caching
-### Soft Navigation
+Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data#router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#1-prefetching) route segments and visited routes are stored in the cache.
-On navigation, the cache for changed segments is reused (if it exists), and no new requests are made to the server for data.
+This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred.
-#### Conditions for Soft Navigation
+Learn more about how the [Router Cache](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data) works and how to configure it.
-On navigation, Next.js will use soft navigation if the route you are navigating to has been [**prefetched**](#prefetching), and either doesn't include [dynamic segments](/docs/app/building-your-application/routing/dynamic-routes) **or** has the same dynamic parameters as the current route.
+#### 3. Partial Rendering
-For example, consider the following route that includes a dynamic `[team]` segment: `/dashboard/[team]/*`. The cached segments below `/dashboard/[team]/*` will only be invalidated when the `[team]` parameter changes.
+Partial rendering means only the route segments that change on navigation re-render on the client, and any shared segments are preserved.
-- Navigating from `/dashboard/team-red/*` to `/dashboard/team-red/*` will be a soft navigation.
-- Navigating from `/dashboard/team-red/*` to `/dashboard/team-blue/*` will be a hard navigation.
+For example, when navigating between two sibling routes, `/dashboard/settings` and `/dashboard/analytics`, the `settings` and `analytics` pages will be rendered, and the shared `dashboard` layout will be preseved.
-### Hard Navigation
+
-On navigation, the cache is invalidated and the server refetches data and re-renders the changed segments.
+Without partial rendering, each navigation would cause the full page to re-render on the server. Rendering only the segment that changes reduces the amount of data transferred and execution time, leading to improved performance.
-### Back/Forward Navigation
+#### 4. Soft Navigation
-Back and forward navigation ([popstate event](https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event)) has a soft navigation behavior. This means, the client-side cache is re-used and navigation is near-instant.
+By default, the browser performs a hard navigation between pages. This means the browser reloads the page and resets React state such as `useState` hooks in your app and browser state such as the user's scroll position or focused element. However, in Next.js, the App Router uses soft navigation. This means React only renders the segments that have changed while preserving React and browser state, and there is no full page reload.
-### Focus and Scroll Management
+#### 5. Back and Forward Navigation
-By default, Next.js will set focus and scroll into view the segment that's changed on navigation.
+By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data).
diff --git a/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx b/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx
index a8216617c1821..edfef950b0d92 100644
--- a/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx
@@ -15,7 +15,7 @@ When you don't know the exact segment names ahead of time and want to create rou
A Dynamic Segment can be created by wrapping a folder's name in square brackets: `[folderName]`. For example, `[id]` or `[slug]`.
-Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-reference/file-conventions/layout), [`page`](/docs/app/api-reference/file-conventions/page), [`route`](/docs/app/building-your-application/routing/router-handlers), and [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) functions.
+Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-reference/file-conventions/layout), [`page`](/docs/app/api-reference/file-conventions/page), [`route`](/docs/app/building-your-application/routing/route-handlers), and [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) functions.
## Example
@@ -45,7 +45,7 @@ See the [generateStaticParams()](#generating-static-params) page to learn how to
## Generating Static Params
-The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/building-your-application/routing/dynamic-routes) to [**statically generate**](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default) routes at build time instead of on-demand at request time.
+The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/building-your-application/routing/dynamic-routes) to [**statically generate**](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default) routes at build time instead of on-demand at request time.
```tsx filename="app/blog/[slug]/page.tsx" switcher
export async function generateStaticParams() {
@@ -67,7 +67,7 @@ export async function generateStaticParams() {
}
```
-The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically deduplicated](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times.
+The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/building-your-application/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times.
Use the [migration guide](/docs/app/building-your-application/upgrading/app-router-migration#dynamic-paths-getstaticpaths) if you are migrating from the `pages` directory.
diff --git a/docs/02-app/01-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/docs/02-app/01-building-your-application/01-routing/06-loading-ui-and-streaming.mdx
index a70699868d86e..642785ffe7ea3 100644
--- a/docs/02-app/01-building-your-application/01-routing/06-loading-ui-and-streaming.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/06-loading-ui-and-streaming.mdx
@@ -53,7 +53,7 @@ In the same folder, `loading.js` will be nested inside `layout.js`. It will auto
> **Good to know**:
>
-> - Navigation is immediate, even with [server-centric routing](/docs/app/building-your-application/routing#server-centric-routing-with-client-side-navigation).
+> - Navigation is immediate, even with [server-centric routing](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works).
> - Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route.
> - Shared layouts remain interactive while new route segments load.
diff --git a/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx b/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx
index 158da45f5596a..5a551816c2db1 100644
--- a/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx
@@ -103,20 +103,13 @@ Consider the following folder structure. The `@team` slot has a `settings` direc
height="930"
/>
-If you were to navigate from the root `/` to `/settings`, the content that gets rendered is different based on the type of navigation and the availability of the `default.js` file.
+#### Navigation
-| | With `@analytics/default.js` | Without `@analytics/default.js` |
-| --------------- | ---------------------------------------------------- | ------------------------------------------------- |
-| Soft Navigation | `@team/settings/page.js` and `@analytics/page.js` | `@team/settings/page.js` and `@analytics/page.js` |
-| Hard Navigation | `@team/settings/page.js` and `@analytics/default.js` | 404 |
+On navigation, Next.js will render the slot's previously active state, even if it doesn't match the current URL.
-#### Soft Navigation
+#### Reload
-On a [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#soft-navigation) - Next.js will render the slot's previously active state, even if it doesn't match the current URL.
-
-#### Hard Navigation
-
-On a [hard navigation](/docs/app/building-your-application/routing/linking-and-navigating#hard-navigation) - a navigation that requires a full page reload - Next.js will first try to render the unmatched slot's `default.js` file. If that's not available, a 404 gets rendered.
+On reload, Next.js will first try to render the unmatched slot's `default.js` file. If that's not available, a 404 gets rendered.
> The 404 for unmatched routes helps ensure that you don't accidentally render a route that shouldn't be parallel rendered.
diff --git a/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx b/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx
index 9ae0950ce4f88..e7594abf6de69 100644
--- a/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx
@@ -20,7 +20,7 @@ For example, when clicking on a photo from within a feed, a modal overlaying the
height="617"
/>
-However, when navigating to the photo directly by for example when clicking a shareable URL or by refreshing the page, the entire photo page should render instead of the modal. No route interception should occur.
+However, when navigating to the photo by clicking a shareable URL or by refreshing the page, the entire photo page should render instead of the modal. No route interception should occur.
**TypeScript Warning:** Although `Response.json()` is valid, native TypeScript types currently shows an error, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead.
-### Dynamic Route Handlers
+### Opting out of caching
-Route handlers are evaluated dynamically when:
+You can opt out of caching by:
- Using the `Request` object with the `GET` method.
- Using any of the other HTTP methods.
@@ -201,9 +201,9 @@ export async function POST(request) {}
The following examples show how to combine Route Handlers with other Next.js APIs and features.
-### Revalidating Static Data
+### Revalidating Cached Data
-You can [revalidate static data](/docs/app/building-your-application/data-fetching/revalidating) fetches using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching#revalidating-data) option:
+You can [revalidate cached data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) option:
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
@@ -626,7 +626,7 @@ export async function GET(request) {
### Edge and Node.js Runtimes
-Route Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as Pages and Layouts, they support long-awaited features like general-purpose [statically regenerated](/docs/app/building-your-application/data-fetching/revalidating) Route Handlers.
+Route Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as Pages and Layouts, they support long-awaited features like general-purpose [statically regenerated](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) Route Handlers.
You can use the `runtime` segment config option to specify the runtime:
diff --git a/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx
index 03e62d8e69157..755e30c56d788 100644
--- a/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx
@@ -127,7 +127,7 @@ The `NextResponse` API allows you to:
To produce a response from Middleware, you can:
-1. `rewrite` to a route ([Page](/docs/app/building-your-application/routing/pages-and-layouts) or [Route Handler](/docs/app/building-your-application/routing/router-handlers)) that produces a response
+1. `rewrite` to a route ([Page](/docs/app/building-your-application/routing/pages-and-layouts) or [Route Handler](/docs/app/building-your-application/routing/route-handlers)) that produces a response
2. return a `NextResponse` directly. See [Producing a Response](#producing-a-response)
diff --git a/docs/02-app/01-building-your-application/01-routing/index.mdx b/docs/02-app/01-building-your-application/01-routing/index.mdx
index fbab832afa0d9..87b1204b2aa15 100644
--- a/docs/02-app/01-building-your-application/01-routing/index.mdx
+++ b/docs/02-app/01-building-your-application/01-routing/index.mdx
@@ -95,7 +95,7 @@ Next.js provides a set of special files to create UI with specific behavior in n
| [`not-found`](/docs/app/api-reference/file-conventions/not-found) | Not found UI for a segment and its children |
| [`error`](/docs/app/building-your-application/routing/error-handling) | Error UI for a segment and its children |
| [`global-error`](/docs/app/building-your-application/routing/error-handling) | Global Error UI |
-| [`route`](/docs/app/building-your-application/routing/router-handlers) | Server-side API endpoint |
+| [`route`](/docs/app/building-your-application/routing/route-handlers) | Server-side API endpoint |
| [`template`](/docs/app/building-your-application/routing/pages-and-layouts#templates) | Specialized re-rendered Layout UI |
| [`default`](/docs/app/api-reference/file-conventions/default) | Fallback UI for [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) |
@@ -146,30 +146,6 @@ This is because while folders define routes, only the contents returned by `page
Learn more about [Project Organization and Colocation](/docs/app/building-your-application/routing/colocation).
-## Server-Centric Routing with Client-side Navigation
-
-Unlike the `pages` directory which uses client-side routing, the App Router uses **server-centric routing** to align with [Server Components](/docs/getting-started/react-essentials#server-components) and [data fetching on the server](/docs/app/building-your-application/data-fetching/fetching). With server-centric routing, the client does not have to download a route map and the same request for Server Components can be used to look up routes. This optimization is useful for all applications, but has a larger impact on applications with many routes.
-
-Although routing is server-centric, the router uses **client-side navigation** with the [Link Component](/docs/app/building-your-application/routing/linking-and-navigating#link-component) - resembling the behavior of a Single-Page Application. This means when a user navigates to a new route, the browser will not reload the page. Instead, the URL will be updated and Next.js will [only render the segments that change](#partial-rendering).
-
-Additionally, as users navigate around the app, the router will store the result of the React Server Component payload in an **in-memory client-side cache**. The cache is split by route segments which allows invalidation at any level and ensures consistency across [React's concurrent renders](https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react). This means that for certain cases, the cache of a previously fetched segment can be re-used, further improving performance.
-
-Learn more about [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating).
-
-## Partial Rendering
-
-When navigating between sibling routes (e.g. `/dashboard/settings` and `/dashboard/analytics` below), Next.js will only fetch and render the layouts and pages in routes that change. It will **not** re-fetch or re-render anything above the segments in the subtree. This means that in routes that share a layout, the layout will be preserved when a user navigates between sibling pages.
-
-
-
-Without partial rendering, each navigation would cause the full page to re-render on the server. Rendering only the segment that’s updating reduces the amount of data transferred and execution time, leading to improved performance.
-
## Advanced Routing Patterns
The App Router also provides a set of conventions to help you implement more advanced routing patterns. These include:
diff --git a/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx
new file mode 100644
index 0000000000000..3ebf9ecaab742
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx
@@ -0,0 +1,344 @@
+---
+title: Data Fetching, Caching, and Revalidating
+nav_title: Fetching, Caching, and Revalidating
+description: Learn how to fetch, cache, and revalidate data in your Next.js application.
+---
+
+Data fetching is a core part of any application. This page goes through how you can fetch, cache, and revalidate data in React and Next.js.
+
+There are three main ways you can fetch data:
+
+1. On the server, with the `fetch` API.
+2. On the server, with third-party libraries.
+3. On the client, with third-party libraries.
+
+## Fetching Data on the Server with `fetch`
+
+Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree.
+
+You can use `fetch` with [`async`/`await` in Server Components](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises), in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions).
+
+For example:
+
+```tsx filename="app/page.tsx" switcher
+async function getData() {
+ const res = await fetch('https://api.example.com/...')
+ // The return value is *not* serialized
+ // You can return Date, Map, Set, etc.
+
+ if (!res.ok) {
+ // This will activate the closest `error.js` Error Boundary
+ throw new Error('Failed to fetch data')
+ }
+
+ return res.json()
+}
+
+export default async function Page() {
+ const data = await getData()
+
+ return
+}
+```
+
+```jsx filename="app/page.js" switcher
+async function getData() {
+ const res = await fetch('https://api.example.com/...')
+ // The return value is *not* serialized
+ // You can return Date, Map, Set, etc.
+
+ if (!res.ok) {
+ // This will activate the closest `error.js` Error Boundary
+ throw new Error('Failed to fetch data')
+ }
+
+ return res.json()
+}
+
+export default async function Page() {
+ const data = await getData()
+
+ return
+}
+```
+
+> **Good to know**:
+>
+> Next.js provides helpful functions you may need when fetching data in Server Components such as [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers). These will cause the route to be dynamically rendered as they rely on request time information.
+> In Route handlers, `fetch` requests are not memoized as Route Handlers are not part of the React component tree.
+> To use `async`/`await` in a Server Component with TypeScript, you'll need to use TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
+
+### Caching Data
+
+Caching stores data so it doesn't need to be re-fetched from your data source on every request.
+
+By default, Next.js automatically caches the returned values of `fetch` in the [Data Cache](/docs/app/building-your-application/caching#data-cache) on the server. This means that the data can be fetched at build time or request time, cached, and reused on each data request.
+
+```js
+// 'force-cache' is the default, and can be omitted
+fetch('https://...', { cache: 'force-cache' })
+```
+
+`fetch` requests that use the `POST` method are also automatically cached. Unless it's inside a [Route Handler](/docs/app/building-your-application/routing/route-handlers) that uses the `POST` method, then it will not be cached.
+
+> **What is the Data Cache?**
+>
+> The Data Cache is a persistent [HTTP cache](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching). Depending on your platform, the cache can scale automatically and be [shared across multiple regions](https://vercel.com/docs/infrastructure/data-cache).
+>
+> > Learn more about the [Data Cache](/docs/app/building-your-application/caching#data-cache).
+
+### Revalidating Data
+
+Revalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information.
+
+Cached data can be revalidated in two ways:
+
+- **Time-based revalidation**: Automatically revalidate data after a certain amount of time has passed. This is useful for data that changes infrequently and freshness is not as critical.
+- **On-demand revalidation**: Manually revalidate data based on an event (e.g. form submission). On-demand revalidation can use a tag-based or path-based approach to revalidate groups of data at once. This is useful when you want to ensure the latest data is shown as soon as possible (e.g. when content from your headless CMS is updated).
+
+#### Time-based Revalidation
+
+To revalidate data at a timed interval, you can use the `next.revalidate` option of `fetch` to set the cache lifetime of a resource (in seconds).
+
+```js
+fetch('https://...', { next: { revalidate: 3600 } })
+```
+
+Alternatively, to revalidate all `fetch` requests in a route segment, you can use the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config).
+
+```jsx filename="layout.js / page.js"
+export const revalidate = 3600 // revalidate at most every hour
+```
+
+If you have multiple fetch requests in a statically rendered route, and each has a different revalidation frequency. The lowest time will be used for all requests. For dynamically rendered routes, each `fetch` request will be revalidated independently.
+
+Learn more about [time-based revalidation](/docs/app/building-your-application/caching#time-based-revalidation).
+
+#### On-demand Revalidation
+
+Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a Route Handler or a Server Action.
+
+Next.js has a cache tagging system for invalidating `fetch` requests across routes.
+
+1. When using `fetch`, you have the option to tag cache entries with one or more tags.
+2. Then, you can call `revalidateTag` to revalidate all entries associated with that tag.
+
+For example, the following `fetch` request adds the cache tag `collection`:
+
+```tsx filename="app/page.tsx" switcher
+export default async function Page() {
+ const res = await fetch('https://...', { next: { tags: ['collection'] } })
+ const data = await res.json()
+ // ...
+}
+```
+
+```jsx filename="app/page.js" switcher
+export default async function Page() {
+ const res = await fetch('https://...', { next: { tags: ['collection'] } })
+ const data = await res.json()
+ // ...
+}
+```
+
+If using a Route Handler, you should create a secret token only known by your Next.js app. This secret will be used to prevent unauthorized revalidation attempts. For example, you can access the route (either manually or with a webhook) with the following URL structure:
+
+```
+https:///api/revalidate?tag=collection&secret=
+```
+
+```ts filename="app/api/revalidate/route.ts" switcher
+import { NextRequest, NextResponse } from 'next/server'
+import { revalidateTag } from 'next/cache'
+
+// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=`
+export async function GET(request: NextRequest) {
+ // Check for secret to confirm this is a valid request
+ if (
+ request.nextUrl.searchParams.get('secret') !== process.env.MY_SECRET_TOKEN
+ ) {
+ return res.status(401).json({ message: 'Invalid token' })
+ }
+
+ const tag = request.nextUrl.searchParams.get('tag')
+ revalidateTag(tag)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+```js filename="app/api/revalidate/route.js" switcher
+import { NextResponse } from 'next/server'
+import { revalidateTag } from 'next/cache'
+
+// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=`
+export async function GET(request) {
+ // Check for secret to confirm this is a valid request
+ if (
+ request.nextUrl.searchParams.get('secret') !== process.env.MY_SECRET_TOKEN
+ ) {
+ return res.status(401).json({ message: 'Invalid token' })
+ }
+
+ const tag = request.nextUrl.searchParams.get('tag')
+ revalidateTag(tag)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+Alternatively, you can use [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) to revalidate all data associated with a path.
+
+```ts filename="app/api/revalidate/route.ts" switcher
+import { NextRequest, NextResponse } from 'next/server'
+import { revalidatePath } from 'next/cache'
+
+export async function GET(request: NextRequest) {
+ const path = request.nextUrl.searchParams.get('path')
+ revalidatePath(path)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+```js filename="app/api/revalidate/route.js" switcher
+import { NextResponse } from 'next/server'
+import { revalidatePath } from 'next/cache'
+
+export async function GET(request) {
+ const path = request.nextUrl.searchParams.get('path')
+ revalidatePath(path)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+Learn more about [on-demand revalidation](/docs/app/building-your-application/caching#on-demand-revalidation).
+
+#### Error handling and revalidation
+
+If an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data.
+
+### Opting out of Data Caching
+
+`fetch` requests are **not** cached if:
+
+- The `cache: 'no-store` is added to `fetch` requests.
+- The `revalidate: 0` option is added to individual `fetch` requests.
+- The `fetch` request is inside a Router Handler that uses the `POST` method.
+- The `fetch` request comes after the usage of `headers` or `cookies`.
+- The `const dynamic = 'force-dynamic'` route segment option is used.
+- The `fetchCache` route segment option is configured to skip cache by default.
+- The `fetch` request uses `Authorization` or `Cookie` headers and there's an uncached request above it in the component tree.
+
+#### Individiual `fetch` Requests
+
+To opt out of caching for individual `fetch` requests, you can set the `cache` option in `fetch` to `'no-store'`. This will fetch data dynamically, on every request.
+
+```js
+fetch('https://...', { cache: 'no-store' })
+```
+
+View all the available `cache` options in the [`fetch` API reference](/docs/app/api-reference/functions/fetch).
+
+#### Multiple `fetch` Requests
+
+If you have multiple `fetch` requests in a route segment (e.g. a Layout or Page), you can configure the caching behavior of all data requests in the segment using the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config).
+
+For example, using `const dynamic = 'force-dynamic` will cause all data to be fetched at request time, and the segment to be rendered dynamically.
+
+```js filename="layout.js / page.js"
+// Add
+export const dynamic = 'auto'
+```
+
+There's an extensive list of Segment Config options, giving you fine-grained control of static and dynamic behavior of a route segment. See the [API reference](/docs/app/api-reference/file-conventions/route-segment-config) for more.
+
+## Fetching data on the Server with third-party libraries
+
+In cases where you're using a third-party library that doesn't support or expose `fetch` (for example, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the [Route Segment Config Option](/docs/app/api-reference/file-conventions/route-segment-config) and React's `cache` function.
+
+Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered.
+
+> **Good to know:**
+>
+> Next.js is working on an API, `unstable_cache`, for configuring the caching and revalidating behavior of individual third-party requests.
+
+### Example
+
+In the example below:
+
+- The `revalidate` option is set to `3600`, meaning the data will be cached and revalidated at most every hour.
+- The React `cache` function is used to [memoize](/docs/app/building-your-application/caching#request-memoization) data requests.
+
+```ts filename="utils/get-item.ts" switcher
+import { cache } from 'react'
+
+export const revalidate = 3600 // revalidate the data at most every hour
+
+export const getItem = cache(async (id: string) => {
+ const item = await db.item.findUnique({ id })
+ return item
+})
+```
+
+```js filename="utils/get-item.js" switcher
+import { cache } from 'react'
+
+export const revalidate = 3600 // revalidate the data at most every hour
+
+export const getItem = cache(async (id) => {
+ const item = await db.item.findUnique({ id })
+ return item
+})
+```
+
+Although the `getItem` function is called twice, only one query will be made to the database.
+
+```tsx filename="app/item/layout.tsx" switcher
+import { getItem } from '@/utils/get-item'
+
+export default async function Layout({
+ params: { id },
+}: {
+ params: { id: string }
+}) {
+ const item = await getItem(id)
+ // ...
+}
+```
+
+```jsx filename="app/item/layout.js" switcher
+import { getItem } from '@/utils/get-item'
+
+export default async function Layout({ params: { id } }) {
+ const item = await getItem(id)
+ // ...
+}
+```
+
+```tsx filename="app/item/[id]/page.tsx" switcher
+import { getItem } from '@/utils/get-item'
+
+export default async function Page({
+ params: { id },
+}: {
+ params: { id: string }
+}) {
+ const item = await getItem(id)
+ // ...
+}
+```
+
+```jsx filename="app/item/[id]/page.js" switcher
+import { getItem } from '@/utils/get-item'
+
+export default async function Page({ params: { id } }) {
+ const item = await getItem(id)
+ // ...
+}
+```
+
+## Fetching Data on the Client
+
+If you need to fetch data on the client, we recommend using a third-party library such as [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/latest). These libraries provide their own APIs for memoizing requests, caching, revalidating, and mutating data.
+
+> **Future APIs**:
+>
+> `use` is a React function that **accepts and handles a promise** returned by a function. Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. Learn more about `use` in the [React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#usepromise).
diff --git a/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx b/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx
new file mode 100644
index 0000000000000..1456d581a8fce
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx
@@ -0,0 +1,311 @@
+---
+title: Data Fetching Patterns
+nav_title: Patterns
+description: Learn about common data fetching patterns in React and Next.js.
+---
+
+There are a few recommended patterns and best practices for fetching data in React and Next.js. This page will go over some of the most common patterns and how to use them.
+
+### Fetching Data on the Server
+
+Whenever possible, we recommend fetching data on the server. This allows you to:
+
+- Have direct access to backend data resources (e.g. databases).
+- Keep your application more secure by preventing sensitive information, such as access tokens and API keys, from being exposed to the client.
+- Fetch data and render in the same environment. This reduces both the back-and-forth communication between client and server, as well as the [work on the main thread](https://vercel.com/blog/how-react-18-improves-application-performance) on the client.
+- Perform multiple data fetches with single round-trip instead of multiple individual requests on the client.
+- Reduce client-server [waterfalls](#parallel-and-sequential-data-fetching).
+- Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance.
+
+You can fetch data on the server using Server Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions).
+
+### Fetching Data Where It's Needed
+
+If you need to use the same data (e.g. current user) in multiple components in a tree, you do not have to fetch data globally, nor forward props between components. Instead, you can use `fetch` or React `cache` in the component that needs the data without worrying about the performance implications of making multiple requests for the same data.
+
+This is possible because `fetch` requests are automatically memoized. Learn more about [request memoization](/docs/app/building-your-application/caching#request-memoization)
+
+> **Good to know**: This also applies to layouts, since it's not possible to pass data between a parent layout and its children.
+
+### Streaming
+
+Streaming and [Suspense](https://react.dev/reference/react/Suspense) are React features that allow you to progressively render and incrementally stream rendered units of the UI to the client.
+
+With Server Components and [nested layouts](/docs/app/building-your-application/routing/pages-and-layouts), you're able to instantly render parts of the page that do not specifically require data, and show a [loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming) for parts of the page that are fetching data. This means the user does not have to wait for the entire page to load before they can start interacting with it.
+
+
+
+To learn more about Streaming and Suspense, see the [Loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming) and [Streaming and Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) pages.
+
+### Parallel and Sequential Data Fetching
+
+When fetching data inside React components, you need to be aware of two data fetching patterns: Parallel and Sequential.
+
+
+
+- With **sequential data fetching**, requests in a route are dependent on each other and therefore create waterfalls. There may be cases where you want this pattern because one fetch depends on the result of the other, or you want a condition to be satisfied before the next fetch to save resources. However, this behavior can also be unintentional and lead to longer loading times.
+- With **parallel data fetching**, requests in a route are eagerly initiated and will load data at the same time. This reduces client-server waterfalls and the total time it takes to load data.
+
+#### Sequential Data Fetching
+
+If you have nested components, and each component fetches its own data, Then, data fetching will happen sequentially if those data requests are different (this doesn't apply to requests for the same data as they are automatically [memoized](/docs/app/building-your-application/caching#request-memoization)).
+
+For example, the `Playlists` component will only start fetching data once the `Artist` component has finished fetching data because `Playlists` depends on the `artistID` prop:
+
+```tsx filename="app/artist/page.tsx" switcher
+// ...
+
+async function Playlists({ artistID }: { artistID: string }) {
+ // Wait for the playlists
+ const playlists = await getArtistPlaylists(artistID)
+
+ return (
+
+ {playlists.map((playlist) => (
+
{playlist.name}
+ ))}
+
+ )
+}
+
+export default async function Page({
+ params: { username },
+}: {
+ params: { username: string }
+}) {
+ // Wait for the artist
+ const artist = await getArtist(username)
+
+ return (
+ <>
+
+ )
+}
+
+export default async function Page({ params: { username } }) {
+ // Wait for the artist
+ const artist = await getArtist(username)
+
+ return (
+ <>
+
{artist.name}
+ Loading...}>
+
+
+ >
+ )
+}
+```
+
+In cases like this, you can use [`loading.js`](/docs/app/building-your-application/routing/loading-ui-and-streaming) (for route segments) or [React ``](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) (for nested components) to show an instant loading state while React streams in the result.
+
+This will prevent the whole route from being blocked by data fetching, and the user will be able to interact with the parts of the page that are not blocked.
+
+> **Blocking Data Requests:**
+>
+> An alternative approach to prevent waterfalls is to fetch data globally, at the root of your application, but this will block rendering for all route segments beneath it until the data has finished loading. This can be described as "all or nothing" data fetching. Either you have the entire data for your page or application, or none.
+>
+> Any fetch requests with `await` will block rendering and data fetching for the entire tree beneath it, unless they are wrapped in a `` boundary or `loading.js` is used. Another alternative is use [parallel data fetching](#parallel-data-fetching) or the [preload pattern](#preloading-data).
+
+#### Parallel Data Fetching
+
+To fetch data in parallel, you can eagerly initiate requests by defining them outside the components that use the data, then calling them from inside the component. This saves time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved.
+
+In the example below, the `getArtist` and `getArtistAlbums` functions are defined outside the `Page` component, then called inside the component, and we wait for both promises to resolve:
+
+```tsx filename="app/artist/[username]/page.tsx" switcher
+import Albums from './albums'
+
+async function getArtist(username: string) {
+ const res = await fetch(`https://api.example.com/artist/${username}`)
+ return res.json()
+}
+
+async function getArtistAlbums(username: string) {
+ const res = await fetch(`https://api.example.com/artist/${username}/albums`)
+ return res.json()
+}
+
+export default async function Page({
+ params: { username },
+}: {
+ params: { username: string }
+}) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumsData = getArtistAlbums(username)
+
+ // Wait for the promises to resolve
+ const [artist, albums] = await Promise.all([artistData, albumsData])
+
+ return (
+ <>
+
{artist.name}
+
+ >
+ )
+}
+```
+
+```jsx filename="app/artist/[username]/page.js" switcher
+import Albums from './albums'
+
+async function getArtist(username) {
+ const res = await fetch(`https://api.example.com/artist/${username}`)
+ return res.json()
+}
+
+async function getArtistAlbums(username) {
+ const res = await fetch(`https://api.example.com/artist/${username}/albums`)
+ return res.json()
+}
+
+export default async function Page({ params: { username } }) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumsData = getArtistAlbums(username)
+
+ // Wait for the promises to resolve
+ const [artist, albums] = await Promise.all([artistData, albumsData])
+
+ return (
+ <>
+
{artist.name}
+
+ >
+ )
+}
+```
+
+To improve the user experience, you can add a [Suspense Boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming) to break up the rendering work and show part of the result as soon as possible.
+
+### Preloading Data
+
+Another way to prevent waterfalls is to use the preload pattern. You can optionally create a `preload` function to further optimize parallel data fetching. With this approach, you don't have to pass promises down as props. The `preload` function can also have any name as it's a pattern, not an API.
+
+```tsx filename="components/Item.tsx" switcher
+import { getItem } from '@/utils/get-item'
+
+export const preload = (id: string) => {
+ // void evaluates the given expression and returns undefined
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
+ void getItem(id)
+}
+export default async function Item({ id }: { id: string }) {
+ const result = await getItem(id)
+ // ...
+}
+```
+
+```jsx filename="components/Item.js" switcher
+import { getItem } from '@/utils/get-item'
+
+export const preload = (id) => {
+ // void evaluates the given expression and returns undefined
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
+ void getItem(id)
+}
+export default async function Item({ id }) {
+ const result = await getItem(id)
+ // ...
+}
+```
+
+```tsx filename="app/item/[id]/page.tsx" switcher
+import Item, { preload, checkIsAvailable } from '@/components/Item'
+
+export default async function Page({
+ params: { id },
+}: {
+ params: { id: string }
+}) {
+ // starting loading item data
+ preload(id)
+ // perform another asynchronous task
+ const isAvailable = await checkIsAvailable()
+
+ return isAvailable ? : null
+}
+```
+
+```jsx filename="app/item/[id]/page.js" switcher
+import Item, { preload, checkIsAvailable } from '@/components/Item'
+
+export default async function Page({ params: { id } }) {
+ // starting loading item data
+ preload(id)
+ // perform another asynchronous task
+ const isAvailable = await checkIsAvailable()
+
+ return isAvailable ? : null
+}
+```
+
+### Using React `cache`, `server-only`, and the Preload Pattern
+
+You can combine the `cache` function, the `preload` pattern, and the `server-only` package to create a data fetching utility that can be used throughout your app.
+
+```ts filename="utils/get-item.ts" switcher
+import { cache } from 'react'
+import 'server-only'
+
+export const preload = (id: string) => {
+ void getItem(id)
+}
+
+export const getItem = cache(async (id: string) => {
+ // ...
+})
+```
+
+```js filename="utils/get-item.js" switcher
+import { cache } from 'react'
+import 'server-only'
+
+export const preload = (id) => {
+ void getItem(id)
+}
+
+export const getItem = cache(async (id) => {
+ // ...
+})
+```
+
+With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching [only happens on the server](/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning).
+
+The `utils/get-item` exports can be used by Layouts, Pages, or other components to give them control over when an item's data is fetched.
+
+> - We recommend using the [`server-only` package](/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning) to make sure server data fetching functions are never used on the client.
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx b/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx
similarity index 99%
rename from docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx
rename to docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx
index 81e0cd54741aa..05d3afa94291b 100644
--- a/docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx
+++ b/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx
@@ -1,7 +1,7 @@
---
title: Server Actions
nav_title: Server Actions
-description: Use Server Actions to mutate data in your Next.js application.
+description: Learn how to mutate data with Server Actions.
related:
title: Next Steps
description: For more information on what to do next, we recommend the following sections
diff --git a/docs/02-app/01-building-your-application/02-data-fetching/index.mdx b/docs/02-app/01-building-your-application/02-data-fetching/index.mdx
new file mode 100644
index 0000000000000..bc61af8abb696
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-data-fetching/index.mdx
@@ -0,0 +1,4 @@
+---
+title: Data Fetching
+description: Learn how to fetch, cache, revalidate, and mutate of data React and Next.js.
+---
diff --git a/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx b/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx
deleted file mode 100644
index c585856b73865..0000000000000
--- a/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx
+++ /dev/null
@@ -1,56 +0,0 @@
----
-title: Static and Dynamic Rendering
-nav_title: Static and Dynamic
-description: Learn about static and dynamic rendering in Next.js.
----
-
-In Next.js, a route can be statically or dynamically rendered.
-
-- In a **static** route, components are rendered on the server at build time. The result of the work is cached and reused on subsequent requests.
-- In a **dynamic** route, components are rendered on the server at request time.
-
-## Static Rendering (Default)
-
-By default, Next.js statically renders routes to improve performance. This means all the rendering work is done ahead of time and can be served from a Content Delivery Network (CDN) geographically closer to the user.
-
-## Static Data Fetching (Default)
-
-By default, Next.js will cache the result of `fetch()` requests that do not specifically opt out of caching behavior. This means that fetch requests that do not set a `cache` option will use the `force-cache` option.
-
-If any fetch requests in the route use the `revalidate` option, the route will be re-rendered statically during revalidation.
-
-To learn more about caching data fetching requests, see the [Caching and Revalidating](/docs/app/building-your-application/data-fetching/caching) page.
-
-## Dynamic Rendering
-
-During static rendering, if a dynamic function or a dynamic `fetch()` request (no caching) is discovered, Next.js will switch to dynamically rendering the whole route at request time. Any cached data requests can still be re-used during dynamic rendering.
-
-This table summarizes how [dynamic functions](#dynamic-functions) and [caching](#static-data-fetching-default) affect the rendering behavior of a route:
-
-| Data Fetching | Dynamic Functions | Rendering |
-| --------------- | ----------------- | --------- |
-| Static (Cached) | No | Static |
-| Static (Cached) | Yes | Dynamic |
-| Not Cached | No | Dynamic |
-| Not Cached | Yes | Dynamic |
-
-Note how dynamic functions always opt the route into dynamic rendering, regardless of whether the data fetching is cached or not. In other words, static rendering is dependent not only on the data fetching behavior, but also on the dynamic functions used in the route.
-
-> **Good to know**: In the future, Next.js will introduce hybrid server-side rendering where layouts and pages in a route can be independently statically or dynamically rendered, instead of the whole route.
-
-### Dynamic Functions
-
-Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are:
-
-- Using [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) in a Server Component will opt the whole route into dynamic rendering at request time.
-- Using [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) in Client Components will skip static rendering and instead render all Client Components up to the nearest parent Suspense boundary on the client.
- - We recommend wrapping the Client Component that uses `useSearchParams()` in a `` boundary. This will allow any Client Components above it to be statically rendered. [Example](/docs/app/api-reference/functions/use-search-params#static-rendering).
-- Using the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) [Pages](/docs/app/api-reference/file-conventions/page) prop will opt the page into dynamic rendering at request time.
-
-## Dynamic Data Fetching
-
-Dynamic data fetches are `fetch()` requests that specifically opt out of caching behavior by setting the `cache` option to `'no-store'` or `revalidate` to `0`.
-
-The caching options for all `fetch` requests in a layout or page can also be set using the [segment config](/docs/app/api-reference/file-conventions/route-segment-config) object.
-
-To learn more about Dynamic Data Fetching, see the [Data Fetching](/docs/app/building-your-application/data-fetching/fetching) page.
diff --git a/docs/02-app/01-building-your-application/02-rendering/index.mdx b/docs/02-app/01-building-your-application/02-rendering/index.mdx
deleted file mode 100644
index 57b6a830413eb..0000000000000
--- a/docs/02-app/01-building-your-application/02-rendering/index.mdx
+++ /dev/null
@@ -1,73 +0,0 @@
----
-title: Rendering
-description: Learn the differences between Next.js rendering environments, strategies, and runtimes.
----
-
-Rendering converts the code you write into user interfaces.
-
-React 18 and Next.js 13 introduced new ways to render your application. This page will help you understand the differences between rendering environments, strategies, runtimes, and how to opt into them.
-
-## Rendering Environments
-
-There are two environments where your application code can be rendered: the client and the server.
-
-
-
-- The **client** refers to the browser on a user's device that sends a request to a server for your application code. It then turns the response from the server into an interface the user can interact with.
-- The **server** refers to the computer in a data center that stores your application code, receives requests from a client, does some computation, and sends back an appropriate response.
-
-> **Good to know**: Server can refer to computers in regions where your application is deployed to, the [Edge Network](https://vercel.com/docs/concepts/edge-network/overview) where your application code is distributed, or [Content Delivery Networks (CDNs)](https://developer.mozilla.org/en-US/docs/Glossary/CDN) where the result of the rendering work can be cached.
-
-## Component-level Client and Server Rendering
-
-Before React 18, the primary way to render your application **using React** was entirely on the client.
-
-Next.js provided an easier way to break down your application into **pages** and prerender on the server by generating HTML and sending it to the client to be [hydrated](https://react.dev/reference/react-dom/hydrate#hydrating-server-rendered-html) by React. However, this led to additional JavaScript needed on the client to make the initial HTML interactive.
-
-Now, with [Server and Client Components](/docs/getting-started/react-essentials), React can render on the client **and** the server meaning you can choose the rendering environment at the component level.
-
-By default, the [`app` router uses **Server Components**](/docs/getting-started/react-essentials#server-components), allowing you to easily render components on the server and reducing the amount of JavaScript sent to the client.
-
-## Static and Dynamic Rendering on the Server
-
-In addition to client-side and server-side rendering with React components, Next.js gives you the option to optimize rendering on the server with **Static** and **Dynamic** Rendering.
-
-### Static Rendering
-
-With **Static Rendering**, both Server _and_ Client Components can be prerendered on the server at **build time**. The result of the work is [cached](/docs/app/building-your-application/data-fetching/caching) and reused on subsequent requests. The cached result can also be [revalidated](/docs/app/building-your-application/data-fetching#revalidating-data).
-
-> **Good to know**: This is equivalent to [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) and [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/rendering/incremental-static-regeneration) in the [Pages Router](/docs/pages/building-your-application/rendering).
-
-Server and Client Components are rendered differently during Static Rendering:
-
-- Client Components have their HTML and JSON prerendered and cached on the server. The cached result is then sent to the client for hydration.
-- Server Components are rendered on the server by React, and their payload is used to generate HTML. The same rendered payload is also used to hydrate the components on the client, resulting in no JavaScript needed on the client.
-
-### Dynamic Rendering
-
-With Dynamic Rendering, both Server _and_ Client Components are rendered on the server at **request time**. The result of the work is not cached.
-
-> **Good to know**: This is equivalent to [Server-Side Rendering (`getServerSideProps()`)](/docs/pages/building-your-application/rendering/server-side-rendering) in the [Pages Router](/docs/pages/building-your-application/rendering).
-
-To learn more about static and dynamic behavior, see the [Static and Dynamic Rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering) page. To learn more about caching, see the [Caching](/docs/app/building-your-application/data-fetching/caching) sections.
-
-## Edge and Node.js Runtimes
-
-On the server, there are two runtimes where your pages can be rendered:
-
-- The **Node.js Runtime** (default) has access to all Node.js APIs and compatible packages from the ecosystem.
-- The **Edge Runtime** is based on [Web APIs](/docs/app/api-reference/edge).
-
-Both runtimes support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) from the server, depending on your deployment infrastructure.
-
-To learn how to switch between runtimes, see the [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) page.
-
-## Next Steps
-
-Now that you understand the fundamentals of rendering, you can learn more about implementing the different rendering strategies and runtimes:
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx b/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx
deleted file mode 100644
index aa282804f3e7e..0000000000000
--- a/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx
+++ /dev/null
@@ -1,401 +0,0 @@
----
-title: Data Fetching
-nav_title: Fetching
-description: Learn how to fetch data in your Next.js application.
----
-
-The Next.js App Router allows you to fetch data directly in your React components by marking the function as `async` and using `await` for the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
-
-Data fetching is built on top of the [`fetch()` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and React Server Components. When using `fetch()`, requests are [automatically deduped](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) by default.
-
-Next.js extends the `fetch` options object to allow each request to set its own [caching and revalidating](/docs/app/building-your-application/data-fetching/caching).
-
-## `async` and `await` in Server Components
-
-You can use `async` and `await` to fetch data in Server Components.
-
-```tsx filename="app/page.tsx" switcher
-async function getData() {
- const res = await fetch('https://api.example.com/...')
- // The return value is *not* serialized
- // You can return Date, Map, Set, etc.
-
- // Recommendation: handle errors
- if (!res.ok) {
- // This will activate the closest `error.js` Error Boundary
- throw new Error('Failed to fetch data')
- }
-
- return res.json()
-}
-
-export default async function Page() {
- const data = await getData()
-
- return
-}
-```
-
-```jsx filename="app/page.js" switcher
-async function getData() {
- const res = await fetch('https://api.example.com/...')
- // The return value is *not* serialized
- // You can return Date, Map, Set, etc.
-
- // Recommendation: handle errors
- if (!res.ok) {
- // This will activate the closest `error.js` Error Boundary
- throw new Error('Failed to fetch data')
- }
-
- return res.json()
-}
-
-export default async function Page() {
- const data = await getData()
-
- return
-}
-```
-
-> **Good to know**:
->
-> To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
-
-### Server Component Functions
-
-Next.js provides helpful server functions you may need when fetching data in Server Components:
-
-- [`cookies()`](/docs/app/api-reference/functions/cookies)
-- [`headers()`](/docs/app/api-reference/functions/headers)
-
-## `use` in Client Components
-
-`use` is a new React function that **accepts a promise** conceptually similar to `await`. `use` **handles the promise** returned by a function in a way that is compatible with components, hooks, and Suspense. Learn more about `use` in the [React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#usepromise).
-
-Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. For now, if you need to fetch data in a Client Component, we recommend using a third-party library such as [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/v4).
-
-> **Good to know**: We'll be adding more examples once `fetch` and `use` work in Client Components.
-
-## Static Data Fetching
-
-By default, `fetch` will automatically fetch and [cache data](/docs/app/building-your-application/data-fetching/caching) indefinitely.
-
-```ts
-fetch('https://...') // cache: 'force-cache' is the default
-```
-
-### Revalidating Data
-
-To revalidate [cached data](/docs/app/building-your-application/data-fetching/caching) at a timed interval, you can use the `next.revalidate` option in `fetch()` to set the `cache` lifetime of a resource (in seconds).
-
-```ts
-fetch('https://...', { next: { revalidate: 10 } })
-```
-
-See [Revalidating Data](/docs/app/building-your-application/data-fetching/revalidating) for more information.
-
-> **Good to know**:
->
-> Caching at the fetch level with `revalidate` or `cache: 'force-cache'` stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from `cookies()` or `headers()`)
-
-## Dynamic Data Fetching
-
-To fetch fresh data on every `fetch` request, use the `cache: 'no-store'` option.
-
-```ts
-fetch('https://...', { cache: 'no-store' })
-```
-
-## Data Fetching Patterns
-
-### Parallel Data Fetching
-
-To minimize client-server waterfalls, we recommend this pattern to fetch data in parallel:
-
-```tsx filename="app/artist/[username]/page.tsx" switcher
-import Albums from './albums'
-
-async function getArtist(username: string) {
- const res = await fetch(`https://api.example.com/artist/${username}`)
- return res.json()
-}
-
-async function getArtistAlbums(username: string) {
- const res = await fetch(`https://api.example.com/artist/${username}/albums`)
- return res.json()
-}
-
-export default async function Page({
- params: { username },
-}: {
- params: { username: string }
-}) {
- // Initiate both requests in parallel
- const artistData = getArtist(username)
- const albumsData = getArtistAlbums(username)
-
- // Wait for the promises to resolve
- const [artist, albums] = await Promise.all([artistData, albumsData])
-
- return (
- <>
-
{artist.name}
-
- >
- )
-}
-```
-
-```jsx filename="app/artist/[username]/page.js" switcher
-import Albums from './albums'
-
-async function getArtist(username) {
- const res = await fetch(`https://api.example.com/artist/${username}`)
- return res.json()
-}
-
-async function getArtistAlbums(username) {
- const res = await fetch(`https://api.example.com/artist/${username}/albums`)
- return res.json()
-}
-
-export default async function Page({ params: { username } }) {
- // Initiate both requests in parallel
- const artistData = getArtist(username)
- const albumsData = getArtistAlbums(username)
-
- // Wait for the promises to resolve
- const [artist, albums] = await Promise.all([artistData, albumsData])
-
- return (
- <>
-
{artist.name}
-
- >
- )
-}
-```
-
-By starting the fetch prior to calling `await` in the Server Component, each request can eagerly start to fetch requests at the same time. This sets the components up so you can avoid waterfalls.
-
-We can save time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved.
-
-To improve the user experience, you can add a [suspense boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming) to break up the rendering work and show part of the result as soon as possible:
-
-```tsx filename="artist/[username]/page.tsx" switcher
-import { getArtist, getArtistAlbums, type Album } from './api'
-
-export default async function Page({
- params: { username },
-}: {
- params: { username: string }
-}) {
- // Initiate both requests in parallel
- const artistData = getArtist(username)
- const albumData = getArtistAlbums(username)
-
- // Wait for the artist's promise to resolve first
- const artist = await artistData
-
- return (
- <>
-
{artist.name}
- {/* Send the artist information first,
- and wrap albums in a suspense boundary */}
- Loading...}>
-
-
- >
- )
-}
-
-// Albums Component
-async function Albums({ promise }: { promise: Promise }) {
- // Wait for the albums promise to resolve
- const albums = await promise
-
- return (
-
- {albums.map((album) => (
-
{album.name}
- ))}
-
- )
-}
-```
-
-```jsx filename="artist/[username]/page.js" switcher
-import { getArtist, getArtistAlbums } from './api'
-
-export default async function Page({ params: { username } }) {
- // Initiate both requests in parallel
- const artistData = getArtist(username)
- const albumData = getArtistAlbums(username)
-
- // Wait for the artist's promise to resolve first
- const artist = await artistData
-
- return (
- <>
-
{artist.name}
- {/* Send the artist information first,
- and wrap albums in a suspense boundary */}
- Loading...}>
-
-
- >
- )
-}
-
-// Albums Component
-async function Albums({ promise }) {
- // Wait for the albums promise to resolve
- const albums = await promise
-
- return (
-
- {albums.map((album) => (
-
{album.name}
- ))}
-
- )
-}
-```
-
-Take a look at the [preloading pattern](/docs/app/building-your-application/data-fetching/caching#preload-pattern-with-cache) for more information on improving components structure.
-
-### Sequential Data Fetching
-
-To fetch data sequentially, you can `fetch` directly inside the component that needs it, or you can `await` the result of `fetch` inside the component that needs it:
-
-```tsx filename="app/artist/page.tsx" switcher
-// ...
-
-async function Playlists({ artistID }: { artistID: string }) {
- // Wait for the playlists
- const playlists = await getArtistPlaylists(artistID)
-
- return (
-
- {playlists.map((playlist) => (
-
{playlist.name}
- ))}
-
- )
-}
-
-export default async function Page({
- params: { username },
-}: {
- params: { username: string }
-}) {
- // Wait for the artist
- const artist = await getArtist(username)
-
- return (
- <>
-