diff --git a/docs/01-getting-started/03-react-essentials.mdx b/docs/01-getting-started/03-react-essentials.mdx deleted file mode 100644 index 563181c0f7..0000000000 --- a/docs/01-getting-started/03-react-essentials.mdx +++ /dev/null @@ -1,863 +0,0 @@ ---- -title: React Essentials -description: An overview of essential React features for building Next.js Applications, including Server Components. ---- - -To build applications with Next.js, it helps to be familiar with React's newer features such as Server Components. This page will go through the differences between Server and Client Components, when to use them, and recommended patterns. - -If you're new to React, we also recommend referring to the [React Docs](https://react.dev/learn). Here are some great resources for learning: - -- [React Tutorial](https://react.dev/learn/tutorial-tic-tac-toe) -- [Thinking in React](https://react.dev/learn/thinking-in-react) -- [Learn React](https://react.dev/learn/describing-the-ui) - -## Server Components - -Server and Client Components allow developers to build applications that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering. - -### 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. - -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. - -For example, consider a [page](/docs/app/building-your-application/routing/pages-and-layouts#pages) in your application: - -Thinking in Server Components - -If we were to split the page into smaller components, you'll notice that the majority of components are non-interactive and can be rendered on the server as Server Components. For smaller pieces of interactive UI, we can _sprinkle in_ Client Components. This aligns with Next.js server-first approach. - -### Why Server Components? - -So, you may be thinking, why Server Components? What are the advantages of using them over Client Components? - -Server Components allow developers to better leverage server infrastructure. For example, you can move data fetching to the server, closer to your database, and keep large dependencies that previously would impact the client JavaScript bundle size on the server, leading to improved performance. Server Components make writing a React application feel similar to PHP or Ruby on Rails, but with the power and flexibility of React and the components model for templating UI. - -With Server Components, the initial page load is faster, and the client-side JavaScript bundle size is reduced. The base client-side runtime is **cacheable** and **predictable** in size, and does _not_ increase as your application grows. Additional JavaScript is _only added_ as client-side interactivity is used in your application through [Client Components](#client-components). - -When a route is loaded with Next.js, the initial HTML is rendered on the server. This HTML is then **progressively enhanced** in the browser, allowing the client to take over the application and add interactivity, by asynchronously loading the Next.js and React client-side runtime. - -To make the transition to Server Components easier, all components inside the [App Router](/docs/app/building-your-application/routing#the-app-router) are Server Components by default, including [special files](/docs/app/building-your-application/routing#file-conventions) and [colocated components](/docs/app/building-your-application/routing#colocation). This allows you to automatically adopt them with no extra work, and achieve great performance out of the box. You can also optionally opt-in to Client Components using the ['use client' directive](#the-use-client-directive). - -## 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) 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 - -The [`"use client"` directive](https://github.com/reactjs/rfcs/pull/227) is a convention to declare a boundary between a Server and Client Component module graph. - -```tsx filename="app/counter.tsx" highlight={1} switcher -'use client' - -import { useState } from 'react' - -export default function Counter() { - const [count, setCount] = useState(0) - - return ( -
-

You clicked {count} times

- -
- ) -} -``` - -```jsx filename="app/counter.js" highlight={1} switcher -'use client' - -import { useState } from 'react' - -export default function Counter() { - const [count, setCount] = useState(0) - - return ( -
-

You clicked {count} times

- -
- ) -} -``` - -Use Client Directive and Network Boundary - -`"use client"` _sits_ between server-only and client code. It's placed at the top of a file, above imports, to define the _cut-off_ point where it crosses the boundary from the server-only to the client part. Once `"use client"` is defined in a file, all other modules imported into it, including child components, are considered part of the client bundle. - -Since Server Components are the default, all components are part of the Server Component module graph unless defined or imported in a module that starts with the `"use client"` directive. - -> **Good to know**: -> -> - Components in the Server Component module graph are guaranteed to be only rendered on the server. -> - Components in the Client Component module graph are primarily rendered on the client, but with Next.js, they can also be pre-rendered on the server and hydrated on the client. -> - The `"use client"` directive must be defined at the **top of a file** before any imports. -> - `"use client"` does **not** need to be defined in every file. The Client module boundary only needs to be defined once, at the "entry point", for all modules imported into it to be considered a Client Component. - -## When to use Server and Client Components? - -To simplify the decision between Server and Client Components, we recommend using Server Components (default in the `app` directory) until you have a use case for a Client Component. - -This table summarizes the different use cases for Server and Client Components: - -| What do you need to do? | Server Component | Client Component | -| ---------------------------------------------------------------------------------- | ------------------- | ------------------- | -| Fetch data. | | | -| Access backend resources (directly) | | | -| Keep sensitive information on the server (access tokens, API keys, etc) | | | -| Keep large dependencies on the server / Reduce client-side JavaScript | | | -| Add interactivity and event listeners (`onClick()`, `onChange()`, etc) | | | -| Use State and Lifecycle Effects (`useState()`, `useReducer()`, `useEffect()`, etc) | | | -| Use browser-only APIs | | | -| Use custom hooks that depend on state, effects, or browser-only APIs | | | -| Use [React Class components](https://react.dev/reference/react/Component) | | | - -## Patterns - -### Moving Client Components to the Leaves - -To improve the performance of your application, we recommend moving Client Components to the leaves of your component tree where possible. - -For example, you may have a Layout that has static elements (e.g. logo, links, etc) and an interactive search bar that uses state. - -Instead of making the whole layout a Client Component, move the interactive logic to a Client Component (e.g. ``) and keep your layout as a Server Component. This means you don't have to send all the component Javascript of the layout to the client. - -```tsx filename="app/layout.tsx" switcher -// SearchBar is a Client Component -import SearchBar from './searchbar' -// Logo is a Server Component -import Logo from './logo' - -// Layout is a Server Component by default -export default function Layout({ children }: { children: React.ReactNode }) { - return ( - <> - -
{children}
- - ) -} -``` - -```jsx filename="app/layout.js" switcher -// SearchBar is a Client Component -import SearchBar from './searchbar' -// Logo is a Server Component -import Logo from './logo' - -// Layout is a Server Component by default -export default function Layout({ children }) { - return ( - <> - -
{children}
- - ) -} -``` - -### Composing Client and Server Components - -Server and Client Components can be combined in the same component tree. - -Behind the scenes, React handles rendering as follows: - -- On the server, React renders **all** Server Components **before** sending the result to the client. - - This includes Server Components nested inside Client Components. - - Client Components encountered during this stage are skipped. -- 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) to produce a faster initial page load. - -### Nesting Server Components inside Client Components - -Given the rendering flow outlined above, there is a restriction around importing a Server Component into a Client Component, as this approach would require an additional server round trip. - -#### Unsupported Pattern: Importing Server Components into Client Components - -The following pattern is not supported. You cannot import a Server Component into a Client Component: - -```tsx filename="app/example-client-component.tsx" switcher highlight={5,18} -'use client' - -// This pattern will **not** work! -// You cannot import a Server Component into a Client Component. -import ExampleServerComponent from './example-server-component' - -export default function ExampleClientComponent({ - children, -}: { - children: React.ReactNode -}) { - const [count, setCount] = useState(0) - - return ( - <> - - - - - ) -} -``` - -```jsx filename="app/example-client-component.js" switcher highlight={5,14} -'use client' - -// This pattern will **not** work! -// You cannot import a Server Component into a Client Component. -import ExampleServerComponent from './example-server-component' - -export default function ExampleClientComponent({ children }) { - const [count, setCount] = useState(0) - - return ( - <> - - - - - ) -} -``` - -#### Recommended Pattern: Passing Server Components to Client Components as Props - -Instead, when designing Client Components you can use React props to mark _"slots"_ for Server Components. - -The Server Component will be rendered on the server, and when the Client Component is rendered on the client, the _"slot"_ will be filled in with the rendered result of the Server Component. - -A common pattern is to use the React `children` prop to create the _"slot"_. We can refactor `` to accept a generic `children` prop and move the import and explicit nesting of `` up to a parent component. - -```tsx filename="app/example-client-component.tsx" switcher highlight={6,16} -'use client' - -import { useState } from 'react' - -export default function ExampleClientComponent({ - children, -}: { - children: React.ReactNode -}) { - const [count, setCount] = useState(0) - - return ( - <> - - - {children} - - ) -} -``` - -```jsx filename="app/example-client-component.js" switcher highlight={5,12} -'use client' - -import { useState } from 'react' - -export default function ExampleClientComponent({ children }) { - const [count, setCount] = useState(0) - - return ( - <> - - - {children} - - ) -} -``` - -Now, `` has no knowledge of what `children` is. It doesn't know that `children` will eventually be filled in by the result of a Server Component. - -The only responsibility `ExampleClientComponent` has is to decide where whatever `children` will eventually be placed. - -In a parent Server Component, you can import both the `` and `` and pass `` as a child of ``: - -```tsx filename="app/page.tsx" highlight={11} switcher -// This pattern works: -// You can pass a Server Component as a child or prop of a -// Client Component. -import ExampleClientComponent from './example-client-component' -import ExampleServerComponent from './example-server-component' - -// Pages in Next.js are Server Components by default -export default function Page() { - return ( - - - - ) -} -``` - -```jsx filename="app/page.js" highlight={11} switcher -// This pattern works: -// You can pass a Server Component as a child or prop of a -// Client Component. -import ExampleClientComponent from './example-client-component' -import ExampleServerComponent from './example-server-component' - -// Pages in Next.js are Server Components by default -export default function Page() { - return ( - - - - ) -} -``` - -With this approach, the rendering of `` and `` are decoupled and can be rendered independently - aligning with Server Components, which are rendered on the server before Client Components. - -> **Good to know** -> -> - This pattern is **already applied** in [layouts and pages](/docs/app/building-your-application/routing/pages-and-layouts) with the `children` prop so you don't have to create an additional wrapper component. -> - Passing React components (JSX) to other components is not a new concept and has always been part of the React composition model. -> - This composition strategy works across Server and Client Components because the component that receives the prop can choose where to place the prop, but has no knowledge of **what** the prop is. -> - This allows the passed prop to be rendered independently, in this case, on the server, well before the Client Component is rendered on the client. -> - The very same strategy of "lifting content up" has been used to avoid state changes in a parent component re-rendering an imported nested child component. -> - You're not limited to the `children` prop. You can use any prop to pass JSX. - -### Passing props from Server to Client Components (Serialization) - -Props passed from the Server to Client Components need to be [serializable](https://developer.mozilla.org/en-US/docs/Glossary/Serialization). This means that values such as functions, Dates, etc, cannot be passed directly to Client Components. - -> **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/patterns#fetching-data-on-the-server) with Server Components. - -### Keeping Server-Only Code out of Client Components (Poisoning) - -Since JavaScript modules can be shared between both Server and Client Components, it's possible for code that was only ever intended to be run on the server to sneak its way into the client. - -For example, take the following data-fetching function: - -```ts filename="lib/data.ts" switcher -export async function getData() { - const res = await fetch('https://external-service.com/data', { - headers: { - authorization: process.env.API_KEY, - }, - }) - - return res.json() -} -``` - -```js filename="lib/data.js" switcher -export async function getData() { - const res = await fetch('https://external-service.com/data', { - headers: { - authorization: process.env.API_KEY, - }, - }) - - return res.json() -} -``` - -At first glance, it appears that `getData` works on both the server and the client. But because the environment variable `API_KEY` is not prefixed with `NEXT_PUBLIC`, it's a private variable that can only be accessed on the server. Next.js replaces private environment variables with the empty string in client code to prevent leaking secure information. - -As a result, even though `getData()` can be imported and executed on the client, it won't work as expected. And while making the variable public would make the function work on the client, it would leak sensitive information. - -So, this function was written with the intention that it would only ever be executed on the server. - -### The "server only" package - -To prevent this sort of unintended client usage of server code, we can use the `server-only` package to give other developers a build-time error if they ever accidentally import one of these modules into a Client Component. - -To use `server-only`, first install the package: - -```bash filename="Terminal" -npm install server-only -``` - -Then import the package into any module that contains server-only code: - -```js filename="lib/data.js" -import 'server-only' - -export async function getData() { - const res = await fetch('https://external-service.com/data', { - headers: { - authorization: process.env.API_KEY, - }, - }) - - return res.json() -} -``` - -Now, any Client Component that imports `getData()` will receive a build-time error explaining that this module can only be used on the server. - -The corresponding package `client-only` can be used to mark modules that contain client-only code – for example, code that accesses the `window` object. - -### Data Fetching - -Although it's possible to fetch data in Client Components, we recommend fetching data in Server Components unless you have a specific reason for fetching data on the client. Moving data fetching to the server leads to better performance and user experience. - -[Learn more about data fetching](/docs/app/building-your-application/data-fetching). - -### Third-party packages - -Since Server Components are new, third-party packages in the ecosystem are just beginning to add the `"use client"` directive to components that use client-only features like `useState`, `useEffect`, and `createContext`. - -Today, many components from `npm` packages that use client-only features do not yet have the directive. These third-party components will work as expected within your own [Client Components](#the-use-client-directive) since they have the `"use client"` directive, but they won't work within Server Components. - -For example, let's say you've installed the hypothetical `acme-carousel` package which has a `` component. This component uses `useState`, but it doesn't yet have the `"use client"` directive. - -If you use `` within a Client Component, it will work as expected: - -```tsx filename="app/gallery.tsx" switcher -'use client' - -import { useState } from 'react' -import { Carousel } from 'acme-carousel' - -export default function Gallery() { - let [isOpen, setIsOpen] = useState(false) - - return ( -
- - - {/* Works, since Carousel is used within a Client Component */} - {isOpen && } -
- ) -} -``` - -```jsx filename="app/gallery.js" switcher -'use client' - -import { useState } from 'react' -import { Carousel } from 'acme-carousel' - -export default function Gallery() { - let [isOpen, setIsOpen] = useState(false) - - return ( -
- - - {/* Works, since Carousel is used within a Client Component */} - {isOpen && } -
- ) -} -``` - -However, if you try to use it directly within a Server Component, you'll see an error: - -```tsx filename="app/page.tsx" switcher -import { Carousel } from 'acme-carousel' - -export default function Page() { - return ( -
-

View pictures

- - {/* Error: `useState` can not be used within Server Components */} - -
- ) -} -``` - -```jsx filename="app/page.js" switcher -import { Carousel } from 'acme-carousel' - -export default function Page() { - return ( -
-

View pictures

- - {/* Error: `useState` can not be used within Server Components */} - -
- ) -} -``` - -This is because Next.js doesn't know `` is using client-only features. - -To fix this, you can wrap third-party components that rely on client-only features in your own Client Components: - -```tsx filename="app/carousel.tsx" switcher -'use client' - -import { Carousel } from 'acme-carousel' - -export default Carousel -``` - -```jsx filename="app/carousel.js" switcher -'use client' - -import { Carousel } from 'acme-carousel' - -export default Carousel -``` - -Now, you can use `` directly within a Server Component: - -```tsx filename="app/page.tsx" switcher -import Carousel from './carousel' - -export default function Page() { - return ( -
-

View pictures

- - {/* Works, since Carousel is a Client Component */} - -
- ) -} -``` - -```jsx filename="app/page.js" switcher -import Carousel from './carousel' - -export default function Page() { - return ( -
-

View pictures

- - {/* Works, since Carousel is a Client Component */} - -
- ) -} -``` - -We don't expect you to need to wrap most third-party components since it's likely you'll be using them within Client Components. However, one exception is provider components, since they rely on React state and context, and are typically needed at the root of an application. [Learn more about third-party context providers below](#rendering-third-party-context-providers-in-server-components). - -#### Library Authors - -- In a similar fashion, library authors creating packages to be consumed by other developers can use the `"use client"` directive to mark client entry points of their package. This allows users of the package to import package components directly into their Server Components without having to create a wrapping boundary. -- You can optimize your package by using ['use client' deeper in the tree](#moving-client-components-to-the-leaves), allowing the imported modules to be part of the Server Component module graph. -- It's worth noting some bundlers might strip out `"use client"` directives. You can find an example of how to configure esbuild to include the `"use client"` directive in the [React Wrap Balancer](https://github.com/shuding/react-wrap-balancer/blob/main/tsup.config.ts#L10-L13) and [Vercel Analytics](https://github.com/vercel/analytics/blob/main/packages/web/tsup.config.js#L26-L30) repositories. - -## Context - -Most React applications rely on [context](https://react.dev/reference/react/useContext) to share data between components, either directly via [`createContext`](https://react.dev/reference/react/useContext), or indirectly via provider components imported from third-party libraries. - -In Next.js 13, context is fully supported within Client Components, but it **cannot** be created or consumed directly within Server Components. This is because Server Components have no React state (since they're not interactive), and context is primarily used for rerendering interactive components deep in the tree after some React state has been updated. - -We'll discuss alternatives for sharing data between Server Components, but first, let's take a look at how to use context within Client Components. - -### Using context in Client Components - -All of the context APIs are fully supported within Client Components: - -```tsx filename="app/sidebar.tsx" switcher -'use client' - -import { createContext, useContext, useState } from 'react' - -const SidebarContext = createContext() - -export function Sidebar() { - const [isOpen, setIsOpen] = useState() - - return ( - - - - ) -} - -function SidebarNav() { - let { isOpen } = useContext(SidebarContext) - - return ( -
-

Home

- - {isOpen && } -
- ) -} -``` - -```jsx filename="app/sidebar.js" switcher -'use client' - -import { createContext, useContext, useState } from 'react' - -const SidebarContext = createContext() - -export function Sidebar() { - const [isOpen, setIsOpen] = useState() - - return ( - - - - ) -} - -function SidebarNav() { - let { isOpen } = useContext(SidebarContext) - - return ( -
-

Home

- - {isOpen && } -
- ) -} -``` - -However, context providers are typically rendered near the root of an application to share global concerns, like the current theme. Because context is not supported in Server Components, trying to create a context at the root of your application will cause an error: - -```tsx filename="app/layout.tsx" switcher -import { createContext } from 'react' - -// createContext is not supported in Server Components -export const ThemeContext = createContext({}) - -export default function RootLayout({ children }) { - return ( - - - {children} - - - ) -} -``` - -```jsx filename="app/layout.js" switcher -import { createContext } from 'react' - -// createContext is not supported in Server Components -export const ThemeContext = createContext({}) - -export default function RootLayout({ children }) { - return ( - - - {children} - - - ) -} -``` - -To fix this, create your context and render its provider inside of a Client Component: - -```tsx filename="app/theme-provider.tsx" switcher -'use client' - -import { createContext } from 'react' - -export const ThemeContext = createContext({}) - -export default function ThemeProvider({ children }) { - return {children} -} -``` - -```jsx filename="app/theme-provider.js" switcher -'use client' - -import { createContext } from 'react' - -export const ThemeContext = createContext({}) - -export default function ThemeProvider({ children }) { - return {children} -} -``` - -Your Server Component will now be able to directly render your provider since it's been marked as a Client Component: - -```tsx filename="app/layout.tsx" switcher -import ThemeProvider from './theme-provider' - -export default function RootLayout({ - children, -}: { - children: React.ReactNode -}) { - return ( - - - {children} - - - ) -} -``` - -```jsx filename="app/layout.js" switcher -import ThemeProvider from './theme-provider' - -export default function RootLayout({ children }) { - return ( - - - {children} - - - ) -} -``` - -With the provider rendered at the root, all other Client Components throughout your app will be able to consume this context. - -> **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `` document. This makes it easier for Next.js to optimize the static parts of your Server Components. - -### Rendering third-party context providers in Server Components - -Third-party npm packages often include Providers that need to be rendered near the root of your application. If these providers include the `"use client"` directive, they can be rendered directly inside of your Server Components. However, since Server Components are so new, many third-party providers won't have added the directive yet. - -If you try to render a third-party provider that doesn't have `"use client"`, it will cause an error: - -```tsx filename="app/layout.tsx" switcher -import { ThemeProvider } from 'acme-theme' - -export default function RootLayout({ children }) { - return ( - - - {/* Error: `createContext` can't be used in Server Components */} - {children} - - - ) -} -``` - -```jsx filename="app/layout.js" switcher -import { ThemeProvider } from 'acme-theme' - -export default function RootLayout({ children }) { - return ( - - - {/* Error: `createContext` can't be used in Server Components */} - {children} - - - ) -} -``` - -To fix this, wrap third-party providers in your own Client Component: - -```jsx filename="app/providers.js" -'use client' - -import { ThemeProvider } from 'acme-theme' -import { AuthProvider } from 'acme-auth' - -export function Providers({ children }) { - return ( - - {children} - - ) -} -``` - -Now, you can import and render `` directly within your root layout. - -```jsx filename="app/layout.js" -import { Providers } from './providers' - -export default function RootLayout({ children }) { - return ( - - - {children} - - - ) -} -``` - -With the providers rendered at the root, all the components and hooks from these libraries will work as expected within your own Client Components. - -Once a third-party library has added `"use client"` to its client code, you'll be able to remove the wrapper Client Component. - -### Sharing data between Server Components - -Since Server Components are not interactive and therefore do not read from React state, you don't need React context to share data. Instead, you can use native JavaScript patterns for common data that multiple Server Components need to access. For example, a module can be used to share a database connection across multiple components: - -```ts filename="utils/database.ts" switcher -export const db = new DatabaseConnection() -``` - -```js filename="utils/database.js" switcher -export const db = new DatabaseConnection() -``` - -```tsx filename="app/users/layout.tsx" switcher -import { db } from '@utils/database' - -export async function UsersLayout() { - let users = await db.query() - // ... -} -``` - -```jsx filename="app/users/layout.js" switcher -import { db } from '@utils/database' - -export async function UsersLayout() { - let users = await db.query() - // ... -} -``` - -```tsx filename="app/users/[id]/page.tsx" switcher -import { db } from '@utils/database' - -export async function DashboardPage() { - let user = await db.query() - // ... -} -``` - -```jsx filename="app/users/[id]/page.js" switcher -import { db } from '@utils/database' - -export async function DashboardPage() { - let user = await db.query() - // ... -} -``` - -In the above example, both the layout and page need to make database queries. Each of these components shares access to the database by importing the `@utils/database` module. This JavaScript pattern is called global singletons. - -### Sharing fetch requests between Server Components - -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 memoized](/docs/app/building-your-application/caching#request-memoization) in Server Components, so each route segment can request exactly the data it needs without worrying about duplicate requests. Next.js will read the same value from the `fetch` cache. diff --git a/docs/01-getting-started/index.mdx b/docs/01-getting-started/index.mdx deleted file mode 100644 index 2c04700d7b..0000000000 --- a/docs/01-getting-started/index.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Getting Started -description: Learn how to create full-stack web applications with Next.js. ---- - -Get started with Next.js by creating a new application using the [Installation](/docs/getting-started/installation) guide. - -If you are new to React, we recommend going through the [React Essentials](/docs/getting-started/react-essentials) guides for an introduction of the basic concepts. diff --git a/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx b/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx index e6a8cb116c..7a93480b14 100644 --- a/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx +++ b/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx @@ -54,7 +54,7 @@ export default function Page() { > - A page is always the [leaf](/docs/app/building-your-application/routing#terminology) of the [route subtree](/docs/app/building-your-application/routing#terminology). > - `.js`, `.jsx`, or `.tsx` file extensions can be used for Pages. > - A `page.js` file is required to make a route segment publicly accessible. -> - Pages 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). +> - Pages are [Server Components](/docs/app/building-your-application/rendering/server-components) by default but can be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > - Pages can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information. ## Layouts @@ -109,7 +109,7 @@ export default function DashboardLayout({ > - Any route segment can optionally define its own [Layout](#nesting-layouts). These layouts will be shared across all pages in that segment. > - Layouts in a route are **nested** by default. Each parent layout wraps child layouts below it using the React `children` prop. > - 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 are [Server Components](/docs/app/building-your-application/rendering/server-components) by default but can be set to a [Client Component](/docs/app/building-your-application/rendering/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/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. @@ -150,7 +150,7 @@ export default function RootLayout({ children }) { > - The root layout must define `` and `` tags since Next.js does not automatically create them. > - You can use the [built-in SEO support](/docs/app/building-your-application/optimizing/metadata) to manage `` HTML elements, for example, the `` element. > - You can use [route groups](/docs/app/building-your-application/routing/route-groups) to create multiple root layouts. See an [example here](/docs/app/building-your-application/routing/route-groups#creating-multiple-root-layouts). -> - The root layout is a [Server Component](/docs/getting-started/react-essentials) by default and **can not** be set to a [Client Component](/docs/getting-started/react-essentials#client-components). +> - The root layout is a [Server Component](/docs/app/building-your-application/rendering/server-components) by default and **can not** be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > **Migrating from the `pages` directory:** The root layout replaces the [`_app.js`](/docs/pages/building-your-application/routing/custom-app) and [`_document.js`](/docs/pages/building-your-application/routing/custom-document) files. [View the migration guide](/docs/app/building-your-application/upgrading/app-router-migration#migrating-_documentjs-and-_appjs). diff --git a/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx b/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx index 4bd216e4f0..3e5d4e2a83 100644 --- a/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx +++ b/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx @@ -165,8 +165,8 @@ There are two ways routes are prefetched in Next.js: The`<Link>`'s prefetching behavior is different for static and dynamic routes: -- [**Static Routes**](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default): `prefetch` defaults to `true`. The entire route is prefetched and cached. -- [**Dynamic Routes**](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering): `prefetch` default to automatic. Only the shared layout down until the first `loading.js` file is prefetched and cached for `30s`. This reduces the cost of fetching an entire dynamic route, and it means you can show an [instant loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for better visual feedback to users. +- [**Static Routes**](/docs/app/building-your-application/rendering/server-components#static-rendering-default): `prefetch` defaults to `true`. The entire route is prefetched and cached. +- [**Dynamic Routes**](/docs/app/building-your-application/rendering/server-components#dynamic-rendering): `prefetch` default to automatic. Only the shared layout down until the first `loading.js` file is prefetched and cached for `30s`. This reduces the cost of fetching an entire dynamic route, and it means you can show an [instant loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for better visual feedback to users. You can disable prefetching by setting the `prefetch` prop to `false`. diff --git a/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx b/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx index edfef950b0..1f4ee11c1c 100644 --- a/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx +++ b/docs/02-app/01-building-your-application/01-routing/05-dynamic-routes.mdx @@ -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#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/server-components#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() { diff --git a/docs/02-app/01-building-your-application/01-routing/13-internationalization.mdx b/docs/02-app/01-building-your-application/01-routing/13-internationalization.mdx index 20f9d03256..faa06d2805 100644 --- a/docs/02-app/01-building-your-application/01-routing/13-internationalization.mdx +++ b/docs/02-app/01-building-your-application/01-routing/13-internationalization.mdx @@ -127,7 +127,7 @@ export default async function Page({ params: { lang } }) { } ``` -Because all layouts and pages in the `app/` directory default to [Server Components](/docs/getting-started/react-essentials#server-components), we do not need to worry about the size of the translation files affecting our client-side JavaScript bundle size. This code will **only run on the server**, and only the resulting HTML will be sent to the browser. +Because all layouts and pages in the `app/` directory default to [Server Components](/docs/app/building-your-application/rendering/server-components), we do not need to worry about the size of the translation files affecting our client-side JavaScript bundle size. This code will **only run on the server**, and only the resulting HTML will be sent to the browser. ## Static Generation diff --git a/docs/02-app/01-building-your-application/01-routing/index.mdx b/docs/02-app/01-building-your-application/01-routing/index.mdx index 87b1204b2a..e0c25449d3 100644 --- a/docs/02-app/01-building-your-application/01-routing/index.mdx +++ b/docs/02-app/01-building-your-application/01-routing/index.mdx @@ -36,7 +36,7 @@ First, you will see these terms being used throughout the documentation. Here's ## The `app` Router -In version 13, Next.js introduced a new **App Router** built on [React Server Components](/docs/getting-started/react-essentials#server-components), which supports shared layouts, nested routing, loading states, error handling, and more. +In version 13, Next.js introduced a new **App Router** built on [React Server Components](/docs/app/building-your-application/rendering/server-components), which supports shared layouts, nested routing, loading states, error handling, and more. The App Router works in a new directory named `app`. The `app` directory works alongside the `pages` directory to allow for incremental adoption. This allows you to opt some routes of your application into the new behavior while keeping other routes in the `pages` directory for previous behavior. If your application uses the `pages` directory, please also see the [Pages Router](/docs/pages/building-your-application/routing) documentation. @@ -50,9 +50,9 @@ The App Router works in a new directory named `app`. The `app` directory works a height="444" /> -By default, components inside `app` are [React Server Components](/docs/getting-started/react-essentials#server-components). This is a performance optimization and allows you to easily adopt them, and you can also use [Client Components](/docs/getting-started/react-essentials#client-components). +By default, components inside `app` are [React Server Components](/docs/app/building-your-application/rendering/server-components). This is a performance optimization and allows you to easily adopt them, and you can also use [Client Components](/docs/app/building-your-application/rendering/client-components). -> **Recommendation:** Check out the [Server and Client Components](/docs/getting-started/react-essentials) page if you're new to Server Components. +> **Recommendation:** Check out the [Server](/docs/app/building-your-application/rendering/server-components) page if you're new to Server Components. ## Roles of Folders and Files diff --git a/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx index 23b9b1071d..eb22b38f81 100644 --- a/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx +++ b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx @@ -277,7 +277,7 @@ There's an extensive list of Segment Config options, giving you fine-grained con In cases where you're using a third-party library that doesn't support or expose `fetch` (for example, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the [Route Segment Config Option](/docs/app/api-reference/file-conventions/route-segment-config) and React's `cache` function. -Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered. +Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered. > **Good to know:** > diff --git a/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx b/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx index 891bc4b6f2..854c0eae6c 100644 --- a/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx +++ b/docs/02-app/01-building-your-application/02-data-fetching/02-patterns.mdx @@ -304,10 +304,10 @@ export const getItem = cache(async (id) => { }) ``` -With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching [only happens on the server](/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning). +With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching [only happens on the server](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment). The `utils/get-item` exports can be used by Layouts, Pages, or other components to give them control over when an item's data is fetched. > **Good to know:** > -> - We recommend using the [`server-only` package](/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning) to make sure server data fetching functions are never used on the client. +> - We recommend using the [`server-only` package](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment) to make sure server data fetching functions are never used on the client. diff --git a/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx b/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx index d9b9bf5884..96de15db29 100644 --- a/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx +++ b/docs/02-app/01-building-your-application/02-data-fetching/03-server-actions.mdx @@ -61,7 +61,7 @@ export default function AddToCart({ productId }) { Rather than needing to manually create an API endpoint, Server Actions automatically create an endpoint for Next.js to use behind the scenes. When calling a Server Action, Next.js sends a `POST` request to the page you're on with metadata for which action to run. -Server Actions inherit the same runtime (either [Node.js or Edge](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes)) defined by the `page` or `layout` they're used on. Currently, if a route uses a Server Action, it is required to [render dynamically](/docs/app/building-your-application/rendering/static-and-dynamic). +Server Actions inherit the same runtime (either [Node.js or Edge](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes)) defined by the `page` or `layout` they're used on. Currently, if a route uses a Server Action, it is required to [render dynamically](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). > **Good to know:** > diff --git a/docs/02-app/01-building-your-application/03-rendering/01-server-components.mdx b/docs/02-app/01-building-your-application/03-rendering/01-server-components.mdx new file mode 100644 index 0000000000..f54290791c --- /dev/null +++ b/docs/02-app/01-building-your-application/03-rendering/01-server-components.mdx @@ -0,0 +1,136 @@ +--- +title: Server Components +description: Learn how you can use React Server Components to render parts of your application on the server. +related: + description: Learn how Next.js caches data and the result of static rendering. + links: + - app/building-your-application/caching +--- + +React Server Components allow you to write UI that can be rendered and optionally cached on the server. In Next.js, the rendering work is further split by route segments to enable streaming and partial rendering, and there are three different server rendering strategies: + +- [Static Rendering](#static-rendering-default) +- [Dynamic Rendering](#dynamic-rendering) +- [Streaming](#streaming) + +This page will go through how Server Components work, when you might use them, and the different server rendering strategies. + +## Benefits of Server Rendering + +There are a couple of benefits to doing the rendering work on the server, including: + +- **Data Fetching**: Server Components allow you to move data fetching to the server, closer to your data source. This can improve performance by reducing time it takes to fetch data needed for rendering, and the amount of requests the client needs to make. +- **Security**: Server Components allow you to keep sensitive data and logic on the server, such as tokens and API keys, without the risk of exposing them to the client. +- **Caching**: By rendering on the server, the result can be cached and reused on subsequent requests and across users. This can improve performance and reduce cost by reducing the amount of rendering and data fetching done on each request. +- **Bundle Sizes**: Server Components allow you to keep large dependencies that previously would impact the client JavaScript bundle size on the server. This is beneficial for users with slower internet or less powerful devices, as the client does not have to download, parse and execute any JavaScript for Server Components. +- **Initial Page Load and [First Contentful Paint (FCP)](https://web.dev/fcp/)**: On the server, we can generate HTML to allow users to view the page immediately, without waiting for the client to download, parse and execute the JavaScript needed to render the page. +- **Search Engine Optimization and Social Network Shareability**: The rendered HTML can be used by search engine bots to index your pages and social network bots to generate social card previews for your pages. +- **Streaming**: Server Components allow you to split the rendering work into chunks and stream them to the client as they become ready. This allows the user to see parts of the page earlier without having to wait for the entire page to be rendered on the server. + +## Using Server Components in Next.js + +By default, Next.js uses Server Components. This allows you to automatically implement server rendering with no additional configuration, and you can opt into using Client Components when you needed, see [Client Components](/docs/app/building-your-application/rendering/client-components). + +## How are Server Components rendered? + +On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks: by individual route segments and [Suspense Boundaries](https://react.dev/reference/react/Suspense). + +Each chunk is rendered in two steps: + +1. React renders Server Components into a special data format called the **React Server Component Payload (RSC Payload)**. +2. Next.js uses the RSC Payload and Client Component JavaScript instructions to render **HTML** on the server. + +{/* Rendering Diagram */} + +Then, on the client: + +1. The HTML is used to immediately show a fast non-interactive preview of the route - this is for the initial page load only. +2. The React Server Components Payload is used to reconcile the Client and Server Component trees, and update the DOM. +3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make the application interactive. + +> **What is the React Server Component Payload (RSC)?** +> +> The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains: +> +> - The rendered result of Server Components +> - Placeholders for where Client Components should be rendered and references to their JavaScript files +> - Any props passed from a Server Component to a Client Component + +## Server Rendering Strategies + +There are three subsets of server rendering: Static, Dynamic, and Streaming. + +### Static Rendering (Default) + +{/* Static Rendering Diagram */} + +With Static Rendering, routes are rendered at **build time**, or in the background after [data revalidation](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data). The result is cached and can be pushed to a [Content Delivery Network (CDN)](https://developer.mozilla.org/en-US/docs/Glossary/CDN). This optimization allows you to share the result of the rendering work between users and server requests. + +Static rendering is useful when a route has data that is not personalized to the user and can be known at build time, such as a static blog post or a product page. + +### Dynamic Rendering + +{/* Dynamic Rendering Diagram */} + +With Dynamic Rendering, routes are rendered for each user at **request time**. + +Dynamic rendering is useful when a route has data that is personalized to the user or has information that can only be known at request time, such as cookies or the URL's search params. + +> **Dynamic Routes with Cached Data** +> +> In most websites, routes are not fully static or fully dynamic - it's a spectrum. For example, you can have e-commerce page that uses cached product data that's revalidated at an interval, but also has uncached, personalized customer data. +> +> In Next.js, you can have dynamically rendered routes that have both cached and uncached data. This is because the RSC Payload and data are cached separetely. This allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time. +> +> Learn more about the [full-route cache](/docs/app/building-your-application/caching#full-route-cache) and [Data Cache](/docs/app/building-your-application/caching#data-cache). + +#### Switching to Dynamic Rendering + +During rendering, if a [dynamic function](#dynamic-functions) or [uncached data request](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching) 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: + +| Dynamic Functions | Data | Route | +| ----------------- | ---------- | -------------------- | +| No | Cached | Statically Rendered | +| Yes | Cached | Dynamically Rendered | +| No | Not Cached | Dynamically Rendered | +| Yes | Not Cached | Dynamically Rendered | + +In 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. + +As a developer, you do not need to choose between static and dynamic rendering as Next.js will automatically choose the best rendering strategy for each route based on the features and APIs used. Instead, you choose when to [cache or revalidate specific data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating), and you may choose to [stream](#streaming) parts of your UI. + +#### 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. + +Using any of these functions will opt the whole route into dynamic rendering at request time. + +### Streaming + +<Image + alt="Diagram showing parallelization of route segments during streaming, showing data fetching, rendering, and hydration of invidiual chunks." + srcLight="/docs/light/sequential-parallel-data-fetching.png" + srcDark="/docs/dark/sequential-parallel-data-fetching.png" + width="1600" + height="525" +/> + +With Streaming, routes are rendered on the server at **request time**. The work is split into chunks and streamed to the client as it becomes ready. This allows the user to see a preview of the page before it's fully rendered. + +<Image + alt="Diagram showing partially rendered page on the client, with loading UI for chunks that are being streamed." + srcLight="/docs/light/server-rendering-with-streaming.png" + srcDark="/docs/dark/server-rendering-with-streaming.png" + width="1600" + height="785" +/> + +Streaming is useful for lower-priority UI, or UI that depends on slower data fetches that would block rendering for the whole route. For example, reviews on a product page. + +In Next.js, you can stream route segments using `loading.js`, and UI components with [React Suspense](https://react.dev/reference/react/Suspense). See the [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) docs for more information. diff --git a/docs/02-app/01-building-your-application/03-rendering/01-static-and-dynamic.mdx b/docs/02-app/01-building-your-application/03-rendering/01-static-and-dynamic.mdx deleted file mode 100644 index 3505a4bf7c..0000000000 --- a/docs/02-app/01-building-your-application/03-rendering/01-static-and-dynamic.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -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 | -| Dynamically Rendered | No | Not Cached | -| Dynamically 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. diff --git a/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx b/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx new file mode 100644 index 0000000000..c4c61bdd8d --- /dev/null +++ b/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx @@ -0,0 +1,106 @@ +--- +title: Client Components +description: Learn how to use Client Components to render parts of your application on the client. +--- + +Client Components allows you to write interactive UI that can be rendered on the client at request time. In Next.js, client rendering is **opt-in**, meaning you have to explicitly decide what components React should render on the client. + +This page will go through how Client Components work, how they're rendered, and when you might use them. + +## Benefits of Client Rendering + +There are a couple of benefits to doing the rendering work on the client, including: + +- **Interactivity**: Client Components can use state, effects, and event listeners, meaning they can provide immediate feedback to the user and update the UI. +- **Browser APIs**: Client Components have access to browser APIs, like [geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) or [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), allowing you to build UI for specific use cases. + +## Using Client Components in Next.js + +To use Client Components, you can add the React [`"use client"` directive](https://react.dev/reference/react/use-client) at the top of a file, above your imports. + +`"use client` is used to declare a [boundary](/docs/app/building-your-application/rendering#network-boundary) between a Server and Client Component modules. This means that by defining a `"use client"` in a file, all other modules imported into it, including child components, are considered part of the client bundle - and will be rendered by React on the client. + +```tsx filename="app/counter.tsx" highlight={1} switcher +'use client' + +import { useState } from 'react' + +export default function Counter() { + const [count, setCount] = useState(0) + + return ( + <div> + <p>You clicked {count} times</p> + <button onClick={() => setCount(count + 1)}>Click me</button> + </div> + ) +} +``` + +```jsx filename="app/counter.js" highlight={1} switcher +'use client' + +import { useState } from 'react' + +export default function Counter() { + const [count, setCount] = useState(0) + + return ( + <div> + <p>You clicked {count} times</p> + <button onClick={() => setCount(count + 1)}>Click me</button> + </div> + ) +} +``` + +The diagram below shows nested components, using `onClick` and `useState` in `toggle.js` will cause an error if the `"use client"` directive is not defined. This is because, by default, the components are rendered on the server where these APIs are not available. By defining the `"use client"` directive to `toggle.js`, you can tell React to render the component and its on the client, where the APIs are available. + +<Image + alt="Use Client Directive and Network Boundary" + srcLight="/docs/light/use-client-directive.png" + srcDark="/docs/dark/use-client-directive.png" + width="1600" + height="1320" +/> + +> **Defining multiple `use client` entry points**: +> +> You can define multiple "use client" entry points in your React Component tree. This allows you to split your application into multiple client bundles (or branches). +> +> However, `"use client"` doesn't need to be defined in every component that needs to be rendered on the client. Once you define the boundary, all child components and modules imported into it are considered part of the client bundle. + +## How are Client Components Rendered? + +In Next.js, Client Components are rendered differently depending on whether the request is part of a full page load (an initial visit to your application or a page reload triggered by a browser refresh) or a subsequent navigation. + +### Full page load + +To optimize the initial page load, Next.js will use React's APIs to render a static HTML preview on the server for both Client and Server Components. This means, when the user first visits your application, they will see the content of the page immediately, without having to wait for the client to download, parse, and execute the Client Component JavaScript bundle. + +On the server: + +1. React renders Server Components into a special data format called the **React Server Component Payload (RSC Payload)**, which includes references to Client Components. +2. Next.js uses the RSC Payload and Client Component JavaScript instructions to render **HTML** for the route on the server. + +Then, on the client: + +1. The HTML is used to immediately show a fast non-interactive initial preview of the route. +2. The React Server Components Payload is used to reconcile the Client and Server Component trees, and update the DOM. +3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make their UI interactive. + +> **What is hydration?** + +> Hydration is process of attaching event listeners to the DOM, to make the static HTML interactive. Behind the scenes, hydration is done with the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) React API. + +### Subsequent Navigations + +On subsequent navigations, Client Components are rendered entirely on the client, without the server-rendered HTML. + +This means the Client Component JavaScript bundle is downloaded and parsed. Once the bundle is ready, React will use the RSC Payload to reconcile the Client and Server Component trees, and update the DOM. + +## Going back to the Server Environment + +Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server. + +You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and Server Actions. See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information. diff --git a/docs/02-app/01-building-your-application/03-rendering/02-server-and-client-components.mdx b/docs/02-app/01-building-your-application/03-rendering/02-server-and-client-components.mdx deleted file mode 100644 index 894caa5c6a..0000000000 --- a/docs/02-app/01-building-your-application/03-rendering/02-server-and-client-components.mdx +++ /dev/null @@ -1,7 +0,0 @@ ---- -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). diff --git a/docs/02-app/01-building-your-application/03-rendering/03-composition-patterns.mdx b/docs/02-app/01-building-your-application/03-rendering/03-composition-patterns.mdx new file mode 100644 index 0000000000..766d9f74a4 --- /dev/null +++ b/docs/02-app/01-building-your-application/03-rendering/03-composition-patterns.mdx @@ -0,0 +1,556 @@ +--- +title: Server and Client Composition Patterns +nav_title: Patterns +description: Recommended patterns for using Server and Client Components. +--- + +When building React applications, you will need to consider what parts of your application should be rendered on the server or the client. This page covers some recommended composition patterns when using Server and Client Components. + +## When to use Server and Client Components? + +Here's a quick summary of the different use cases for Server and Client Components: + +| What do you need to do? | Server Component | Client Component | +| ---------------------------------------------------------------------------------- | ------------------- | ------------------- | +| Fetch data | <Check size={18} /> | <Cross size={18} /> | +| Access backend resources (directly) | <Check size={18} /> | <Cross size={18} /> | +| Keep sensitive information on the server (access tokens, API keys, etc) | <Check size={18} /> | <Cross size={18} /> | +| Keep large dependencies on the server / Reduce client-side JavaScript | <Check size={18} /> | <Cross size={18} /> | +| Add interactivity and event listeners (`onClick()`, `onChange()`, etc) | <Cross size={18} /> | <Check size={18} /> | +| Use State and Lifecycle Effects (`useState()`, `useReducer()`, `useEffect()`, etc) | <Cross size={18} /> | <Check size={18} /> | +| Use browser-only APIs | <Cross size={18} /> | <Check size={18} /> | +| Use custom hooks that depend on state, effects, or browser-only APIs | <Cross size={18} /> | <Check size={18} /> | +| Use [React Class components](https://react.dev/reference/react/Component) | <Cross size={18} /> | <Check size={18} /> | + +## Server Component Patterns + +Before opting into client-side rendering, you may wish to do some work on the server like fetching data, or accessing your database or backend services. + +Here are some common patterns when working with Server Components: + +### Sharing data between components + +When fetching data on the server, there may be cases where you need to share data across different components. For example, you may have a layout and a page that depend on the same data. + +Instead of using [React Context](https://react.dev/learn/passing-data-deeply-with-context) (which is not available on the server) or passing data as props, you can use [`fetch`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch) or React's `cache` function to fetch the same data in the components that need it, without worrying about making duplicate requests for the same data. This is because React extends `fetch` to automatically memoize data requests, and the `cache` function can be used when `fetch` is not available. + +Learn more about [memoization](/docs/app/building-your-application/caching#request-memoization) in React. + +### Keeping Server-only Code out of the Client Environment + +Since JavaScript modules can be shared between both Server and Client Components modules, it's possible for code that was only ever intended to be run on the server to sneak its way into the client. + +For example, take the following data-fetching function: + +```ts filename="lib/data.ts" switcher +export async function getData() { + const res = await fetch('https://external-service.com/data', { + headers: { + authorization: process.env.API_KEY, + }, + }) + + return res.json() +} +``` + +```js filename="lib/data.js" switcher +export async function getData() { + const res = await fetch('https://external-service.com/data', { + headers: { + authorization: process.env.API_KEY, + }, + }) + + return res.json() +} +``` + +At first glance, it appears that `getData` works on both the server and the client. However, this function contains an `API_KEY`, written with the intention that it would only ever be executed on the server. + +Since the environment variable `API_KEY` is not prefixed with `NEXT_PUBLIC`, it's a private variable that can only be accessed on the server. To prevent your environment variables from being leaked to the client, Next.js replaces private environment variables with an empty string. + +As a result, even though `getData()` can be imported and executed on the client, it won't work as expected. And while making the variable public would make the function work on the client, you may not want to expose sensitive information to the client. + +To prevent this sort of unintended client usage of server code, we can use the `server-only` package to give other developers a build-time error if they ever accidentally import one of these modules into a Client Component. + +To use `server-only`, first install the package: + +```bash filename="Terminal" +npm install server-only +``` + +Then import the package into any module that contains server-only code: + +```js filename="lib/data.js" +import 'server-only' + +export async function getData() { + const res = await fetch('https://external-service.com/data', { + headers: { + authorization: process.env.API_KEY, + }, + }) + + return res.json() +} +``` + +Now, any Client Component that imports `getData()` will receive a build-time error explaining that this module can only be used on the server. + +The corresponding package `client-only` can be used to mark modules that contain client-only code – for example, code that accesses the `window` object. + +### Using Third-party Packages and Providers + +Since Server Components are a new React feature, third-party packages and providers in the ecosystem are just beginning to add the `"use client"` directive to components that use client-only features like `useState`, `useEffect`, and `createContext`. + +Today, many components from `npm` packages that use client-only features do not yet have the directive. These third-party components will work as expected within Client Components since they have the `"use client"` directive, but they won't work within Server Components. + +For example, let's say you've installed the hypothetical `acme-carousel` package which has a `<Carousel />` component. This component uses `useState`, but it doesn't yet have the `"use client"` directive. + +If you use `<Carousel />` within a Client Component, it will work as expected: + +```tsx filename="app/gallery.tsx" switcher +'use client' + +import { useState } from 'react' +import { Carousel } from 'acme-carousel' + +export default function Gallery() { + let [isOpen, setIsOpen] = useState(false) + + return ( + <div> + <button onClick={() => setIsOpen(true)}>View pictures</button> + + {/* Works, since Carousel is used within a Client Component */} + {isOpen && <Carousel />} + </div> + ) +} +``` + +```jsx filename="app/gallery.js" switcher +'use client' + +import { useState } from 'react' +import { Carousel } from 'acme-carousel' + +export default function Gallery() { + let [isOpen, setIsOpen] = useState(false) + + return ( + <div> + <button onClick={() => setIsOpen(true)}>View pictures</button> + + {/* Works, since Carousel is used within a Client Component */} + {isOpen && <Carousel />} + </div> + ) +} +``` + +However, if you try to use it directly within a Server Component, you'll see an error: + +```tsx filename="app/page.tsx" switcher +import { Carousel } from 'acme-carousel' + +export default function Page() { + return ( + <div> + <p>View pictures</p> + + {/* Error: `useState` can not be used within Server Components */} + <Carousel /> + </div> + ) +} +``` + +```jsx filename="app/page.js" switcher +import { Carousel } from 'acme-carousel' + +export default function Page() { + return ( + <div> + <p>View pictures</p> + + {/* Error: `useState` can not be used within Server Components */} + <Carousel /> + </div> + ) +} +``` + +This is because Next.js doesn't know `<Carousel />` is using client-only features. + +To fix this, you can wrap third-party components that rely on client-only features in your own Client Components: + +```tsx filename="app/carousel.tsx" switcher +'use client' + +import { Carousel } from 'acme-carousel' + +export default Carousel +``` + +```jsx filename="app/carousel.js" switcher +'use client' + +import { Carousel } from 'acme-carousel' + +export default Carousel +``` + +Now, you can use `<Carousel />` directly within a Server Component: + +```tsx filename="app/page.tsx" switcher +import Carousel from './carousel' + +export default function Page() { + return ( + <div> + <p>View pictures</p> + + {/* Works, since Carousel is a Client Component */} + <Carousel /> + </div> + ) +} +``` + +```jsx filename="app/page.js" switcher +import Carousel from './carousel' + +export default function Page() { + return ( + <div> + <p>View pictures</p> + + {/* Works, since Carousel is a Client Component */} + <Carousel /> + </div> + ) +} +``` + +We don't expect you to need to wrap most third-party components since it's likely you'll be using them within Client Components. However, one exception is providers, since they rely on React state and context, and are typically needed at the root of an application. [Learn more about third-party context providers below](#using-context-providers). + +#### Using Context Providers + +Context providers are typically rendered near the root of an application to share global concerns, like the current theme. Since [React context](https://react.dev/learn/passing-data-deeply-with-context) is not supported in Server Components, trying to create a context at the root of your application will cause an error: + +```tsx filename="app/layout.tsx" switcher +import { createContext } from 'react' + +// createContext is not supported in Server Components +export const ThemeContext = createContext({}) + +export default function RootLayout({ children }) { + return ( + <html> + <body> + <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> + </body> + </html> + ) +} +``` + +```jsx filename="app/layout.js" switcher +import { createContext } from 'react' + +// createContext is not supported in Server Components +export const ThemeContext = createContext({}) + +export default function RootLayout({ children }) { + return ( + <html> + <body> + <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> + </body> + </html> + ) +} +``` + +To fix this, create your context and render its provider inside of a Client Component: + +```tsx filename="app/theme-provider.tsx" switcher +'use client' + +import { createContext } from 'react' + +export const ThemeContext = createContext({}) + +export default function ThemeProvider({ children }) { + return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> +} +``` + +```jsx filename="app/theme-provider.js" switcher +'use client' + +import { createContext } from 'react' + +export const ThemeContext = createContext({}) + +export default function ThemeProvider({ children }) { + return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> +} +``` + +Your Server Component will now be able to directly render your provider since it's been marked as a Client Component: + +```tsx filename="app/layout.tsx" switcher +import ThemeProvider from './theme-provider' + +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + <html> + <body> + <ThemeProvider>{children}</ThemeProvider> + </body> + </html> + ) +} +``` + +```jsx filename="app/layout.js" switcher +import ThemeProvider from './theme-provider' + +export default function RootLayout({ children }) { + return ( + <html> + <body> + <ThemeProvider>{children}</ThemeProvider> + </body> + </html> + ) +} +``` + +With the provider rendered at the root, all other Client Components throughout your app will be able to consume this context. + +> **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components. + +#### Advice for Library Authors + +In a similar fashion, library authors creating packages to be consumed by other developers can use the `"use client"` directive to mark client entry points of their package. This allows users of the package to import package components directly into their Server Components without having to create a wrapping boundary. + +You can optimize your package by using ['use client' deeper in the tree](#moving-client-components-down-the-tree), allowing the imported modules to be part of the Server Component module graph. + +It's worth noting some bundlers might strip out `"use client"` directives. You can find an example of how to configure esbuild to include the `"use client"` directive in the [React Wrap Balancer](https://github.com/shuding/react-wrap-balancer/blob/main/tsup.config.ts#L10-L13) and [Vercel Analytics](https://github.com/vercel/analytics/blob/main/packages/web/tsup.config.js#L26-L30) repositories. + +### Client Components + +#### Moving Client Components Down the Tree + +To reduce the Client JavaScript bundle size, we recommend moving Client Components down your component tree. + +For example, you may have a Layout that has static elements (e.g. logo, links, etc) and an interactive search bar that uses state. + +Instead of making the whole layout a Client Component, move the interactive logic to a Client Component (e.g. `<SearchBar />`) and keep your layout as a Server Component. This means you don't have to send all the component Javascript of the layout to the client. + +```tsx filename="app/layout.tsx" switcher +// SearchBar is a Client Component +import SearchBar from './searchbar' +// Logo is a Server Component +import Logo from './logo' + +// Layout is a Server Component by default +export default function Layout({ children }: { children: React.ReactNode }) { + return ( + <> + <nav> + <Logo /> + <SearchBar /> + </nav> + <main>{children}</main> + </> + ) +} +``` + +```jsx filename="app/layout.js" switcher +// SearchBar is a Client Component +import SearchBar from './searchbar' +// Logo is a Server Component +import Logo from './logo' + +// Layout is a Server Component by default +export default function Layout({ children }) { + return ( + <> + <nav> + <Logo /> + <SearchBar /> + </nav> + <main>{children}</main> + </> + ) +} +``` + +### Passing props from Server to Client Components (Serialization) + +If you fetch data in a Server Component, you may want to pass data down as props to Client Components. Props passed from the Server to Client Components need to be [serializable](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) by React. + +If your Client Components depend on data that is not serializable, you can [fetch data on the client with a third party library](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-client-with-third-party-libraries) or on the server via a [Route Handler](/docs/app/building-your-application/routing/route-handlers). + +## Interleaving Server and Client Components + +When interleaving Client and Server Components, it may be helpful to visualize your UI as a tree of components. Starting with the [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required), which is a Server Component, you can then render certain subtrees of components on the client by adding the `"use client"` directive. + +{/* Diagram - interleaving */} + +Within those client subtrees, you can still nest Server Components or call Server Actions, however there are some things to keep in mind: + +- During a request-response lifecycle, your code moves from the server to the client. If you need to access data or resources on the server while on the client, you'll be making a **new** request to the server - not switching back and forth. +- When a new request is made to the server, all Server Components are rendered first, including those nested inside Client Components. The rendered result (RSC Payload) will contain references to the locations of Client Components. Then, on the client, React uses the RSC Payload to reconcile Server and Client Components into a single tree. + +{/* Diagram */} + +- Since Client Components are rendered after Server Components, you cannot import a Server Component into a Client Component module (since it would require a new request back to the server). Instead, you can pass a Server Component as `props` to a Client Component. See the [unsupported pattern](#unsupported-pattern-importing-server-components-into-client-components) and [supported pattern](#supported-pattern-passing-server-components-to-client-components-as-props) sections below. + +### Unsupported Pattern: Importing Server Components into Client Components + +The following pattern is not supported. You cannot import a Server Component into a Client Component: + +```tsx filename="app/client-component.tsx" switcher highlight={4,17} +'use client' + +// You cannot import a Server Component into a Client Component. +import ServerComponent from './Server-Component' + +export default function ClientComponent({ + children, +}: { + children: React.ReactNode +}) { + const [count, setCount] = useState(0) + + return ( + <> + <button onClick={() => setCount(count + 1)}>{count}</button> + + <ServerComponent /> + </> + ) +} +``` + +```jsx filename="app/client-component.js" switcher highlight={3,13} +'use client' + +// You cannot import a Server Component into a Client Component. +import ServerComponent from './Server-Component' + +export default function ClientComponent({ children }) { + const [count, setCount] = useState(0) + + return ( + <> + <button onClick={() => setCount(count + 1)}>{count}</button> + + <ServerComponent /> + </> + ) +} +``` + +#### Supported Pattern: Passing Server Components to Client Components as Props + +The following pattern is supported. You can pass Server Components as a prop to a Client Component. + +A common pattern is to use the React `children` prop to create a _"slot"_ in your Client Component. + +In the example below, `<ClientComponent>` accepts a `children` prop: + +```tsx filename="app/client-component.tsx" switcher highlight={6,15} +'use client' + +import { useState } from 'react' + +export default function ClientComponent({ + children, +}: { + children: React.ReactNode +}) { + const [count, setCount] = useState(0) + + return ( + <> + <button onClick={() => setCount(count + 1)}>{count}</button> + {children} + </> + ) +} +``` + +```jsx filename="app/client-component.js" switcher highlight={5,12} +'use client' + +import { useState } from 'react' + +export default function ClientComponent({ children }) { + const [count, setCount] = useState(0) + + return ( + <> + <button onClick={() => setCount(count + 1)}>{count}</button> + + {children} + </> + ) +} +``` + +`<ClientComponent>` doesn't know that `children` will eventually be filled in by the result of a Server Component. The only responsibility `<ClientComponent>` has is to decide **where** `children` will eventually be placed. + +In a parent Server Component, you can import both the `<ClientComponent>` and `<ServerComponent>` and pass `<ServerComponent>` as a child of `<ClientComponent>`: + +```tsx filename="app/page.tsx" highlight={11} switcher +// This pattern works: +// You can pass a Server Component as a child or prop of a +// Client Component. +import ClientComponent from './client-component' +import ServerComponent from './server-component' + +// Pages in Next.js are Server Components by default +export default function Page() { + return ( + <ClientComponent> + <ServerComponent /> + </ClientComponent> + ) +} +``` + +```jsx filename="app/page.js" highlight={11} switcher +// This pattern works: +// You can pass a Server Component as a child or prop of a +// Client Component. +import ClientComponent from './client-component' +import ServerComponent from './server-component' + +// Pages in Next.js are Server Components by default +export default function Page() { + return ( + <ClientComponent> + <ServerComponent /> + </ClientComponent> + ) +} +``` + +With this approach, `<ClientComponent>` and `<ServerComponent>` are decoupled and can be rendered independently. In this case, the child `<ServerComponent>` can be rendered on the server, well before `<ClientComponent>` is rendered on the client. + +> **Good to know:** +> +> - The pattern of "lifting content up" has been used to avoid re-rendering a nested child component when a parent to re-renders. +> - You're not limited to the `children` prop. You can use any prop to pass JSX. diff --git a/docs/02-app/01-building-your-application/03-rendering/03-edge-and-nodejs-runtimes.mdx b/docs/02-app/01-building-your-application/03-rendering/04-edge-and-nodejs-runtimes.mdx similarity index 100% rename from docs/02-app/01-building-your-application/03-rendering/03-edge-and-nodejs-runtimes.mdx rename to docs/02-app/01-building-your-application/03-rendering/04-edge-and-nodejs-runtimes.mdx diff --git a/docs/02-app/01-building-your-application/03-rendering/index.mdx b/docs/02-app/01-building-your-application/03-rendering/index.mdx index 81bad5fc67..6e2fd0ea65 100644 --- a/docs/02-app/01-building-your-application/03-rendering/index.mdx +++ b/docs/02-app/01-building-your-application/03-rendering/index.mdx @@ -3,9 +3,17 @@ 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. +Rendering converts the code you write into user interfaces. React and Next.js allow you to create hybrid web applications where parts of your code can be rendered on the server or the client. This section will help you understand the differences between these rendering environments, strategies, and runtimes. -## Background +## Fundamentals + +To start, it's helpful to be familiar with three foundational web concepts: + +- The [Environments](#rendering-environments) your application code can be executed in: the server and the client. +- The [Request-Response Lifecycle](#request-response-lifecycle) that's initiated when a user visits or interacts with your application. +- The [Network Boundary](#network-boundary) that separates server and client code. + +### Rendering Environments There are two environments where web applications can be rendered: the client and the server. @@ -17,13 +25,54 @@ There are two environments where web applications can be rendered: the client an 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. +- 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 a user interface. +- The **server** refers to the computer in a data center that stores your application code, receives requests from a client, 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. +Historically, developers had to use different languages (e.g. JavaScript, PHP) and frameworks when writing code for the server and the client. With React, developers can use the **same language** (JavaScript), and the **same framework** (e.g. Next.js or your framework of choice). This flexibility allows you to seamlessly write code for both environments without context switching. -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. +However, each environment has its own set of capabilities and constraints. Therefore, the code you write for the server and the client is not always the same. There are certain operations (e.g. data fetching or managing user state) that are better suited for one environment over the other. -By default, the App Router uses Server Components to improve performance, and you can opt into using Client Components when needed. +Understanding these differences is key to effectively using React and Next.js. We'll cover the differences and use cases in more detail on the [Server](/docs/app/building-your-application/rendering/server-components) and [Client](/docs/app/building-your-application/rendering/client-components) Components pages, for now, let's continue building on our foundation. -Learn more about rendering by exploring the sections below: +### Request-Response Lifecycle + +Broadly speaking, all websites follow the same **Request-Response Lifecycle**: + +1. **User Action:** The user interacts with a web application. This could be clicking a link, submitting a form, or typing a URL directly into the browser's address bar. +2. **HTTP Request:** The client sends an [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) request to the server that contains necessary information about what resources are being requested, what method is being used (e.g. `GET`, `POST`), and additional data if necessary. +3. **Server:** The server processes the request and responds with the appropriate resources. This process may take a couple of steps like routing, fetching data, etc. +4. **HTTP Response:** After processing the request, the server sends an HTTP response back to the client. This response contains a status code (which tells the client whether the request was successful or not) and requested resources (e.g. HTML, CSS, JavaScript, static assets, etc). +5. **Client:** The client parses the resources to render the user interface. +6. **User Action:** Once the user interface is rendered, the user can interact with it, and the whole process starts again. + +A major part of building a hybrid web application is deciding how to split the work in the lifecycle, and where to place the Network Boundary. + +### Network Boundary + +In web development, the **Network Boundary** is a conceptual line that separates the different environments. For example, the client and the server, or the server and the data store. + +{/* Diagram: Network Boundary */} + +In React, you choose where to place the client-server network boundary wherever it makes the most sense. + +Behind the scenes, the work is split into two parts: the **client module graph** and the **server module graph**. The server module graph contains all the components that are rendered on the server, and the client module graph contains all components that are rendered on the client. + +{/* Diagram: Client and Server Module Graphs */} + +It may be helpful to think about module graphs as a visual representation of how files in your application depend on each other. + +{/* For example, if you have a file called `Page.jsx` that imports a file called `Button.jsx` on the server, the module graph would look something like this: - Diagram - */} + +You can use the React `"use client"` convention to define the boundary. There's also a `"use server"` convention, which tells React to do some computational work on the server while on the client. + +## Building Hybrid Applications + +When working in these environments, it's helpful to think of the flow of the code in your application as **unidirectional**. In other words, during a response, your application code flows in one direction: from the server to the client. + +{/* Diagram: Response flow */} + +If you need to access the server from the client, you send a **new** request to the server rather than re-use the same request. This makes it easier understand where to render your components and where you to place the Network Boundary. + +In practice, this model encourages developers to think about what they want to execute on the server first, before sending the result to the client and making the application interactive. + +This concept will become clearer when we look at how you can [interleave client and server components](/docs/app/building-your-application/rendering/composition-patterns) in the same component tree. diff --git a/docs/02-app/01-building-your-application/04-caching/index.mdx b/docs/02-app/01-building-your-application/04-caching/index.mdx index 5081049437..21c98ef0c7 100644 --- a/docs/02-app/01-building-your-application/04-caching/index.mdx +++ b/docs/02-app/01-building-your-application/04-caching/index.mdx @@ -255,7 +255,7 @@ This means we don't have to wait for everything to render before caching the wor > - Placeholders for where Client Components should be rendered and references to their JavaScript files > - Any props passed from a Server Component to a Client Component > -> To learn more, see the [React Rendering](/docs/app/building-your-application/rendering/server-and-client-components) documentation. +> To learn more, see the [Server Components](/docs/app/building-your-application/rendering/server-components) documentation. ### 2. Next.js Caching on the Server (Full Route Cache) @@ -301,7 +301,7 @@ This diagram shows the difference between statically and dynamically rendered ro height="1314" /> -Learn more about [static and dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic). +Learn more about [static and dynamic rendering](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). ### Duration @@ -359,7 +359,7 @@ This results in an improved navigation experience for the user: The cache is stored in the browser's temporary memory. Two factors determine how long the router cache lasts: - **Session**: The cache persists across navigation. However, it's cleared on page refresh. -- **Automatic Invalidation Period**: The cache of an individual segment is automatically invalidated after a specific time. The duration depends on whether the route is [statically](/docs/app/building-your-application/rendering/static-and-dynamic#static-rendering-default) or [dynamically](/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering) rendered: +- **Automatic Invalidation Period**: The cache of an individual segment is automatically invalidated after a specific time. The duration depends on whether the route is [statically](/docs/app/building-your-application/rendering/server-components#static-rendering-default) or [dynamically](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) rendered: - **Dynamically Rendered**: 30 seconds - **Statically Rendered**: 5 minutes diff --git a/docs/02-app/01-building-your-application/06-optimizing/03-scripts.mdx b/docs/02-app/01-building-your-application/06-optimizing/03-scripts.mdx index a6be9fb23e..99ddb75b73 100644 --- a/docs/02-app/01-building-your-application/06-optimizing/03-scripts.mdx +++ b/docs/02-app/01-building-your-application/06-optimizing/03-scripts.mdx @@ -208,7 +208,7 @@ Event handlers can be used with the Script component to execute additional code <AppOnly> -These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/getting-started/react-essentials) where `"use client"` is defined as the first line of code: +These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/app/building-your-application/rendering/client-components) where `"use client"` is defined as the first line of code: ```tsx filename="app/page.tsx" switcher 'use client' @@ -254,7 +254,7 @@ Refer to the [`next/script`](/docs/app/api-reference/components/script#onload) A <PagesOnly> -These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/getting-started/react-essentials) where `"use client"` is defined as the first line of code: +These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/app/building-your-application/rendering/client-components) where `"use client"` is defined as the first line of code: ```tsx filename="pages/index.tsx" switcher import Script from 'next/script' diff --git a/docs/02-app/01-building-your-application/07-configuring/11-draft-mode.mdx b/docs/02-app/01-building-your-application/07-configuring/11-draft-mode.mdx index c0f624ca88..fee480698a 100644 --- a/docs/02-app/01-building-your-application/07-configuring/11-draft-mode.mdx +++ b/docs/02-app/01-building-your-application/07-configuring/11-draft-mode.mdx @@ -3,7 +3,7 @@ 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#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/server-components#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. diff --git a/docs/02-app/01-building-your-application/09-upgrading/02-app-router-migration.mdx b/docs/02-app/01-building-your-application/09-upgrading/02-app-router-migration.mdx index a4a92875fb..3b140f4b06 100644 --- a/docs/02-app/01-building-your-application/09-upgrading/02-app-router-migration.mdx +++ b/docs/02-app/01-building-your-application/09-upgrading/02-app-router-migration.mdx @@ -86,7 +86,7 @@ The behavior of [`next/script`](/docs/app/api-reference/components/script) has b - Move any `beforeInteractive` scripts you previously included in `_document.js` to the root layout file (`app/layout.tsx`). - The experimental `worker` strategy does not yet work in `app` and scripts denoted with this strategy will either have to be removed or modified to use a different strategy (e.g. `lazyOnload`). -- `onLoad`, `onReady`, and `onError` handlers will not work in Server Components so make sure to move them to a [Client Component](/docs/getting-started/react-essentials) or remove them altogether. +- `onLoad`, `onReady`, and `onError` handlers will not work in Server Components so make sure to move them to a [Client Component](/docs/app/building-your-application/rendering/server-components) or remove them altogether. ### Font Optimization @@ -188,7 +188,7 @@ export const metadata = { If you have an existing `_app` or `_document` file, you can copy the contents (e.g. global styles) to the root layout (`app/layout.tsx`). Styles in `app/layout.tsx` will _not_ apply to `pages/*`. You should keep `_app`/`_document` while migrating to prevent your `pages/*` routes from breaking. Once fully migrated, you can then safely delete them. -If you are using any React Context providers, they will need to be moved to a [Client Component](/docs/getting-started/react-essentials). +If you are using any React Context providers, they will need to be moved to a [Client Component](/docs/app/building-your-application/rendering/client-components). #### Migrating the `getLayout()` pattern to Layouts (Optional) @@ -232,7 +232,7 @@ Page.getLayout = function getLayout(page) { } ``` -- Move the contents of `DashboardLayout` into a new [Client Component](/docs/getting-started/react-essentials#client-components) to retain `pages` directory behavior. +- Move the contents of `DashboardLayout` into a new [Client Component](/docs/app/building-your-application/rendering/client-components) to retain `pages` directory behavior. ```jsx filename="app/dashboard/DashboardLayout.js" 'use client' // this directive should be at top of the file, before any imports. @@ -325,7 +325,7 @@ export default function Page() { ### Step 4: Migrating Pages -- Pages in the [`app` directory](/docs/app/building-your-application/routing) are [Server Components](/docs/getting-started/react-essentials) by default. This is different from the `pages` directory where pages are [Client Components](/docs/getting-started/react-essentials). +- Pages in the [`app` directory](/docs/app/building-your-application/routing) are [Server Components](/docs/app/building-your-application/rendering/server-components) by default. This is different from the `pages` directory where pages are [Client Components](/docs/app/building-your-application/rendering/client-components). - [Data fetching](/docs/app/building-your-application/data-fetching) has changed in `app`. `getServerSideProps`, `getStaticProps` and `getInitialProps` have been replaced with a simpler API. - The `app` directory uses nested folders to [define routes](/docs/app/building-your-application/routing/defining-routes) and a special `page.js` file to make a route segment publicly accessible. - | `pages` Directory | `app` Directory | Route | @@ -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-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. +- `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/building-your-application/rendering/server-components#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). @@ -547,7 +547,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. +In the `app` directory, we can colocate our data fetching inside our React components using [Server Components](/docs/app/building-your-application/rendering/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/fetching-caching-and-revalidating). This is similar to `getServerSideProps` in the `pages` directory. @@ -622,8 +622,8 @@ export default function Page(props) { The `app` directory exposes new read-only functions to retrieve request data: -- [`headers()`](/docs/app/api-reference/functions/headers): Based on the Web Headers API, and can be used inside [Server Components](/docs/getting-started/react-essentials) to retrieve request headers. -- [`cookies()`](/docs/app/api-reference/functions/cookies): Based on the Web Cookies API, and can be used inside [Server Components](/docs/getting-started/react-essentials) to retrieve cookies. +- [`headers()`](/docs/app/api-reference/functions/headers): Based on the Web Headers API, and can be used inside [Server Components](/docs/app/building-your-application/rendering/server-components) to retrieve request headers. +- [`cookies()`](/docs/app/api-reference/functions/cookies): Based on the Web Cookies API, and can be used inside [Server Components](/docs/app/building-your-application/rendering/server-components) to retrieve cookies. ```tsx filename="app/page.tsx" switcher // `app` directory @@ -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-caching-and-revalidating). +> **Good to know**: If you previously used API routes to call an external API from the client, you can now use [Server Components](/docs/app/building-your-application/rendering/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 diff --git a/docs/02-app/02-api-reference/01-components/image.mdx b/docs/02-app/02-api-reference/01-components/image.mdx index 86871f4dd9..b6c127120e 100644 --- a/docs/02-app/02-api-reference/01-components/image.mdx +++ b/docs/02-app/02-api-reference/01-components/image.mdx @@ -152,7 +152,7 @@ export default function Page() { <AppOnly> -> **Good to know**: Using props like `loader`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function. +> **Good to know**: Using props like `loader`, which accept a function, require using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. </AppOnly> @@ -292,7 +292,7 @@ The callback function will be called with one argument, a reference to the under <AppOnly> -> **Good to know**: Using props like `onLoadingComplete`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function. +> **Good to know**: Using props like `onLoadingComplete`, which accept a function, require using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. </AppOnly> @@ -308,7 +308,7 @@ The load event might occur before the image placeholder is removed and the image <AppOnly> -> **Good to know**: Using props like `onLoad`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function. +> **Good to know**: Using props like `onLoad`, which accept a function, require using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. </AppOnly> @@ -322,7 +322,7 @@ A callback function that is invoked if the image fails to load. <AppOnly> -> **Good to know**: Using props like `onError`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function. +> **Good to know**: Using props like `onError`, which accept a function, require using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. </AppOnly> @@ -492,7 +492,7 @@ Examples: <AppOnly> -> **Good to know**: Customizing the image loader file, which accepts a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function. +> **Good to know**: Customizing the image loader file, which accepts a function, require using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. </AppOnly> diff --git a/docs/02-app/02-api-reference/02-file-conventions/01-metadata/app-icons.mdx b/docs/02-app/02-api-reference/02-file-conventions/01-metadata/app-icons.mdx index 2d6db2dc2c..3a1346dbdb 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/01-metadata/app-icons.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/01-metadata/app-icons.mdx @@ -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#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. +> - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#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. diff --git a/docs/02-app/02-api-reference/02-file-conventions/01-metadata/opengraph-image.mdx b/docs/02-app/02-api-reference/02-file-conventions/01-metadata/opengraph-image.mdx index c28c2cf0e2..83e31ba69b 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/01-metadata/opengraph-image.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/01-metadata/opengraph-image.mdx @@ -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#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. +> - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#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`. @@ -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#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/server-components#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' diff --git a/docs/02-app/02-api-reference/02-file-conventions/error.mdx b/docs/02-app/02-api-reference/02-file-conventions/error.mdx index 3b920e245a..b2561d6fe3 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/error.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/error.mdx @@ -96,7 +96,7 @@ Can be used to prompt the user to attempt to recover from the error. > **Good to know**: > -> - `error.js` boundaries must be **[Client Components](/docs/getting-started/react-essentials)**. +> - `error.js` boundaries must be **[Client Components](/docs/app/building-your-application/rendering/client-components)**. > - In Production builds, errors forwarded from Server Components will be stripped of specific error details to avoid leaking sensitive information. > - An `error.js` boundary will **not** handle errors thrown in a `layout.js` component in the **same** segment because the error boundary is nested **inside** that layouts component. > - To handle errors for a specific layout, place an `error.js` file in the layouts parent segment. diff --git a/docs/02-app/02-api-reference/02-file-conventions/loading.mdx b/docs/02-app/02-api-reference/02-file-conventions/loading.mdx index 8b9224abaf..ec538b01c0 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/loading.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/loading.mdx @@ -5,7 +5,7 @@ description: API reference for the loading.js file. A **loading** file can create instant loading states built on [Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming). -By default, this file is a [Server Component](/docs/getting-started/react-essentials#server-components) - but can also be used as a Client Component through the `"use client"` directive. +By default, this file is a [Server Component](/docs/app/building-your-application/rendering/server-components) - but can also be used as a Client Component through the `"use client"` directive. ```tsx filename="app/feed/loading.tsx" switcher export default function Loading() { diff --git a/docs/02-app/02-api-reference/02-file-conventions/page.mdx b/docs/02-app/02-api-reference/02-file-conventions/page.mdx index 21af2f7632..edd8d37f3e 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/page.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/page.mdx @@ -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#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` is a **[Dynamic API](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#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/server-components#dynamic-rendering)** at request time. > - `searchParams` returns a plain JavaScript object and not a `URLSearchParams` instance. ## Version History diff --git a/docs/02-app/02-api-reference/02-file-conventions/route-segment-config.mdx b/docs/02-app/02-api-reference/02-file-conventions/route-segment-config.mdx index 449d27dbf5..7d3e8b3a6d 100644 --- a/docs/02-app/02-api-reference/02-file-conventions/route-segment-config.mdx +++ b/docs/02-app/02-api-reference/02-file-conventions/route-segment-config.mdx @@ -68,7 +68,7 @@ export const dynamic = 'auto' - 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 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: +- **`'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/server-components#server-rendering-strategies#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`. @@ -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#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. +- **`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/server-components#server-rendering-strategies#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/server-components#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. > **Good to know**: The `revalidate` option is only available when using the [Node.js Runtime](/https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#nodejs-runtime). This means using the `revalidate` option with `runtime = 'edge'` will not work. @@ -130,7 +130,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#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/server-components#server-rendering-strategies#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. diff --git a/docs/02-app/02-api-reference/04-functions/cookies.mdx b/docs/02-app/02-api-reference/04-functions/cookies.mdx index 78570764a3..2a9d597f95 100644 --- a/docs/02-app/02-api-reference/04-functions/cookies.mdx +++ b/docs/02-app/02-api-reference/04-functions/cookies.mdx @@ -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/route-handlers). +The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/app/building-your-application/rendering/server-components) 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#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. +> **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#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/server-components#dynamic-rendering)** at request time. ## `cookies().get(name)` diff --git a/docs/02-app/02-api-reference/04-functions/draft-mode.mdx b/docs/02-app/02-api-reference/04-functions/draft-mode.mdx index c16242a627..0e22481ea8 100644 --- a/docs/02-app/02-api-reference/04-functions/draft-mode.mdx +++ b/docs/02-app/02-api-reference/04-functions/draft-mode.mdx @@ -3,7 +3,7 @@ title: draftMode description: API Reference for the draftMode function. --- -The `draftMode` function allows you to detect [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) inside a [Server Component](/docs/getting-started/react-essentials). +The `draftMode` function allows you to detect [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) inside a [Server Component](/docs/app/building-your-application/rendering/server-components). ```jsx filename="app/page.js" import { draftMode } from 'next/headers' diff --git a/docs/02-app/02-api-reference/04-functions/fetch.mdx b/docs/02-app/02-api-reference/04-functions/fetch.mdx index 859c370d09..5bea3d17f7 100644 --- a/docs/02-app/02-api-reference/04-functions/fetch.mdx +++ b/docs/02-app/02-api-reference/04-functions/fetch.mdx @@ -55,8 +55,6 @@ export default async function Page() { Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), you can use any of the [native options available](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters). -Further, Next.js polyfills `fetch` on both the client and the server, so you can use fetch in both [Server and Client Components](/docs/getting-started/react-essentials). - ### `options.cache` Configure how the request should interact with Next.js [Data Cache](/docs/app/building-your-application/caching#data-cache). @@ -72,7 +70,7 @@ fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) > **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#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/server-components#server-rendering-strategies#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` diff --git a/docs/02-app/02-api-reference/04-functions/generate-static-params.mdx b/docs/02-app/02-api-reference/04-functions/generate-static-params.mdx index 3f1431279f..ff20442f1b 100644 --- a/docs/02-app/02-api-reference/04-functions/generate-static-params.mdx +++ b/docs/02-app/02-api-reference/04-functions/generate-static-params.mdx @@ -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#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/server-components#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 diff --git a/docs/02-app/02-api-reference/04-functions/headers.mdx b/docs/02-app/02-api-reference/04-functions/headers.mdx index 788a6a37eb..49fd586c9d 100644 --- a/docs/02-app/02-api-reference/04-functions/headers.mdx +++ b/docs/02-app/02-api-reference/04-functions/headers.mdx @@ -3,7 +3,7 @@ title: headers description: API reference for the headers function. --- -The `headers` function allows you to read the HTTP incoming request headers from a [Server Component](/docs/getting-started/react-essentials). +The `headers` function allows you to read the HTTP incoming request headers from a [Server Component](/docs/app/building-your-application/rendering/server-components). ## `headers()` @@ -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#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. +> - `headers()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#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/server-components#dynamic-rendering)** at request time. ### API Reference diff --git a/docs/02-app/02-api-reference/04-functions/use-pathname.mdx b/docs/02-app/02-api-reference/04-functions/use-pathname.mdx index c3ea07eccb..1204b70a6c 100644 --- a/docs/02-app/02-api-reference/04-functions/use-pathname.mdx +++ b/docs/02-app/02-api-reference/04-functions/use-pathname.mdx @@ -27,13 +27,13 @@ export default function ExampleClientComponent() { } ``` -`usePathname` intentionally requires using a [Client Component](/docs/getting-started/react-essentials). It's important to note Client Components are not a de-optimization. They are an integral part of the [Server Components](/docs/getting-started/react-essentials) architecture. +`usePathname` intentionally requires using a [Client Component](/docs/app/building-your-application/rendering/client-components). It's important to note Client Components are not a de-optimization. They are an integral part of the [Server Components](/docs/app/building-your-application/rendering/server-components) architecture. For example, a Client Component with `usePathname` will be rendered into HTML on the initial page load. When navigating to a new route, this component does not need to be re-fetched. Instead, the component is downloaded once (in the client JavaScript bundle), and re-renders based on the current state. > **Good to know**: > -> - Reading the current URL from a [Server Component](/docs/getting-started/react-essentials) is not supported. This design is intentional to support layout state being preserved across page navigations. +> - Reading the current URL from a [Server Component](/docs/app/building-your-application/rendering/server-components) is not supported. This design is intentional to support layout state being preserved across page navigations. > - Compatibility mode: > - `usePathname` can return `null` when a [fallback route](/docs/pages/api-reference/functions/get-static-paths#fallback-true) is being rendered or when a `pages` directory page has been [automatically statically optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization) by Next.js and the router is not ready. > - Next.js will automatically update your types if it detects both an `app` and `pages` directory in your project. diff --git a/docs/02-app/02-api-reference/04-functions/use-router.mdx b/docs/02-app/02-api-reference/04-functions/use-router.mdx index ed34bd2fc2..121b77a17f 100644 --- a/docs/02-app/02-api-reference/04-functions/use-router.mdx +++ b/docs/02-app/02-api-reference/04-functions/use-router.mdx @@ -3,7 +3,7 @@ title: useRouter description: API reference for the useRouter hook. --- -The `useRouter` hook allows you to programmatically change routes inside [Client Components](/docs/getting-started/react-essentials). +The `useRouter` hook allows you to programmatically change routes inside [Client Components](/docs/app/building-your-application/rendering/client-components). > **Recommendation:** Use the [`<Link>` component](/docs/app/building-your-application/routing/linking-and-navigating#link-component) for navigation unless you have a specific requirement for using `useRouter`. @@ -110,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#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/server-components#static-rendering-default). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior). ### Disabling scroll restoration diff --git a/docs/02-app/02-api-reference/04-functions/use-search-params.mdx b/docs/02-app/02-api-reference/04-functions/use-search-params.mdx index 7b1552eadb..0451a9981e 100644 --- a/docs/02-app/02-api-reference/04-functions/use-search-params.mdx +++ b/docs/02-app/02-api-reference/04-functions/use-search-params.mdx @@ -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/linking-and-navigating#3-partial-rendering). +> - `useSearchParams` is a [Client Component](/docs/app/building-your-application/rendering/client-components) hook and is **not supported** in [Server Components](/docs/app/building-your-application/rendering/server-components) 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#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/server-components#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#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/server-components#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. diff --git a/docs/02-app/02-api-reference/04-functions/use-selected-layout-segment.mdx b/docs/02-app/02-api-reference/04-functions/use-selected-layout-segment.mdx index 6dee9ef5a6..c9bcdbbf9d 100644 --- a/docs/02-app/02-api-reference/04-functions/use-selected-layout-segment.mdx +++ b/docs/02-app/02-api-reference/04-functions/use-selected-layout-segment.mdx @@ -33,7 +33,7 @@ export default function ExampleClientComponent() { > **Good to know**: > -> - Since `useSelectedLayoutSegment` is a [Client Component](/docs/getting-started/react-essentials#client-components) hook, and Layouts are [Server Components](/docs/getting-started/react-essentials#server-components) by default, `useSelectedLayoutSegment` is usually called via a Client Component that is imported into a Layout. +> - Since `useSelectedLayoutSegment` is a [Client Component](/docs/app/building-your-application/rendering/client-components) hook, and Layouts are [Server Components](/docs/app/building-your-application/rendering/server-components) by default, `useSelectedLayoutSegment` is usually called via a Client Component that is imported into a Layout. > - `useSelectedLayoutSegment` only returns the segment one level down. To return all active segments, see [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) ## Parameters diff --git a/docs/02-app/02-api-reference/04-functions/use-selected-layout-segments.mdx b/docs/02-app/02-api-reference/04-functions/use-selected-layout-segments.mdx index a0c416e147..d6dc86e028 100644 --- a/docs/02-app/02-api-reference/04-functions/use-selected-layout-segments.mdx +++ b/docs/02-app/02-api-reference/04-functions/use-selected-layout-segments.mdx @@ -45,7 +45,7 @@ export default function ExampleClientComponent() { > **Good to know**: > -> - Since `useSelectedLayoutSegments` is a [Client Component](/docs/getting-started/react-essentials#client-components) hook, and Layouts are [Server Components](/docs/getting-started/react-essentials#server-components) by default, `useSelectedLayoutSegments` is usually called via a Client Component that is imported into a Layout. +> - Since `useSelectedLayoutSegments` is a [Client Component](/docs/app/building-your-application/rendering/client-components) hook, and Layouts are [Server Components](/docs/app/building-your-application/rendering/server-components) by default, `useSelectedLayoutSegments` is usually called via a Client Component that is imported into a Layout. > - The returned segments include [Route Groups](/docs/app/building-your-application/routing/route-groups), which you might not want to be included in your UI. You can use the `filter()` array method to remove items that start with a bracket. ## Parameters diff --git a/docs/02-app/02-api-reference/05-next-config-js/appDir.mdx b/docs/02-app/02-api-reference/05-next-config-js/appDir.mdx index 13fa2d486c..067a1c530a 100644 --- a/docs/02-app/02-api-reference/05-next-config-js/appDir.mdx +++ b/docs/02-app/02-api-reference/05-next-config-js/appDir.mdx @@ -5,6 +5,6 @@ description: Enable the App Router to use layouts, streaming, and more. > **Good to know**: This option is **no longer** needed as of Next.js 13.4. The App Router is now stable. -The App Router ([`app` directory](/docs/app/building-your-application/routing)) enables support for [layouts](/docs/app/building-your-application/routing/pages-and-layouts), [Server Components](/docs/getting-started/react-essentials#server-components), [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming), and [colocated data fetching](/docs/app/building-your-application/data-fetching). +The App Router ([`app` directory](/docs/app/building-your-application/routing)) enables support for [layouts](/docs/app/building-your-application/routing/pages-and-layouts), [Server Components](/docs/app/building-your-application/rendering/server-components), [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming), and [colocated data fetching](/docs/app/building-your-application/data-fetching). Using the `app` directory will automatically enable [React Strict Mode](https://react.dev/reference/react/StrictMode). Learn how to [incrementally adopt `app`](/docs/app/building-your-application/upgrading/app-router-migration#migrating-from-pages-to-app). diff --git a/docs/02-app/02-api-reference/05-next-config-js/serverComponentsExternalPackages.mdx b/docs/02-app/02-api-reference/05-next-config-js/serverComponentsExternalPackages.mdx index b290b3621d..9452840613 100644 --- a/docs/02-app/02-api-reference/05-next-config-js/serverComponentsExternalPackages.mdx +++ b/docs/02-app/02-api-reference/05-next-config-js/serverComponentsExternalPackages.mdx @@ -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/route-handlers) will automatically be bundled by Next.js. +Dependencies used inside [Server Components](/docs/app/building-your-application/rendering/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`. diff --git a/docs/03-pages/02-api-reference/03-next-config-js/runtime-configuration.mdx b/docs/03-pages/02-api-reference/03-next-config-js/runtime-configuration.mdx index 4e092594cd..153954d33a 100644 --- a/docs/03-pages/02-api-reference/03-next-config-js/runtime-configuration.mdx +++ b/docs/03-pages/02-api-reference/03-next-config-js/runtime-configuration.mdx @@ -3,7 +3,7 @@ title: Runtime Config description: Add client and server runtime configuration to your Next.js app. --- -> **Warning**: This feature is considered legacy and does not work with [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization), [Output File Tracing](/docs/pages/api-reference/next-config-js/output#automatically-copying-traced-files), or [React Server Components](/docs/getting-started/react-essentials#server-components). Please use [environment variables](/docs/pages/building-your-application/configuring/environment-variables) instead to avoid initialization overhead. +> **Warning**: This feature is considered legacy and does not work with [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization), [Output File Tracing](/docs/pages/api-reference/next-config-js/output#automatically-copying-traced-files), or [React Server Components](/docs/app/building-your-application/rendering/server-components). Please use [environment variables](/docs/pages/building-your-application/configuring/environment-variables) instead to avoid initialization overhead. To add runtime configuration to your app, open `next.config.js` and add the `publicRuntimeConfig` and `serverRuntimeConfig` configs: diff --git a/docs/index.mdx b/docs/index.mdx index 48b2b6fd99..3831cd8f30 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -32,7 +32,7 @@ On the left side of the screen, you'll find the docs navbar. The pages of the do On the right side of the screen, you'll see a table of contents that makes it easier to navigate between sections of a page. If you need to quickly find a page, you can use the search bar at the top, or the search shortcut (`Ctrl+K` or `Cmd+K`). -To get started, checkout the [Installation](/docs/getting-started/installation) guide. If you're new to React, we recommend reading the [React Essentials](/docs/getting-started/react-essentials) page. +To get started, checkout the [Installation](/docs/getting-started/installation) guide. ## App Router vs Pages Router diff --git a/errors/app-static-to-dynamic-error.mdx b/errors/app-static-to-dynamic-error.mdx index e7a9ee5641..07e090ff34 100644 --- a/errors/app-static-to-dynamic-error.mdx +++ b/errors/app-static-to-dynamic-error.mdx @@ -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) - 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. +- [Static and Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies) - Learn more about the differences between static and dynamic rendering in Next.js. +- [Dynamic Functions](/docs/app/building-your-application/rendering/server-components#dynamic-functions) - Understand more about the usage of dynamic server functions in your Next.js application. diff --git a/errors/class-component-in-server-component.mdx b/errors/class-component-in-server-component.mdx index 7936dc017e..701ebfd30c 100644 --- a/errors/class-component-in-server-component.mdx +++ b/errors/class-component-in-server-component.mdx @@ -54,4 +54,4 @@ export default class Page extends React.Component { ## Useful Links -[Server and Client Components](/docs/getting-started/react-essentials) +[Server Components](/docs/app/building-your-application/rendering/server-components) diff --git a/errors/context-in-server-component.mdx b/errors/context-in-server-component.mdx index d44491681b..1c39592261 100644 --- a/errors/context-in-server-component.mdx +++ b/errors/context-in-server-component.mdx @@ -29,4 +29,4 @@ const Context = createContext() ## Useful Links -[Server and Client Components](/docs/getting-started/react-essentials#context) +[Server and Client Components Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) diff --git a/errors/react-client-hook-in-server-component.mdx b/errors/react-client-hook-in-server-component.mdx index 5f1eb78d8e..332045f01f 100644 --- a/errors/react-client-hook-in-server-component.mdx +++ b/errors/react-client-hook-in-server-component.mdx @@ -40,4 +40,4 @@ export default function Example() { ## Useful Links -[Server and Client Components](/docs/getting-started/react-essentials) +[Server Components](/docs/app/building-your-application/rendering/server-components)