Unverified Commit 98c3076e authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

Docs: Document caching mechanisms (#52514)

This PR document the caching semantics in Next.js, how they interact, and what APIs affect them. We're also taking the opportunity to consolidate terminology, remove duplicate content, and update sections of the docs that relate to caching. 

### Documentation

- [x] Create a new section for caching
- [x] Explain how the different caching mechanisms work
   - [x] Request Memoization (React Cache)
   - [x] Persistent Data Cache 
   - [x] Persistent Full Route Cache 
   - [x] In-memory, client-side Router Cache 
- [x] Document how different APIs affect caching
- [x] Document cache interactions 
- [x] Clean up stale information in the other docs sections
   - [x] Routing Section
      - [x] Move advanced navigation topics from fundamentals to **How Navigation Works** section
      - [x] Rewrite the **How Navigation Works** section
   - [x] Rendering Section
      - [x] Simplify fundamentals page
      - [x] Rewrite the **Static and Dynamic Rendering** pages
      - [ ] ~Create a page to explain how **Client and Server Components** are rendered~. Moved to this PR: https://github.com/vercel/next.js/pull/51579
   - [x] Data fetching section 
      - [x] Consolidate data fetching story for fetching, caching, and revalidating
      - [x] Clarify data fetching story with 3rd party libraries and React `cache`
      - [x] Create **Data Fetching Patterns** page
- [x] Document other related behaviors: 
   - [x] Update information on scroll position for back/forward navigation 
   - [x] Remove the concepts of **soft and hard navigation**
   - [x] Remove the concepts of **static and dynamic data fetching**
   - [x] Use consistent terminology **runtime** 👉🏼  **request time**. Runtime for Edge and Node.js, request time to describe when dynamic stuff happens
   - [x] `generateStaticParams` being able to seed the Full Route Cache
- [x] Polish 💅🏼 

---
### Related PRs:

- Diagrams: https://github.com/vercel/front/pull/24142
- Redirects: https://github.com/vercel/front/pull/24179
parent 35e16f75
......@@ -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.
......@@ -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.
......
......@@ -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.
......
......@@ -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.
......
......@@ -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.
......
......@@ -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.
<Image
alt="Intercepting routes hard navigation"
......
......@@ -45,9 +45,9 @@ In addition to supporting native [Request](https://developer.mozilla.org/en-US/d
## Behavior
### Static Route Handlers
### Caching
Route Handlers are [statically evaluated](/docs/app/building-your-application/data-fetching#static-and-dynamic-data-fetching) by default when using the `GET` method with the `Response` object.
Route Handlers are cached by default when using the `GET` method with the `Response` object.
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
......@@ -83,9 +83,9 @@ export async function GET() {
> **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:
......
......@@ -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)
</AppOnly>
......
......@@ -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.
<Image
alt="How partial rendering works"
srcLight="/docs/light/partial-rendering.png"
srcDark="/docs/dark/partial-rendering.png"
width="1600"
height="945"
/>
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:
......
---
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
......
---
title: Data Fetching
description: Learn how to fetch, cache, revalidate, and mutate of data React and Next.js.
---
---
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 `<Suspense/>` 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.
---
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.
<Image
alt="Client and Server Environments"
srcLight="/docs/light/client-and-server-environments.png"
srcDark="/docs/dark/client-and-server-environments.png"
width="1600"
height="672"
/>
- 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:
---
title: Revalidating Data
nav_title: Revalidating
description: Learn about revalidating data in Next.js using Incremental Static Regeneration.
---
Next.js allows you to update specific static routes **without needing to rebuild your entire site**. Revalidation (also known as [Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)) allows you to retain the benefits of static while scaling to millions of pages.
There are two types of revalidation in Next.js:
- **Background**: Revalidates the data at a specific time interval.
- **On-demand**: Revalidates the data based on an event such as an update.
## Background Revalidation
To revalidate cached data at a specific interval, you can use the `next.revalidate` option in `fetch()` to set the `cache` lifetime of a resource (in seconds).
```js
fetch('https://...', { next: { revalidate: 60 } })
```
If you want to revalidate data that does not use `fetch` (i.e. using an external package or query builder), you can use the [route segment config](/docs/app/api-reference/file-conventions/route-segment-config#revalidate).
```tsx filename="app/page.tsx" switcher
export const revalidate = 60 // revalidate this page every 60 seconds
```
```jsx filename="app/page.js" switcher
export const revalidate = 60 // revalidate this page every 60 seconds
```
In addition to `fetch`, you can also revalidate data using [`cache`](/docs/app/building-your-application/data-fetching/caching#per-request-caching).
### How it works
1. When a request is made to the route that was statically rendered at build time, it will initially show the cached data.
2. Any requests to the route after the initial request and before 60 seconds are also cached and instantaneous.
3. After the 60-second window, the next request will still show the cached (stale) data.
4. Next.js will trigger a regeneration of the data in the background.
5. Once the route generates successfully, Next.js will invalidate the cache and show the updated route. If the background regeneration fails, the old data would still be unaltered.
When a request is made to a route segment that hasn’t been generated, Next.js will dynamically render the route on the first request. Future requests will serve the static route segments from the cache.
> **Good to know**: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. `useCdn: false`), otherwise a revalidation won't be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the `Cache-Control` header. ISR on Vercel [persists the cache globally and handles rollbacks](https://vercel.com/docs/concepts/incremental-static-regeneration/overview).
## On-demand Revalidation
If you set a `revalidate` time of `60`, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is if someone visits the page after the minute has passed.
The Next.js App Router supports revalidating content on-demand based on a route or cache tag. This allows you to manually purge the Next.js cache for specific fetches, making it easier to update your site when:
- Content from your headless CMS is created or updated.
- Ecommerce metadata changes (price, description, category, reviews, etc).
### Using 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)).
For example, the following `fetch` 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()
// ...
}
```
This cached data can then be revalidated on-demand by calling `revalidateTag` in a [Route Handler](/docs/app/building-your-application/routing/router-handlers).
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request: NextRequest) {
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'
export async function GET(request) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
```
## 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.
---
title: Static and Dynamic Rendering
nav_title: Static and Dynamic
description: Learn about static and dynamic rendering in Next.js.
related:
description: Learn how Next.js caches data and the result of static rendering.
links:
- app/building-your-application/caching
---
In Next.js, a route can be statically or dynamically rendered.
## Static Rendering (Default)
By default, Next.js statically renders routes to improve performance. At **build time**, Server and Client components are rendered on the server, and the result of the work is [cached](/docs/app/building-your-application/caching#full-route-cache) and reused on subsequent requests.
> To understand how Client and Server Components are rendered, see the [Rendering Client and Server Components](/docs/app/building-your-application/rendering/server-and-client-components) page.
## Dynamic Rendering
With Dynamic Rendering, both Server _and_ Client Components for a route are rendered on the server at **request time**.
During rendering, if a [dynamic function](#dynamic-functions) or uncached data request is discovered, Next.js will switch to dynamically rendering the whole route. This table summarizes how dynamic functions and data caching affect whether a route is statically or dynamically rendered:
| Route | Dynamic Functions | Data |
| -------------------- | ----------------- | ---------- |
| Statically Rendered | No | Cached |
| Dynamically Rendered | Yes | Cached |
| Dynamic Rendered | No | Not Cached |
| Dynamic Rendered | Yes | Not Cached |
From the table above, for a route to be fully static, all data must be cached. However, you can have a dynamically rendered route that uses both cached and uncached data fetches. This is useful when you have a page that mostly re-uses cached data, but has some uncached data. It allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time.
> **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:
- **[`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers)**: Using these in a Server Component will opt the whole route into dynamic rendering at request time.
- **[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params)**:
- In Client Components, it'll 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 `<Suspense/>` boundary. This will allow any Client Components above it to be statically rendered. [Example](/docs/app/api-reference/functions/use-search-params#static-rendering).
- **[`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)**: Using the [Pages](/docs/app/api-reference/file-conventions/page) prop will opt the page into dynamic rendering at request time.
---
title: Rendering Client and Server Components
nav_title: Client and Server Components
description: Learn how Server and Client Components are rendered in Next.js.
---
This page is currently being worked on. Follow its progress and give feedback on [GitHub](https://github.com/vercel/next.js/pull/51579).
......@@ -5,14 +5,12 @@ description: Learn about the switchable runtimes (Edge and Node.js) in Next.js.
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
In the context of Next.js, "runtime" refers to the set of libraries, APIs, and general functionality available to your code during execution.
In the context of Next.js, runtime refers to the set of libraries, APIs, and general functionality available to your code during execution.
Next.js has two server runtimes where you can render parts of your application code:
On the server, there are two runtimes where parts of your application code can be rendered:
- [Node.js Runtime](#nodejs-runtime)
- [Edge Runtime](#edge-runtime)
Each runtime has its own set of APIs. Please refer to the [Node.js Docs](https://nodejs.org/docs/latest/api/) and [Edge Docs](/docs/app/api-reference/edge) for the full list of available APIs. Both runtimes can also support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) depending on your deployment infrastructure.
- 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).
By default, the `app` directory uses the Node.js runtime. However, you can opt into different runtimes (e.g. Edge) on a per-route basis.
......@@ -81,3 +79,5 @@ export const runtime = 'edge' // 'nodejs' (default) | 'edge'
If the segment runtime is _not_ set, the default `nodejs` runtime will be used. You do not need to use the `runtime` option if you do not plan to change from the Node.js runtime.
</AppOnly>
> Please refer to the [Node.js Docs](https://nodejs.org/docs/latest/api/) and [Edge Docs](/docs/app/api-reference/edge) for the full list of available APIs. Both runtimes can also support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) depending on your deployment infrastructure.
---
title: Rendering
description: Learn the differences between Next.js rendering environments, strategies, and runtimes.
---
Rendering converts the code you write into user interfaces. This section will help you understand the differences between rendering environments, Client and Server Component rendering, static and dynamic rendering, and runtimes.
## Background
There are two environments where web applications can be rendered: the client and the server.
<Image
alt="Client and Server Environments"
srcLight="/docs/light/client-and-server-environments.png"
srcDark="/docs/dark/client-and-server-environments.png"
width="1600"
height="672"
/>
- 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.
Before React 18, the primary way to render your application was entirely on the client. Next.js provided an easier way to break down your application into **pages** and render on the server.
Now, with Server and Client Components, **React renders on the client and the server**, meaning you can choose where to render your application code, per component.
By default, the App Router uses Server Components to improve performance, and you can opt into using Client Components when needed.
Learn more about rendering by exploring the sections below:
This diff is collapsed.
......@@ -106,7 +106,7 @@ For all the available params, see the [API Reference](/docs/app/api-reference/fu
> **Good to know**:
>
> - Both static and dynamic metadata through `generateMetadata` are **only supported in Server Components**.
> - When rendering a route, Next.js will [automatically deduplicate `fetch` requests](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/data-fetching/caching#react-cache) if `fetch` is unavailable.
> - `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable.
> - Next.js will wait for data fetching inside `generateMetadata` to complete before streaming UI to the client. This guarantees the first part of a [streamed response](/docs/app/building-your-application/routing/loading-ui-and-streaming) includes `<head>` tags.
## File-based metadata
......@@ -281,7 +281,7 @@ export async function GET() {
}
```
`ImageResponse` integrates well with other Next.js APIs, including [Route Handlers](/docs/app/building-your-application/routing/router-handlers) and file-based Metadata. For example, you can use `ImageResponse` in a `opengraph-image.tsx` file to generate Open Graph images at build time or dynamically at request time.
`ImageResponse` integrates well with other Next.js APIs, including [Route Handlers](/docs/app/building-your-application/routing/route-handlers) and file-based Metadata. For example, you can use `ImageResponse` in a `opengraph-image.tsx` file to generate Open Graph images at build time or dynamically at request time.
`ImageResponse` supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. [See the full list of supported CSS properties](/docs/app/api-reference/functions/image-response).
......
......@@ -32,4 +32,4 @@ For static metadata files, such as `robots.txt`, `favicon.ico`, etc, you should
> Good to know:
>
> - The directory must be named `public`. The name cannot be changed and it's the only directory used to serve static assets.
> - Only assets that are in the `public` directory at [build time](/docs/app/api-reference/next-cli#build) will be served by Next.js. Files added at runtime won't be available. We recommend using a third-party service like [AWS S3](https://aws.amazon.com/s3/) for persistent file storage.
> - Only assets that are in the `public` directory at [build time](/docs/app/api-reference/next-cli#build) will be served by Next.js. Files added at request time won't be available. We recommend using a third-party service like [AWS S3](https://aws.amazon.com/s3/) for persistent file storage.
......@@ -131,9 +131,9 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) {
Next.js 13 has **enhanced type safety**. This includes:
1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types.
2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching) in Next.js 13, this is no longer an issue.
2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) in Next.js 13, this is no longer an issue.
[Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.
[Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.
We're able to type the response data as you would expect with normal TypeScript. For example:
......
......@@ -48,7 +48,7 @@ export async function getStaticProps() {
<AppOnly>
This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Route Handlers](/docs/app/building-your-application/routing/router-handlers).
This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Route Handlers](/docs/app/building-your-application/routing/route-handlers).
For example:
......
......@@ -3,13 +3,13 @@ title: Draft Mode
description: Next.js has draft mode to toggle between static and dynamic pages. You can learn how it works with App Router here.
---
Static rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to switch to [dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering) only for this specific case.
Static rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to switch to [dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering only for this specific case.
Next.js has a feature called **Draft Mode** which solves this problem. Here are instructions on how to use it.
## Step 1: Create and access the Route Handler
First, create a [Route Handler](/docs/app/building-your-application/routing/router-handlers). It can have any name - e.g. `app/api/draft/route.ts`
First, create a [Route Handler](/docs/app/building-your-application/routing/route-handlers). It can have any name - e.g. `app/api/draft/route.ts`
Then, import `draftMode` from `next/headers` and call the `enable()` method.
......
......@@ -68,7 +68,7 @@ export default async function Page() {
### Client Components
If you want to perform data fetching on the client, you can use a Client Component with [SWR](https://github.com/vercel/swr) to deduplicate requests.
If you want to perform data fetching on the client, you can use a Client Component with [SWR](https://github.com/vercel/swr) to memoize requests.
```tsx filename="app/other/page.tsx" switcher
'use client'
......@@ -232,7 +232,7 @@ export default function Page() {
### Route Handlers
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from dynamic or static data. For example:
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. For example:
```ts filename="app/data.json/route.ts" switcher
import { NextResponse } from 'next/server'
......@@ -293,7 +293,7 @@ The following additional dynamic features are not supported with a static export
- `redirects` in `next.config.js`
- `headers` in `next.config.js`
- Middleware
- [Incremental Static Regeneration](/docs/app/building-your-application/data-fetching/revalidating)
- [Incremental Static Regeneration](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating)
</AppOnly>
......
......@@ -384,7 +384,7 @@ export default function HomePage({ recentPosts }) {
- Create a new `app/page.tsx` file inside the `app` directory. This is a Server Component by default.
- Import the `home-page.tsx` Client Component into the page.
- If you were fetching data in `pages/index.js`, move the data fetching logic directly into the Server Component using the new [data fetching APIs](/docs/app/building-your-application/data-fetching/fetching). See the [data fetching upgrade guide](#step-6-migrating-data-fetching-methods) for more details.
- If you were fetching data in `pages/index.js`, move the data fetching logic directly into the Server Component using the new [data fetching APIs](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). See the [data fetching upgrade guide](#step-6-migrating-data-fetching-methods) for more details.
```tsx filename="app/page.tsx" switcher
// Import your Client Component
......@@ -472,7 +472,7 @@ In addition, the new `useRouter` hook has the following changes:
- The `locale`, `locales`, `defaultLocales`, `domainLocales` values have been removed because built-in i18n Next.js features are no longer necessary in the `app` directory. [Learn more about i18n](/docs/pages/building-your-application/routing/internationalization).
- `basePath` has been removed. The alternative will not be part of `useRouter`. It has not yet been implemented.
- `asPath` has been removed because the concept of `as` has been removed from the new router.
- `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/building-your-application/rendering#static-rendering), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-params) hook will skip the prerendering step and instead be rendered on the client at runtime.
- `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-params) hook will skip the prerendering step and instead be rendered on the client at runtime.
[View the `useRouter()` API reference](/docs/app/api-reference/functions/use-router).
......@@ -549,7 +549,7 @@ export default function Dashboard({ projects }) {
In the `app` directory, we can colocate our data fetching inside our React components using [Server Components](/docs/getting-started/react-essentials#server-components). This allows us to send less JavaScript to the client, while maintaining the rendered HTML from the server.
By setting the `cache` option to `no-store`, we can indicate that the fetched data should [never be cached](/docs/app/building-your-application/data-fetching/caching). This is similar to `getServerSideProps` in the `pages` directory.
By setting the `cache` option to `no-store`, we can indicate that the fetched data should [never be cached](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating. This is similar to `getServerSideProps` in the `pages` directory.
```tsx filename="app/dashboard/page.tsx" switcher
// `app` directory
......@@ -808,11 +808,11 @@ export default async function Post({ params }) {
}
```
With [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) set to `true` (the default), when a route segment is requested that hasn't been generated, it will be server-rendered and cached as [static data](/docs/app/building-your-application/data-fetching#static-and-dynamic-data-fetching) on success.
With [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) set to `true` (the default), when a route segment is requested that hasn't been generated, it will be server-rendered and cached.
#### Incremental Static Regeneration (`getStaticProps` with `revalidate`)
In the `pages` directory, the `getStaticProps` function allows you to add a `revalidate` field to automatically regenerate a page after a certain amount of time. This is called [Incremental Static Regeneration (ISR)](/docs/app/building-your-application/data-fetching/fetching#static-data-fetching) and helps you update static content without redeploying.
In the `pages` directory, the `getStaticProps` function allows you to add a `revalidate` field to automatically regenerate a page after a certain amount of time.
```jsx filename="pages/index.js"
// `pages` directory
......@@ -857,7 +857,7 @@ export default async function PostList() {
#### API Routes
API Routes continue to work in the `pages/api` directory without any changes. However, they have been replaced by [Route Handlers](/docs/app/building-your-application/routing/router-handlers) in the `app` directory.
API Routes continue to work in the `pages/api` directory without any changes. However, they have been replaced by [Route Handlers](/docs/app/building-your-application/routing/route-handlers) in the `app` directory.
Route Handlers allow you to create custom request handlers for a given route using the Web [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) APIs.
......@@ -869,7 +869,7 @@ export async function GET(request: Request) {}
export async function GET(request) {}
```
> **Good to know**: If you previously used API routes to call an external API from the client, you can now use [Server Components](/docs/getting-started/react-essentials#server-components) instead to securely fetch data. Learn more about [data fetching](/docs/app/building-your-application/data-fetching/fetching).
> **Good to know**: If you previously used API routes to call an external API from the client, you can now use [Server Components](/docs/getting-started/react-essentials#server-components) instead to securely fetch data. Learn more about [data fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating).
### Step 7: Styling
......
......@@ -13,7 +13,7 @@ description: Enable fast client-side navigation with the built-in `next/link` co
</details>
`<Link>` is a React component that extends the HTML `<a>` element to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
`<Link>` is a React component that extends the HTML `<a>` element to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#1-prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
<AppOnly>
......
......@@ -172,7 +172,7 @@ export default function Icon() {
> **Good to know**
>
> - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) or [dynamic data fetching](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-data-fetching).
> - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) or uncached data.
> - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
> - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead.
......@@ -256,7 +256,7 @@ export default function Icon() {}
#### Route Segment Config
`icon` and `apple-icon` are specialized [Route Handlers](/docs/app/building-your-application/routing/router-handlers) that can use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) options as Pages and Layouts.
`icon` and `apple-icon` are specialized [Route Handlers](/docs/app/building-your-application/routing/route-handlers) that can use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) options as Pages and Layouts.
| Option | Type | Default |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------- |
......
......@@ -84,7 +84,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi
> **Good to know**
>
> - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) or [dynamic data fetching](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-data-fetching).
> - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) or uncached data.
> - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/server`.
......@@ -311,7 +311,7 @@ export default function Image() {}
#### Route Segment Config
`opengraph-image` and `twitter-image` are specialized [Route Handlers](/docs/app/building-your-application/routing/router-handlers) that can use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) options as Pages and Layouts.
`opengraph-image` and `twitter-image` are specialized [Route Handlers](/docs/app/building-your-application/routing/route-handlers) that can use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) options as Pages and Layouts.
| Option | Type | Default |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------- |
......@@ -339,7 +339,7 @@ export default function Image() {}
This example uses the `params` object and external data to generate the image.
> **Good to know**:
> By default, this generated image will be [statically optimized](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
> By default, this generated image will be [statically optimized](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/server'
......
......@@ -92,9 +92,9 @@ export default function ShopLayout({ children, params }) {
## Good to know
### Layout's do not receive `searchParams`
### Layouts do not receive `searchParams`
Unlike [Pages](/docs/app/api-reference/file-conventions/page), Layout components **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing#partial-rendering) which could lead to stale `searchParams` between navigations.
Unlike [Pages](/docs/app/api-reference/file-conventions/page), Layout components **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing/linking-and-navigating#3-partial-rendering) which could lead to stale `searchParams` between navigations.
When using client-side navigation, Next.js automatically only renders the part of the page below the common layout between two routes.
......
......@@ -47,7 +47,7 @@ An object containing the [search parameters](https://developer.mozilla.org/en-US
> **Good to know**:
>
> - `searchParams` is a **[Dynamic API](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering)** at request time.
> - `searchParams` is a **[Dynamic API](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering)** at request time.
> - `searchParams` returns a plain JavaScript object and not a `URLSearchParams` instance.
## Version History
......
......@@ -3,7 +3,7 @@ title: Route Segment Config
description: Learn about how to configure options for Next.js route segments.
---
The Route Segment options allows you configure the behavior of a [Page](/docs/app/building-your-application/routing/pages-and-layouts), [Layout](/docs/app/building-your-application/routing/pages-and-layouts), or [Route Handler](/docs/app/building-your-application/routing/router-handlers) by directly exporting the following variables:
The Route Segment options allows you configure the behavior of a [Page](/docs/app/building-your-application/routing/pages-and-layouts), [Layout](/docs/app/building-your-application/routing/pages-and-layouts), or [Route Handler](/docs/app/building-your-application/routing/route-handlers) by directly exporting the following variables:
| Option | Type | Default |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
......@@ -62,18 +62,18 @@ export const dynamic = 'auto'
> **Good to know**: The new model in the `app` directory favors granular caching control at the `fetch` request level over the binary all-or-nothing model of `getServerSideProps` and `getStaticProps` at the page-level in the `pages` directory. The `dynamic` option is a way to opt back in to the previous model as a convenience and provides a simpler migration path.
- **`'auto'`** (default): The default option to cache as much as possible without preventing any components from opting into dynamic behavior.
- **`'force-dynamic'`**: Force dynamic rendering and dynamic data fetching of a layout or page by disabling all caching of `fetch` requests and always revalidating. This option is equivalent to:
- **`'force-dynamic'`**: Force dynamic rendering and uncached data fetching of a layout or page by disabling all caching of `fetch` requests and always revalidating. This option is equivalent to:
- `getServerSideProps()` in the `pages` directory.
- Setting the option of every `fetch()` request in a layout or page to `{ cache: 'no-store', next: { revalidate: 0 } }`.
- Setting the segment config to `export const fetchCache = 'force-no-store'`
- **`'error'`**: Force static rendering and static data fetching of a layout or page by causing an error if any components use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) or [dynamic fetches](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-data-fetching). This option is equivalent to:
- **`'error'`**: Force static rendering and cache the data of a layout or page by causing an error if any components use [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) or uncached data. This option is equivalent to:
- `getStaticProps()` in the `pages` directory.
- Setting the option of every `fetch()` request in a layout or page to `{ cache: 'force-cache' }`.
- Setting the segment config to `fetchCache = 'only-cache', dynamicParams = false`.
- `dynamic = 'error'` changes the default of `dynamicParams` from `true` to `false`. You can opt back into dynamically rendering pages for dynamic params not generated by `generateStaticParams` by manually setting `dynamicParams = true`.
- **`'force-static'`**: Force static rendering and static data fetching of a layout or page by forcing [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers) and [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) to return empty values.
- **`'force-static'`**: Force static rendering and cache the data of a layout or page by forcing [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers) and [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) to return empty values.
> **Good to know**:
>
......@@ -114,8 +114,8 @@ export const revalidate = false
// false | 'force-cache' | 0 | number
```
- **`false`**: (default) The default heuristic to cache any `fetch` requests that set their `cache` option to `'force-cache'` or are discovered before a [dynamic function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) is used. Semantically equivalent to `revalidate: Infinity` which effectively means the resource should be cached indefinitely. It is still possible for individual `fetch` requests to use `cache: 'no-store'` or `revalidate: 0` to avoid being cached and make the route dynamically rendered. Or set `revalidate` to a positive number lower than the route default to increase the revalidation frequency of a route.
- **`0`**: Ensure a layout or page is always [dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering) even if no dynamic functions or dynamic data fetches are discovered. This option changes the default of `fetch` requests that do not set a `cache` option to `'no-store'` but leaves `fetch` requests that opt into `'force-cache'` or use a positive `revalidate` as is.
- **`false`**: (default) The default heuristic to cache any `fetch` requests that set their `cache` option to `'force-cache'` or are discovered before a [dynamic function](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) is used. Semantically equivalent to `revalidate: Infinity` which effectively means the resource should be cached indefinitely. It is still possible for individual `fetch` requests to use `cache: 'no-store'` or `revalidate: 0` to avoid being cached and make the route dynamically rendered. Or set `revalidate` to a positive number lower than the route default to increase the revalidation frequency of a route.
- **`0`**: Ensure a layout or page is always [dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering) even if no dynamic functions or uncached data fetches are discovered. This option changes the default of `fetch` requests that do not set a `cache` option to `'no-store'` but leaves `fetch` requests that opt into `'force-cache'` or use a positive `revalidate` as is.
- **`number`**: (in seconds) Set the default revalidation frequency of a layout or page to `n` seconds.
#### Revalidation Frequency
......@@ -128,7 +128,7 @@ export const revalidate = false
<details>
<summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary>
By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) are used and **will not cache** `fetch` requests that are discovered **after** dynamic functions are used.
By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any [dynamic functions](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) are used and **will not cache** `fetch` requests that are discovered **after** dynamic functions are used.
`fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page.
......
......@@ -8,9 +8,9 @@ related:
- app/building-your-application/data-fetching/server-actions
---
The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/getting-started/react-essentials) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).
The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/getting-started/react-essentials) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
> **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering)** at request time.
> **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering)** at request time.
## `cookies().get(name)`
......@@ -62,7 +62,7 @@ export default function Page() {
A method that takes a cookie name, value, and options and sets the outgoing request cookie.
> **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).
> **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
```js filename="app/actions.js"
'use server'
......@@ -87,7 +87,7 @@ async function create(data) {
To "delete" a cookie, you must set a new cookie with the same name and an empty value. You can also set the `maxAge` to `0` to expire the cookie immediately.
> **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).
> **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
```js filename="app/actions.js"
'use server'
......
......@@ -59,20 +59,20 @@ Further, Next.js polyfills `fetch` on both the client and the server, so you can
### `options.cache`
Configure how the request should interact with Next.js HTTP cache.
Configure how the request should interact with Next.js [Data Cache](/docs/app/building-your-application/caching#data-cache).
```ts
fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
```
- **`force-cache`** (default) - Next.js looks for a matching request in its HTTP cache.
- **`force-cache`** (default) - Next.js looks for a matching request in its Data Cache.
- If there is a match and it is fresh, it will be returned from the cache.
- If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.
- **`no-store`** - Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource.
> **Good to know**:
>
> - If you don't provide a `cache` option, Next.js will default to `force-cache`, unless a [dynamic function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions) such as `cookies()` is used, in which case it will default to `no-store`.
> - If you don't provide a `cache` option, Next.js will default to `force-cache`, unless a [dynamic function](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) such as `cookies()` is used, in which case it will default to `no-store`.
> - The `no-cache` option behaves the same way as `no-store` in Next.js.
### `options.next.revalidate`
......@@ -83,7 +83,7 @@ fetch(`https://...`, { next: { revalidate: false | 0 | number } })
Set the cache lifetime of a resource (in seconds).
- **`false`** - Cache the resource indefinitely. Semantically equivalent to `revalidate: Infinity`. The [HTTP cache](/docs/app/building-your-application/data-fetching#caching-data) may evict older resources over time.
- **`false`** - Cache the resource indefinitely. Semantically equivalent to `revalidate: Infinity`. The HTTP cache may evict older resources over time.
- **`0`** - Prevent the resource from being cached.
- **`number`** - (in seconds) Specify the resource should have a cache lifetime of at most `n` seconds.
......
......@@ -162,7 +162,7 @@ export default function Page({ params, searchParams }) {}
> **Good to know**:
>
> - If metadata doesn't depend on runtime information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`.
> - When rendering a route, Next.js will [automatically deduplicate `fetch` requests](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/data-fetching/caching#react-cache) if `fetch` is unavailable.
> - `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable.
> - `searchParams` are only available in `page.js` segments.
> - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`.
......
......@@ -3,7 +3,7 @@ title: generateStaticParams
description: API reference for the generateStaticParams function.
---
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.
```jsx filename="app/blog/[slug]/page.js"
// Return a list of `params` to populate the [slug] dynamic segment
......@@ -299,7 +299,7 @@ export default function Page({ params }) {
}
```
> **Good to know**: When rendering a route, Next.js will [automatically deduplicate `fetch` requests](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/data-fetching/caching#react-cache) if `fetch` is unavailable.
> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable.
## Version History
......
......@@ -33,7 +33,7 @@ export default function Page() {
> **Good to know**:
>
> - `headers()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering)** at request time.
> - `headers()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering)** at request time.
### API Reference
......@@ -60,7 +60,7 @@ const headersList = headers()
#### Usage with Data Fetching
`headers()` can be used in combination with [Suspense for Data Fetching](/docs/app/building-your-application/data-fetching/fetching).
`headers()` can be used in combination with [Suspense for Data Fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating).
```jsx filename="app/page.js"
import { headers } from 'next/headers'
......
......@@ -3,7 +3,7 @@ title: redirect
description: API Reference for the redirect function.
---
The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/router-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions).
The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions).
If you need to redirect to a 404, use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead.
......
......@@ -10,7 +10,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path') || '/'
const path = request.nextUrl.searchParams.get('path')
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
......@@ -21,7 +21,7 @@ import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET(request) {
const path = request.nextUrl.searchParams.get('path') || '/'
const path = request.nextUrl.searchParams.get('path')
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
......
......@@ -44,14 +44,13 @@ export default function Page() {
- `router.push(href: string)`: Perform a client-side navigation to the provided route. Adds a new entry into the [browser’s history](https://developer.mozilla.org/en-US/docs/Web/API/History_API) stack.
- `router.replace(href: string)`: Perform a client-side navigation to the provided route without adding a new entry into the [browser’s history stack](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
- `router.refresh()`: Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. `useState`) or browser state (e.g. scroll position).
- `router.prefetch(href: string)`: [Prefetch](/docs/app/building-your-application/routing/linking-and-navigating#prefetching) the provided route for faster client-side transitions.
- `router.back()`: Navigate back to the previous route in the browser’s history stack using [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#soft-navigation).
- `router.forward()`: Navigate forwards to the next page in the browser’s history stack using [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#soft-navigation).
- `router.prefetch(href: string)`: [Prefetch](/docs/app/building-your-application/routing/linking-and-navigating#1-prefetching) the provided route for faster client-side transitions.
- `router.back()`: Navigate back to the previous route in the browser’s history stack.
- `router.forward()`: Navigate forwards to the next page in the browser’s history stack.
> **Good to know**:
>
> - The `push()` and `replace()` methods will perform a [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#soft-navigation) if the new route has been prefetched, 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.
> - `next/link` automatically prefetch routes as they become visible in the viewport.
> - The `<Link>` component automatically prefetch routes as they become visible in the viewport.
> - `refresh()` could re-produce the same result if fetch requests are cached. Other dynamic functions like `cookies` and `headers` could also change the response.
> **Migrating from the `pages` directory:**
......@@ -111,7 +110,7 @@ export default function Layout({ children }) {
}
```
> **Good to know**: `<NavigationEvents>` is wrapped in a [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior).
> **Good to know**: `<NavigationEvents>` is wrapped in a [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior).
| Version | Changes |
| --------- | ---------------------------------------------- |
......
......@@ -71,14 +71,14 @@ const searchParams = useSearchParams()
> **Good to know**:
>
> - `useSearchParams` is a [Client Component](/docs/getting-started/react-essentials) hook and is **not supported** in [Server Components](/docs/getting-started/react-essentials) to prevent stale values during [partial rendering](/docs/app/building-your-application/routing#partial-rendering).
> - `useSearchParams` is a [Client Component](/docs/getting-started/react-essentials) hook and is **not supported** in [Server Components](/docs/getting-started/react-essentials) to prevent stale values during [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#3-partial-rendering).
> - If an application includes the `/pages` directory, `useSearchParams` will return `ReadonlyURLSearchParams | null`. The `null` value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use `getServerSideProps`
## Behavior
### Static Rendering
If a route is [statically rendered](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default), calling `useSearchParams()` will cause the tree up to the closest [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) to be client-side rendered.
If a route is [statically rendered](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default), calling `useSearchParams()` will cause the tree up to the closest [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) to be client-side rendered.
This allows a part of the page to be statically rendered while the dynamic part that uses `searchParams` is client-side rendered.
......@@ -172,7 +172,7 @@ export default function Page() {
### Dynamic Rendering
If a route is [dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
If a route is [dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
> **Good to know**: Setting the [`dynamic` route segment config option](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) to `force-dynamic` can be used to force dynamic rendering.
......@@ -256,7 +256,7 @@ To access search params in [Pages](/docs/app/api-reference/file-conventions/page
#### Layouts
Unlike Pages, [Layouts](/docs/app/api-reference/file-conventions/layout) (Server Components) **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing#partial-rendering) which could lead to stale `searchParams` between navigations. View [detailed explanation](/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams).
Unlike Pages, [Layouts](/docs/app/api-reference/file-conventions/layout) (Server Components) **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing/linking-and-navigating#3-partial-rendering) which could lead to stale `searchParams` between navigations. View [detailed explanation](/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams).
Instead, use the Page [`searchParams`](/docs/app/api-reference/file-conventions/page) prop or the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook in a Client Component, which is re-rendered on the client with the latest `searchParams`.
......
......@@ -3,7 +3,7 @@ title: incrementalCacheHandlerPath
description: Configure the Next.js cache used for storing and revalidating data.
---
In Next.js, the [default cache handler](/docs/app/building-your-application/data-fetching/caching) uses the filesystem cache. This requires no configuration, however, you can customize the cache handler by using the `incrementalCacheHandlerPath` field in `next.config.js`.
In Next.js, the [default cache handler](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating uses the filesystem cache. This requires no configuration, however, you can customize the cache handler by using the `incrementalCacheHandlerPath` field in `next.config.js`.
```js filename="next.config.js"
module.exports = {
......@@ -64,4 +64,4 @@ Returns `Promise<void>`.
| --------- | -------- | ---------------------------- |
| `tag` | `string` | The cache tag to revalidate. |
Returns `Promise<void>`. Learn more about [revalidating data](/docs/app/building-your-application/data-fetching/revalidating) or the [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) function.
Returns `Promise<void>`. Learn more about [revalidating data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) or the [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) function.
......@@ -3,7 +3,7 @@ title: serverComponentsExternalPackages
description: Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.
---
Dependencies used inside [Server Components](/docs/getting-started/react-essentials#server-components) and [Route Handlers](/docs/app/building-your-application/routing/router-handlers) will automatically be bundled by Next.js.
Dependencies used inside [Server Components](/docs/getting-started/react-essentials#server-components) and [Route Handlers](/docs/app/building-your-application/routing/route-handlers) will automatically be bundled by Next.js.
If a dependency is using Node.js specific features, you can choose to opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.
......
......@@ -16,7 +16,7 @@ description: Next.js supports API Routes, which allow you to build your API with
<PagesOnly>
> **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/building-your-application/data-fetching/fetching) or [Route Handlers](/docs/app/building-your-application/routing/router-handlers) instead of API Routes.
> **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead of API Routes.
</PagesOnly>
......
......@@ -15,9 +15,9 @@ To resolve this issue, you have two main options:
1. Use the `next build` command instead of `next export` if you're deploying your application on platforms that don't require `next export`. For example, [Vercel](https://vercel.com) is a popular hosting platform for Next.js applications that supports this feature.
2. If you still need to use `next export`, make sure to remove any paths that use API routes from your `exportPathMap` in your `next.config.js` file.
3. Consider [incrementally adopting the App Router](/docs/app/building-your-application/upgrading/app-router-migration), which supportes [Route Handlers](/docs/app/building-your-application/routing/router-handlers). These "API Routes" can be used to create endpoints that can be statically exported in your application.
3. Consider [incrementally adopting the App Router](/docs/app/building-your-application/upgrading/app-router-migration), which supportes [Route Handlers](/docs/app/building-your-application/routing/route-handlers). These "API Routes" can be used to create endpoints that can be statically exported in your application.
## Useful Links
- [Static HTML export](/docs/pages/building-your-application/deploying/static-exports) - Learn more about how you can create a static HTML export of your Next.js application.
- [Route Handlers](/docs/app/building-your-application/routing/router-handlers) - Learn more about how you can use Route Handlers to create endpoints that can be statically exported in your application.
- [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - Learn more about how you can use Route Handlers to create endpoints that can be statically exported in your application.
......@@ -19,5 +19,5 @@ To resolve this issue, you have two main options:
## Useful Links
- [Static and Dynamic Rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering) - Learn more about the differences between static and dynamic rendering in Next.js.
- [Dynamic Functions](/docs/app/building-your-application/data-fetching/fetching#server-component-functions) - Understand more about the usage of dynamic server functions in your Next.js application.
- [Static and Dynamic Rendering](/docs/app/building-your-application/rendering/static-and-dynamic) - Learn more about the differences between static and dynamic rendering in Next.js.
- [Dynamic Functions](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-functions) - Understand more about the usage of dynamic server functions in your Next.js application.
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