}
diff --git a/contributing/.vercel.approvers b/contributing/.vercel.approvers
new file mode 100644
index 0000000000000..2ed372107ca9f
--- /dev/null
+++ b/contributing/.vercel.approvers
@@ -0,0 +1,2 @@
+@vercel/devex
+@vercel/next-js:optional
\ No newline at end of file
diff --git a/contributing/docs/adding-documentation.md b/contributing/docs/adding-documentation.md
index 37ea3654600ad..5067e7d3f5373 100644
--- a/contributing/docs/adding-documentation.md
+++ b/contributing/docs/adding-documentation.md
@@ -1,40 +1,3 @@
-# Updating Documentation Paths
+# Contributing to Documentation
-Our documentation currently leverages a [manifest file](/docs/manifest.json), which is how documentation entries are checked.
-
-When adding a new entry under an existing category you only need to add an entry with `{title: '', path: '/docs/path/to/file.md'}`. The "title" is what is shown on the sidebar.
-
-When moving the location/url of an entry, the "title" field can be removed from the existing entry and the ".md" extension removed from the "path", then a "redirect" field with the shape of `{permanent: true/false, destination: '/some-url'}` can be added. A new entry should be added with the "title" and "path" fields if the document is renamed within the [`docs` folder](/docs) that points to the new location in the folder, e.g. `/docs/some-url.md`
-
-Example of moving documentation file:
-
-Before:
-
-```json
-[
- {
- "path": "/docs/original.md",
- "title": "Hello world"
- }
-]
-```
-
-After:
-
-```json
-[
- {
- "path": "/docs/original",
- "redirect": {
- "permanent": false,
- "destination": "/new"
- }
- },
- {
- "path": "/docs/new.md",
- "title": "Hello world"
- }
-]
-```
-
-Note: the manifest is checked automatically in the "lint" step in CI when opening a PR.
+See the [Docs Contribution Guide](https://nextjs.org/docs/community/contribution-guide) to learn how to contribute to the Next.js Documentation.
diff --git a/contributing/examples/adding-examples.md b/contributing/examples/adding-examples.md
index 978857e0ef8e8..9fbbaac8c6828 100644
--- a/contributing/examples/adding-examples.md
+++ b/contributing/examples/adding-examples.md
@@ -35,7 +35,7 @@ Description
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
-[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/DIRECTORY_NAME&project-name=DIRECTORY_NAME&repository-name=DIRECTORY_NAME)
+[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/DIRECTORY_NAME&project-name=DIRECTORY_NAME&repository-name=DIRECTORY_NAME)
## How to use
diff --git a/docs/.vercel.approvers b/docs/.vercel.approvers
new file mode 100644
index 0000000000000..2ed372107ca9f
--- /dev/null
+++ b/docs/.vercel.approvers
@@ -0,0 +1,2 @@
+@vercel/devex
+@vercel/next-js:optional
\ No newline at end of file
diff --git a/docs/01-getting-started/01-installation.mdx b/docs/01-getting-started/01-installation.mdx
new file mode 100644
index 0000000000000..046d9feda5325
--- /dev/null
+++ b/docs/01-getting-started/01-installation.mdx
@@ -0,0 +1,134 @@
+---
+title: Installation
+description: Create a new Next.js application with `create-next-app`. Set up TypeScript, styles, and configure your `next.config.js` file.
+related:
+ title: Next Steps
+ description: For more information on what to do next, we recommend the following sections
+ links:
+ - getting-started/react-essentials
+ - app/building-your-application
+ - app/building-your-application/configuring/typescript
+---
+
+System Requirements:
+
+- [Node.js 16.8](https://nodejs.org/) or later.
+- macOS, Windows (including WSL), and Linux are supported.
+
+## Automatic Installation
+
+We recommend creating a new Next.js app using `create-next-app`, which sets up everything automatically for you. To create a project, run:
+
+```bash filename="Terminal"
+npx create-next-app@latest
+```
+
+On installation, you'll see the following prompts:
+
+```txt filename="Terminal"
+What is your project named? my-app
+Would you like to use TypeScript with this project? No / Yes
+Would you like to use ESLint with this project? No / Yes
+Would you like to use Tailwind CSS with this project? No / Yes
+Would you like to use `src/` directory with this project? No / Yes
+Use App Router (recommended)? No / Yes
+Would you like to customize the default import alias? No / Yes
+```
+
+Next.js now ships with TypeScript, ESLint, and Tailwind CSS configuration by default. You can also choose to use the `src` directory for your application code.
+
+After the prompts, `create-next-app` will create a folder with your project name and install the required dependencies.
+
+> **Note:** While you can use the [Pages Router](/docs/pages) in your new project. We recommend starting new applications with the App Router to leverage React's latest features.
+
+## Manual Installation
+
+To manually create a new Next.js app, install the required packages:
+
+```bash filename="Terminal"
+npm install next@latest react@latest react-dom@latest
+```
+
+Open `package.json` and add the following `scripts`:
+
+```json filename="package.json"
+{
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start",
+ "lint": "next lint"
+ }
+}
+```
+
+These scripts refer to the different stages of developing an application:
+
+- `dev`: runs [`next dev`](/docs/app/api-reference/next-cli#development) to start Next.js in development mode.
+- `build`: runs [`next build`](/docs/app/api-reference/next-cli#build) to build the application for production usage.
+- `start`: runs [`next start`](/docs/app/api-reference/next-cli#production) to start a Next.js production server.
+- `lint`: runs [`next lint`](/docs/app/api-reference/next-cli#lint) to set up Next.js' built-in ESLint configuration.
+
+### Create the `app` folder
+
+Next, create an `app` folder and add a `layout.tsx` and `page.tsx` file. These will be rendered when the user visits the root of your application.
+
+
+
+Create a [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) inside `app/layout.tsx` with the required `` and `` tags:
+
+```tsx filename="app/layout.tsx" switcher
+export default function RootLayout({
+ children,
+}: {
+ children: React.ReactNode
+}) {
+ return (
+
+ {children}
+
+ )
+}
+```
+
+```jsx filename="app/layout.js" switcher
+export default function RootLayout({ children }) {
+ return (
+
+ {children}
+
+ )
+}
+```
+
+Finally, create a home page `app/page.tsx` with some initial content:
+
+```tsx filename="app/page.tsx" switcher
+export default function Page() {
+ return
+}
+```
+
+> **Good to know**: If you forget to create `layout.tsx`, Next.js will automatically create this file for you when running the development server with `next dev`.
+
+### Create the `public` folder
+
+You can optionally create a `public` folder to store static assets such as images, fonts, etc. Files inside `public` directory can then be referenced by your code starting from the base URL (`/`).
+
+## Run the Development Server
+
+1. Run `npm run dev` to start the development server.
+2. Visit `http://localhost:3000` to view your application.
+3. Edit `app/layout.tsx` or `app/page.tsx` and save to see the updated result in your browser.
diff --git a/docs/01-getting-started/02-project-structure.mdx b/docs/01-getting-started/02-project-structure.mdx
new file mode 100644
index 0000000000000..ca755f3d86375
--- /dev/null
+++ b/docs/01-getting-started/02-project-structure.mdx
@@ -0,0 +1,149 @@
+---
+title: Next.js Project Structure
+nav_title: Project Structure
+description: A list of folders and files conventions in a Next.js project
+---
+
+This page provides an overview of the file and folder structure of a Next.js project. It covers top-level files and folders, configuration files, and routing conventions within the `app` and `pages` directories.
+
+## Top-level files
+
+| | |
+| ------------------------------------------------------------------------------------------- | --------------------------------------- |
+| **Next.js** | |
+| [`next.config.js`](/docs/app/api-reference/next-config-js) | Configuration file for Next.js |
+| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware |
+| [`.env`](/docs/app/building-your-application/configuring/environment-variables) | Environment variables |
+| [`.env.local`](/docs/app/building-your-application/configuring/environment-variables) | Local environment variables |
+| [`.env.production`](/docs/app/building-your-application/configuring/environment-variables) | Production environment variables |
+| [`.env.development`](/docs/app/building-your-application/configuring/environment-variables) | Development environment variables |
+| `.next-env.d.ts` | TypeScript declaration file for Next.js |
+| **Ecosystem** | |
+| [`package.json`](/docs/getting-started/installation#manual-installation) | Project dependencies and scripts |
+| `.gitignore` | Git files and folders to ignore |
+| `tsconfig.json` | Configuration file for TypeScript |
+| `jsconfig.json` | Configuration file for JavaScript |
+| [`.eslintrc.json`](/docs/app/building-your-application/configuring/eslint) | Configuration file for ESLint |
+
+## Top-level folders
+
+| | |
+| ----------------------------------------------------------------------- | ---------------------------------- |
+| [`app`](/docs/app/building-your-application/routing) | App Router |
+| [`pages`](/docs/pages/building-your-application/routing) | Pages Router |
+| [`public`](/docs/getting-started/installation#create-the-public-folder) | Static assets to be served |
+| [`src`](/docs/app/building-your-application/configuring/src-directory) | Optional application source folder |
+
+## `app` Routing Conventions
+
+### Routing Files
+
+| | | |
+| ------------------------------------------------------------------------------- | ------------------- | ---------------------------- |
+| [`layout`](/docs/app/api-reference/file-conventions/layout) | `.js` `.jsx` `.tsx` | Layout |
+| [`page`](/docs/app/api-reference/file-conventions/page) | `.js` `.jsx` `.tsx` | Page |
+| [`loading`](/docs/app/api-reference/file-conventions/loading) | `.js` `.jsx` `.tsx` | Loading UI |
+| [`not-found`](/docs/app/api-reference/file-conventions/not-found) | `.js` `.jsx` `.tsx` | Not found UI |
+| [`error`](/docs/app/api-reference/file-conventions/error) | `.js` `.jsx` `.tsx` | Error UI |
+| [`global-error`](/docs/app/api-reference/file-conventions/error#global-errorjs) | `.js` `.jsx` `.tsx` | Global error UI |
+| [`route`](/docs/app/api-reference/file-conventions/route) | `.js` `.ts` | API endpoint |
+| [`template`](/docs/app/api-reference/file-conventions/template) | `.js` `.jsx` `.tsx` | Re-rendered layout |
+| [`default`](/docs/app/api-reference/file-conventions/default) | `.js` `.jsx` `.tsx` | Parallel route fallback page |
+
+### Nested Routes
+
+| | |
+| ---------------------------------------------------------------------------- | -------------------- |
+| [`folder`](/docs/app/building-your-application/routing#route-segments) | Route segment |
+| [`folder/folder`](/docs/app/building-your-application/routing#nested-routes) | Nested route segment |
+
+### Dynamic Routes
+
+| | |
+| --------------------------------------------------------------------------------------------------------- | --------------------------- |
+| [`[folder]`](/docs/app/building-your-application/routing/dynamic-routes#convention) | Dynamic route segment |
+| [`[...folder]`](/docs/app/building-your-application/routing/dynamic-routes) | Catch-all segments |
+| [`[[...folder]]`](/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments) | Optional catch-all segments |
+
+### Route Groups and Private Folders
+
+| | |
+| ----------------------------------------------------------------------------------- | ------------------------------------------------ |
+| [`(folder)`](/docs/app/building-your-application/routing/route-groups#convention) | Group routes without affecting routing |
+| [`_folder`](/docs/app/building-your-application/routing/colocation#private-folders) | Opt folder and all child segments out of routing |
+
+### Parallel and Intercepted Routes
+
+| | |
+| ---------------------------------------------------------------------------------------------- | -------------------------- |
+| [`@folder`](/docs/app/building-your-application/routing/parallel-routes#convention) | Named slot |
+| [`(.)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) | Intercept same level |
+| [`(..)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) | Intercept one level above |
+| [`(..)(..)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) | Intercept two levels above |
+| [`(...)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) | Intercept from root |
+
+### Metadata File Conventions
+
+#### App Icons
+
+| | | |
+| --------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------------------------ |
+| [`favicon`](/docs/app/api-reference/file-conventions/metadata/app-icons#favicon) | `.ico` | Favicon file |
+| [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon) | `.png` `.svg` | App Icon file |
+| [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.ico` `.jpg` `.jpeg` `.png` `.svg` | Generated App Icon |
+| [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon) | `.jpg` `.jpeg`, `.png` | Apple App Icon file |
+| [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated Apple App Icon |
+
+#### Open Graph and Twitter Images
+
+| | | |
+| --------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | -------------------------- |
+| [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#opengraph-image) | `.jpg` `.jpeg` `.png` `.gif` | Open Graph image file |
+| [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#generate-images-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated Open Graph image |
+| [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#twitter-image) | `.jpg` `.jpeg` `.png` `.gif` | Twitter image file |
+| [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#generate-images-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated Twitter image |
+
+#### SEO
+
+| | | |
+| ------------------------------------------------------------------------------------------- | ----------- | --------------------- |
+| [`sitemap`](/docs/app/api-reference/file-conventions/metadata/sitemap#static-sitemapxml) | `.xml` | Sitemap file |
+| [`sitemap`](/docs/app/api-reference/file-conventions/metadata/sitemap#generate-a-sitemap) | `.js` `.ts` | Generated Sitemap |
+| [`robots`](/docs/app/api-reference/file-conventions/metadata/robots#static-robotstxt) | `.txt` | Robots file |
+| [`robots`](/docs/app/api-reference/file-conventions/metadata/robots#generate-a-robots-file) | `.js` `.ts` | Generated Robots file |
+
+## `pages` Routing Conventions
+
+### Special Files
+
+| | | |
+| ----------------------------------------------------------------------------------------------------------- | ------------------- | ----------------- |
+| [`_app`](/docs/pages/building-your-application/routing/custom-app) | `.js` `.jsx` `.tsx` | Custom App |
+| [`_document`](/docs/pages/building-your-application/routing/custom-document) | `.js` `.jsx` `.tsx` | Custom Document |
+| [`_error`](/docs/pages/building-your-application/routing/custom-error#more-advanced-error-page-customizing) | `.js` `.jsx` `.tsx` | Custom Error Page |
+| [`404`](/docs/pages/building-your-application/routing/custom-error#404-page) | `.js` `.jsx` `.tsx` | 404 Error Page |
+| [`500`](/docs/pages/building-your-application/routing/custom-error#500-page) | `.js` `.jsx` `.tsx` | 500 Error Page |
+
+### Routes
+
+| | | |
+| ---------------------------------------------------------------------------------------------- | ------------------- | ----------- |
+| **Folder convention** | | |
+| [`index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) | `.js` `.jsx` `.tsx` | Home page |
+| [`folder/index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) | `.js` `.jsx` `.tsx` | Nested page |
+| **File convention** | | |
+| [`index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) | `.js` `.jsx` `.tsx` | Home page |
+| [`file`](/docs/pages/building-your-application/routing/pages-and-layouts) | `.js` `.jsx` `.tsx` | Nested page |
+
+### Dynamic Routes
+
+| | | |
+| ----------------------------------------------------------------------------------------------------------------- | ------------------- | --------------------------- |
+| **Folder convention** | | |
+| [`[folder]/index`](/docs/pages/building-your-application/routing/dynamic-routes) | `.js` `.jsx` `.tsx` | Dynamic route segment |
+| [`[...folder]/index`](/docs/pages/building-your-application/routing/dynamic-routes#catch-all-segments) | `.js` `.jsx` `.tsx` | Catch-all segments |
+| [`[[...folder]]/index`](/docs/pages/building-your-application/routing/dynamic-routes#optional-catch-all-segments) | `.js` `.jsx` `.tsx` | Optional catch-all segments |
+| **File convention** | | |
+| [`[file]`](/docs/pages/building-your-application/routing/dynamic-routes) | `.js` `.jsx` `.tsx` | Dynamic route segment |
+| [`[...file]`](/docs/pages/building-your-application/routing/dynamic-routes#catch-all-segments) | `.js` `.jsx` `.tsx` | Catch-all segments |
+| [`[[...file]]`](/docs/pages/building-your-application/routing/dynamic-routes#optional-catch-all-segments) | `.js` `.jsx` `.tsx` | Optional catch-all segments |
diff --git a/docs/01-getting-started/03-react-essentials.mdx b/docs/01-getting-started/03-react-essentials.mdx
new file mode 100644
index 0000000000000..0a0401bc44258
--- /dev/null
+++ b/docs/01-getting-started/03-react-essentials.mdx
@@ -0,0 +1,863 @@
+---
+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](/docs/app/building-your-application/rendering#rendering-environments).
+
+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:
+
+
+
+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#component-level-client-and-server-rendering) on the server and [hydrated](/docs/app/building-your-application/rendering#component-level-client-and-server-rendering) on the client. You can think of Client Components as how components in the [Pages Router](/docs/pages) have always worked.
+
+### 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 (
+
+ )
+}
+```
+
+
+
+`"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#static-and-dynamic-rendering-on-the-server) 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 _"holes"_ for Server Components.
+
+The Server Component will be rendered on the server, and when the Client Component is rendered on the client, the _"hole"_ 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 _"hole"_. 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. Infact, from its perspective it doesn't even 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 should 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 has no knowledge of **what** the prop is. It is only responsible for where the thing that it is passed should be placed.
+> - 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#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 an `` 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 */}
+
+
+
+ {/* 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 */}
+
+
+
+ {/* 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 (
+
+ )
+}
+```
+
+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.
+
+> Note: 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 deduped](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) in Server Components, so each route segment can request exactly the data it needs without worrying about duplicate requests. Next.js will read the same value from the `fetch` cache.
diff --git a/docs/01-getting-started/index.mdx b/docs/01-getting-started/index.mdx
new file mode 100644
index 0000000000000..2c04700d7b5b8
--- /dev/null
+++ b/docs/01-getting-started/index.mdx
@@ -0,0 +1,8 @@
+---
+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/01-defining-routes.mdx b/docs/02-app/01-building-your-application/01-routing/01-defining-routes.mdx
new file mode 100644
index 0000000000000..0cad98f02477e
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/01-defining-routes.mdx
@@ -0,0 +1,58 @@
+---
+title: Defining Routes
+description: Learn how to create your first route in Next.js.
+related:
+ description: Learn more about creating pages and layouts.
+ links:
+ - app/building-your-application/routing/pages-and-layouts
+---
+
+> We recommend reading the [Routing Fundamentals](/docs/app/building-your-application/routing) page before continuing.
+
+This page will guide you through how to define and organize routes in your Next.js application.
+
+## Creating Routes
+
+Next.js uses a file-system based router where **folders** are used to define routes.
+
+Each folder represents a [**route** segment](/docs/app/building-your-application/routing#route-segments) that maps to a **URL** segment. To create a [nested route](/docs/app/building-your-application/routing#nested-routes), you can nest folders inside each other.
+
+
+
+A special [`page.js` file](/docs/app/building-your-application/routing/pages-and-layouts#pages) is used to make route segments publicly accessible.
+
+
+
+In this example, the `/dashboard/analytics` URL path is _not_ publicly accessible because it does not have a corresponding `page.js` file. This folder could be used to store components, stylesheets, images, or other colocated files.
+
+> **Good to know:** `.js`, `.jsx`, or `.tsx` file extensions can be used for special files.
+
+## Creating UI
+
+[Special file conventions](/docs/app/building-your-application/routing#file-conventions) are used to create UI for each route segment. The most common are [pages](/docs/app/building-your-application/routing/pages-and-layouts#pages) to show UI unique to a route, and [layouts](/docs/app/building-your-application/routing/pages-and-layouts#layouts) to show UI that is shared across multiple routes.
+
+For example, to create your first page, add a `page.js` file inside the `app` directory and export a React component:
+
+```tsx filename="app/page.tsx" switcher
+export default function Page() {
+ return
+}
+```
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
new file mode 100644
index 0000000000000..3ba1c5c16d7e9
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx
@@ -0,0 +1,272 @@
+---
+title: Pages and Layouts
+description: Create your first page and shared layout with the App Router.
+---
+
+> We recommend reading the [Routing Fundamentals](/docs/app/building-your-application/routing) and [Defining Routes](/docs/app/building-your-application/routing/defining-routes) pages before continuing.
+
+The App Router inside Next.js 13 introduced new file conventions to easily create [pages](#pages), [shared layouts](#layouts), and [templates](#templates). This page will guide you through how to use these special files in your Next.js application.
+
+## Pages
+
+A page is UI that is **unique** to a route. You can define pages by exporting a component from a `page.js` file. Use nested folders to [define a route](/docs/app/building-your-application/routing/defining-routes) and a `page.js` file to make the route publicly accessible.
+
+Create your first page by adding a `page.js` file inside the `app` directory:
+
+
+
+```tsx filename="app/page.tsx" switcher
+// `app/page.tsx` is the UI for the `/` URL
+export default function Page() {
+ return
Hello, Home page!
+}
+```
+
+```jsx filename="app/page.js" switcher
+// `app/page.js` is the UI for the `/` URL
+export default function Page() {
+ return
Hello, Home page!
+}
+```
+
+```tsx filename="app/dashboard/page.tsx" switcher
+// `app/dashboard/page.tsx` is the UI for the `/dashboard` URL
+export default function Page() {
+ return
Hello, Dashboard Page!
+}
+```
+
+```jsx filename="app/dashboard/page.js" switcher
+// `app/dashboard/page.js` is the UI for the `/dashboard` URL
+export default function Page() {
+ return
Hello, Dashboard Page!
+}
+```
+
+> **Good to know:**
+>
+> - 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 can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information.
+
+## Layouts
+
+A layout is UI that is **shared** between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be [nested](#nesting-layouts).
+
+You can define a layout by `default` exporting a React component from a `layout.js` file. The component should accept a `children` prop that will be populated with a child layout (if it exists) or a child page during rendering.
+
+
+
+```tsx filename="app/dashboard/layout.tsx" switcher
+export default function DashboardLayout({
+ children, // will be a page or nested layout
+}: {
+ children: React.ReactNode
+}) {
+ return (
+
+ {/* Include shared UI here e.g. a header or sidebar */}
+
+
+ {children}
+
+ )
+}
+```
+
+```jsx filename="app/dashboard/layout.js" switcher
+export default function DashboardLayout({
+ children, // will be a page or nested layout
+}) {
+ return (
+
+ {/* Include shared UI here e.g. a header or sidebar */}
+
+
+ {children}
+
+ )
+}
+```
+
+> **Good to know:**
+>
+> - The top-most layout is called the [Root Layout](#root-layout-required). This **required** layout is shared across all pages in an application. Root layouts must contain `html` and `body` tags.
+> - 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 can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information.
+> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) without affecting performance.
+> - Layouts do not have access to the current route segment(s). To access route segments, you can use [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) in a Client Component.
+> - `.js`, `.jsx`, or `.tsx` file extensions can be used for Layouts.
+> - A `layout.js` and `page.js` file can be defined in the same folder. The layout will wrap the page.
+
+### Root Layout (Required)
+
+The root layout is defined at the top level of the `app` directory and applies to all routes. This layout enables you to modify the initial HTML returned from the server.
+
+```tsx filename="app/layout.tsx" switcher
+export default function RootLayout({
+ children,
+}: {
+ children: React.ReactNode
+}) {
+ return (
+
+ {children}
+
+ )
+}
+```
+
+```jsx filename="app/layout.js" switcher
+export default function RootLayout({ children }) {
+ return (
+
+ {children}
+
+ )
+}
+```
+
+> **Good to know:**
+>
+> - The `app` directory **must** include a root layout.
+> - 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).
+
+> **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).
+
+### Nesting Layouts
+
+Layouts defined inside a folder (e.g. `app/dashboard/layout.js`) apply to specific route segments (e.g. `acme.com/dashboard`) and render when those segments are active. By default, layouts in the file hierarchy are **nested**, which means they wrap child layouts via their `children` prop.
+
+
+
+```tsx filename="app/dashboard/layout.tsx" switcher
+export default function DashboardLayout({
+ children,
+}: {
+ children: React.ReactNode
+}) {
+ return {children}
+}
+```
+
+```jsx filename="app/dashboard/layout.js" switcher
+export default function DashboardLayout({ children }) {
+ return {children}
+}
+```
+
+If you were to combine the two layouts above, the root layout (`app/layout.js`) would wrap the dashboard layout (`app/dashboard/layout.js`), which would wrap route segments inside `app/dashboard/*`.
+
+The two layouts would be nested as such:
+
+
+
+You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts.
+
+## Templates
+
+Templates are similar to layouts in that they wrap each child layout or page. Unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is **not** preserved, and effects are re-synchronized.
+
+There may be cases where you need those specific behaviors, and templates would be a more suitable option than layouts. For example:
+
+- Enter/exit animations using CSS or animation libraries.
+- Features that rely on `useEffect` (e.g logging page views) and `useState` (e.g a per-page feedback form).
+- To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.
+
+> **Recommendation:** We recommend using Layouts unless you have a specific reason to use Template.
+
+A template can be defined by exporting a default React component from a `template.js` file. The component should accept a `children` prop which will be nested segments.
+
+
+
+```tsx filename="app/template.tsx" switcher
+export default function Template({ children }: { children: React.ReactNode }) {
+ return
{children}
+}
+```
+
+```jsx filename="app/template.js" switcher
+export default function Template({ children }) {
+ return
}>
+
+
+ Loading weather...}>
+
+
+
+ )
+}
+```
+
+```jsx filename="app/dashboard/page.js" switcher
+import { Suspense } from 'react'
+import { PostFeed, Weather } from './Components'
+
+export default function Posts() {
+ return (
+
+ Loading feed...}>
+
+
+ Loading weather...}>
+
+
+
+ )
+}
+```
+
+By using Suspense, you get the benefits of:
+
+1. **Streaming Server Rendering** - Progressively rendering HTML from the server to the client.
+2. **Selective Hydration** - React prioritizes what components to make interactive first based on user interaction.
+
+For more Suspense examples and use cases, please see the [React Documentation](https://react.dev/reference/react/Suspense).
+
+### SEO
+
+- Next.js will wait for data fetching inside [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) to complete before streaming UI to the client. This guarantees the first part of a streamed response includes `` tags.
+- Since streaming is server-rendered, it does not impact SEO. You can use the [Mobile Friendly Test](https://search.google.com/test/mobile-friendly) tool from Google to see how your page appears to Google's web crawlers and view the serialized HTML ([source](https://web.dev/rendering-on-the-web/#seo-considerations)).
diff --git a/docs/02-app/01-building-your-application/01-routing/07-error-handling.mdx b/docs/02-app/01-building-your-application/01-routing/07-error-handling.mdx
new file mode 100644
index 0000000000000..3f47ae2c6e570
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/07-error-handling.mdx
@@ -0,0 +1,215 @@
+---
+title: Error Handling
+description: Handle runtime errors by automatically wrapping route segments and their nested children in a React Error Boundary.
+---
+
+The `error.js` file convention allows you to gracefully handle runtime errors in [nested routes](/docs/app/building-your-application/routing#nested-routes).
+
+- Automatically wrap a route segment and its nested children in a [React Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary).
+- Create error UI tailored to specific segments using the file-system hierarchy to adjust granularity.
+- Isolate errors to affected segments while keeping the rest of the app functional.
+- Add functionality to attempt to recover from an error without a full page reload.
+
+Create error UI by adding an `error.js` file inside a route segment and exporting a React component:
+
+
+
+```tsx filename="app/dashboard/error.tsx" switcher
+'use client' // Error components must be Client Components
+
+import { useEffect } from 'react'
+
+export default function Error({
+ error,
+ reset,
+}: {
+ error: Error
+ reset: () => void
+}) {
+ useEffect(() => {
+ // Log the error to an error reporting service
+ console.error(error)
+ }, [error])
+
+ return (
+
+
Something went wrong!
+
+
+ )
+}
+```
+
+```jsx filename="app/dashboard/error.js" switcher
+'use client' // Error components must be Client Components
+
+import { useEffect } from 'react'
+
+export default function Error({ error, reset }) {
+ useEffect(() => {
+ // Log the error to an error reporting service
+ console.error(error)
+ }, [error])
+
+ return (
+
+
Something went wrong!
+
+
+ )
+}
+```
+
+### How `error.js` Works
+
+
+
+- `error.js` automatically creates an [React Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) that **wraps** a nested child segment or `page.js` component.
+- The React component exported from the `error.js` file is used as the **fallback** component.
+- If an error is thrown within the error boundary, the error is **contained**, and the fallback component is **rendered**.
+- When the fallback error component is active, layouts **above** the error boundary **maintain** their state and **remain** interactive, and the error component can display functionality to recover from the error.
+
+### Recovering From Errors
+
+The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.
+
+An error component can use the `reset()` function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render.
+
+```tsx filename="app/dashboard/error.tsx" switcher
+'use client'
+
+export default function Error({
+ error,
+ reset,
+}: {
+ error: Error
+ reset: () => void
+}) {
+ return (
+
+ )
+}
+```
+
+### Nested Routes
+
+React components created through [special files](/docs/app/building-your-application/routing#file-conventions) are rendered in a [specific nested hierarchy](/docs/app/building-your-application/routing#component-hierarchy).
+
+For example, a nested route with two segments that both include `layout.js` and `error.js` files are rendered in the following _simplified_ component hierarchy:
+
+
+
+The nested component hierarchy has implications for the behavior of `error.js` files across a nested route:
+
+- Errors bubble up to the nearest parent error boundary. This means an `error.js` file will handle errors for all its nested child segments. More or less granular error UI can be achieved by placing `error.js` files at different levels in the nested folders of a route.
+- 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.
+
+### Handling Errors in Layouts
+
+`error.js` boundaries do **not** catch errors thrown in `layout.js` or `template.js` components of the same segment. This [intentional hierarchy](#nested-routes) keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.
+
+To handle errors within a specific layout or template, place an `error.js` file in the layouts parent segment.
+
+To handle errors within the root layout or template, use a variation of `error.js` called `global-error.js`.
+
+### Handling Errors in Root Layouts
+
+The root `app/error.js` boundary does **not** catch errors thrown in the root `app/layout.js` or `app/template.js` component.
+
+To specifically handle errors in these root components, use a variation of `error.js` called `app/global-error.js` located in the root `app` directory.
+
+Unlike the root `error.js`, the `global-error.js` error boundary wraps the **entire** application, and its fallback component replaces the root layout when active. Because of this, it is important to note that `global-error.js` **must** define its own `` and `` tags.
+
+`global-error.js` is the least granular error UI and can be considered "catch-all" error handling for the whole application. It is unlikely to be triggered often as root components are typically less dynamic, and other `error.js` boundaries will catch most errors.
+
+Even if a `global-error.js` is defined, it is still recommended to define a root `error.js` whose fallback component will be rendered **within** the root layout, which includes globally shared UI and branding.
+
+```tsx filename="app/global-error.tsx" switcher
+'use client'
+
+export default function GlobalError({
+ error,
+ reset,
+}: {
+ error: Error
+ reset: () => void
+}) {
+ return (
+
+
+
+
+
+
+ )
+}
+```
+
+### Handling Server Errors
+
+If an error is thrown during [data fetching](/docs/app/building-your-application/data-fetching/fetching) or inside a Server Component, Next.js will forward the resulting `Error` object to the nearest `error.js` file as the `error` prop.
+
+When running `next dev`, the `error` will be serialized and forwarded from the Server Component to the client `error.js`. To ensure security when running `next start` in production, a generic error message is forwarded to `error` along with a `.digest` which contains a hash of the error message. This hash can be used to correspond to server logs.
diff --git a/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx b/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx
new file mode 100644
index 0000000000000..74252ebfddcd4
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/08-parallel-routes.mdx
@@ -0,0 +1,319 @@
+---
+title: Parallel Routes
+description: Simultaneously render one or more pages in the same view that can be navigated independently. A pattern for highly dynamic applications.
+---
+
+Parallel Routing allows you to simultaneously or conditionally render one or more pages in the same layout. For highly dynamic sections of an app, such as dashboards and feeds on social sites, Parallel Routing can be used to implement complex routing patterns.
+
+For example, you can simultaneously render the team and analytics pages.
+
+
+
+Parallel Routing allows you to define independent error and loading states for each route as they're being streamed in independently.
+
+
+
+Parallel Routing also allow you to conditionally render a slot based on certain conditions, such as authentication state. This enables fully separated code on the same URL.
+
+
+
+## Convention
+
+Parallel routes are created using named **slots**. Slots are defined with the `@folder` convention, and are passed to the same-level layout as props.
+
+> Slots are _not_ route segments and _do not affect the URL structure_. The file path `/@team/members` would be accessible at `/members`.
+
+For example, the following file structure defines two explicit slots: `@analytics` and `@team`.
+
+
+
+The folder structure above means that the component in `app/layout.js` now accepts the `@analytics` and `@team` slots props, and can render them in parallel alongside the `children` prop:
+
+```tsx filename="app/layout.tsx" switcher
+export default function Layout(props: {
+ children: React.ReactNode
+ analytics: React.ReactNode
+ team: React.ReactNode
+}) {
+ return (
+ <>
+ {props.children}
+ {props.team}
+ {props.analytics}
+ >
+ )
+}
+```
+
+```jsx filename="app/layout.js" switcher
+export default function Layout(props) {
+ return (
+ <>
+ {props.children}
+ {props.team}
+ {props.analytics}
+ >
+ )
+}
+```
+
+> **Good to know**: The `children` prop is an implicit slot that does not need to be mapped to a folder. This means `app/page.js` is equivalent to `app/@children/page.js`.
+
+## Unmatched Routes
+
+By default, the content rendered within a slot will match the current URL.
+
+In the case of an unmatched slot, the content that Next.js renders differs based on the routing technique and folder structure.
+
+### `default.js`
+
+You can define a `default.js` file to render as a fallback when Next.js cannot recover a slot's active state based on the current URL.
+
+Consider the following folder structure. The `@team` slot has a `settings` directory, but `@analytics` does not.
+
+
+
+If you were to navigate from the root `/` to `/settings`, the content that gets rendered is different based on the type of navigation and the availability of the `default.js` file.
+
+| | With `@analytics/default.js` | Without `@analytics/default.js` |
+| --------------- | ---------------------------------------------------- | ------------------------------------------------- |
+| Soft Navigation | `@team/settings/page.js` and `@analytics/page.js` | `@team/settings/page.js` and `@analytics/page.js` |
+| Hard Navigation | `@team/settings/page.js` and `@analytics/default.js` | 404 |
+
+#### Soft Navigation
+
+On a [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#soft-navigation) - Next.js will render the slot's previously active state, even if it doesn't match the current URL.
+
+#### Hard Navigation
+
+On a [hard navigation](/docs/app/building-your-application/routing/linking-and-navigating#hard-navigation) - a navigation that requires a full page reload - Next.js will first try to render the unmatched slot's `default.js` file. If that's not available, a 404 gets rendered.
+
+> The 404 for unmatched routes helps ensure that you don't accidentally render a route that shouldn't be parallel rendered.
+
+## `useSelectedLayoutSegment(s)`
+
+Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRoutesKey`, which allows you read the active route segment within that slot.
+
+```tsx filename="app/layout.tsx" switcher
+'use client'
+import { useSelectedLayoutSegment } from 'next/navigation'
+
+export default async function Layout(props: {
+ //...
+ authModal: React.ReactNode
+}) {
+ const loginSegments = useSelectedLayoutSegment('authModal')
+ // ...
+}
+```
+
+```jsx filename="app/layout.js" switcher
+'use client'
+import { useSelectedLayoutSegment } from 'next/navigation'
+
+export default async function Layout(props) {
+ const loginSegments = useSelectedLayoutSegment('authModal')
+ // ...
+}
+```
+
+When a user navigates to `@authModal/login`, or `/login` in the URL bar, `loginSegments` will be equal to the string `"login"`.
+
+## Examples
+
+### Modals
+
+Parallel Routing can be used to render modals.
+
+
+
+The `@authModal` slot renders a`` component that can be shown by navigating to a matching route, for example `/login`.
+
+```tsx filename="app/layout.tsx" switcher
+export default async function Layout(props: {
+ // ...
+ authModal: React.ReactNode
+}) {
+ return (
+ <>
+ {/* ... */}
+ {props.authModal}
+ >
+ )
+}
+```
+
+```jsx filename="app/layout.js" switcher
+export default async function Layout(props) {
+ return (
+ <>
+ {/* ... */}
+ {props.authModal}
+ >
+ )
+}
+```
+
+```tsx filename="app/@authModal/login/page.tsx" switcher
+import { Modal } from 'components/modal'
+
+export default function Login() {
+ return (
+
+
+ {/* ... */}
+
+ )
+}
+```
+
+To ensure that the contents of the modal don't get rendered when it's not active, you can create a `default.js` file that returns `null`.
+
+```tsx filename="app/@authModal/login/default.tsx" switcher
+export default function Default() {
+ return null
+}
+```
+
+```jsx filename="app/@authModal/login/default.js" switcher
+export default function Default() {
+ return null
+}
+```
+
+#### Dismissing a modal
+
+If a modal was initiated through client navigation, e.g. by using ``, you can dismiss the modal by calling `router.back()` or by using a `Link` component.
+
+```tsx filename="app/@authModal/login/page.tsx" highlight="5" switcher
+'use client'
+import { useRouter } from 'next/navigation'
+import { Modal } from 'components/modal'
+
+export default async function Login() {
+ const router = useRouter()
+ return (
+
+ router.back()}>Close modal
+
+ ...
+
+ )
+}
+```
+
+> More information on modals is covered in the [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) section.
+
+If you want to navigate elsewhere and dismiss a modal, you can also use a catch-all route.
+
+
+
+```tsx filename="app/@authModal/[...catchAll]/page.js"
+export default function CatchAll() {
+ return null
+}
+```
+
+> Catch-all routes take presedence over `default.js`.
+
+### Conditional Routes
+
+Parallel Routes can be used to implement conditional routing. For example, you can render a `@dashboard` or `@login` route depending on the authentication state.
+
+```tsx filename="app/layout.tsx" switcher
+import { getUser } from '@/lib/auth'
+
+export default function Layout({ params, dashboard, login }) {
+ const isLoggedIn = getUser()
+ return isLoggedIn ? dashboard : login
+}
+```
+
+```jsx filename="app/layout.js" switcher
+import { getUser } from '@/lib/auth'
+
+export default function Layout({ params, dashboard, login }) {
+ const isLoggedIn = getUser()
+ return isLoggedIn ? dashboard : login
+}
+```
+
+
diff --git a/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx b/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx
new file mode 100644
index 0000000000000..9ae0950ce4f88
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/09-intercepting-routes.mdx
@@ -0,0 +1,81 @@
+---
+title: Intercepting Routes
+description: Use intercepting routes to load a new route within the current layout while masking the browser URL, useful for advanced routing patterns such as modals.
+related:
+ title: Next Steps
+ description: Learn how to use modals with Intercepted and Parallel Routes.
+ links:
+ - app/building-your-application/routing/parallel-routes
+---
+
+Intercepting routes allows you to load a route within the current layout while keeping the context for the current page. This routing paradigm can be useful when you want to "intercept" a certain route to show a different route.
+
+For example, when clicking on a photo from within a feed, a modal overlaying the feed should show up with the photo. In this case, Next.js intercepts the `/feed` route and "masks" this URL to show `/photo/123` instead.
+
+
+
+However, when navigating to the photo directly by for example when clicking a shareable URL or by refreshing the page, the entire photo page should render instead of the modal. No route interception should occur.
+
+
+
+## Convention
+
+Intercepting routes can be defined with the `(..)` convention, which is similar to relative path convention `../` but for segments.
+
+You can use:
+
+- `(.)` to match segments on the **same level**
+- `(..)` to match segments **one level above**
+- `(..)(..)` to match segments **two levels above**
+- `(...)` to match segments from the **root** `app` directory
+
+For example, you can intercept the `photo` segment from within the `feed` segment by creating a `(..)photo` directory.
+
+
+
+> Note that the `(..)` convention is based on _route segments_, not the file-system.
+
+## Examples
+
+### Modals
+
+Intercepting Routes can be used together with [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) to create modals.
+
+Using this pattern to create modals overcomes some common challenges when working with modals, by allowing you to:
+
+- Make the modal content **shareable through a URL**
+- **Preserve context** when the page is refreshed, instead of closing the modal
+- **Close the modal on backwards navigation** rather than going to the previous route
+- **Reopen the modal on forwards navigation**
+
+
+
+> In the above example, the path to the `photo` segment can use the `(..)` matcher since `@modal` is a _slot_ and not a _segment_. This means that the `photo` route is only one _segment_ level higher, despite being two _file-system_ levels higher.
+
+Other examples could include opening a login modal in a top navbar while also having a dedicated `/login` page, or opening a shopping cart in a side modal.
+
+[View an example](https://github.com/vercel-labs/nextgram) of modals with Intercepted and Parallel Routes.
diff --git a/docs/02-app/01-building-your-application/01-routing/10-router-handlers.mdx b/docs/02-app/01-building-your-application/01-routing/10-router-handlers.mdx
new file mode 100644
index 0000000000000..3bc5b740e53d0
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/10-router-handlers.mdx
@@ -0,0 +1,589 @@
+---
+title: Route Handlers
+description: Create custom request handlers for a given route using the Web's Request and Response APIs.
+related:
+ title: API Reference
+ description: Learn more about the route.js file.
+ links:
+ - app/api-reference/file-conventions/route
+---
+
+Route Handlers allow you to create custom request handlers for a given route using the Web [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) APIs.
+
+
+
+> **Good to know:** Route Handlers are only available inside the `app` directory. They are the equivalent of [API Routes](/docs/pages/building-your-application/routing/api-routes) inside the `pages` directory meaning you **do not** need to use API Routes and Route Handlers together.
+
+## Convention
+
+Route Handlers are defined in a [`route.js|ts` file](/docs/app/api-reference/file-conventions/route) inside the `app` directory:
+
+```ts filename="app/api/route.ts" switcher
+export async function GET(request: Request) {}
+```
+
+```js filename="app/api/route.js" switcher
+export async function GET(request) {}
+```
+
+Route Handlers can be nested inside the `app` directory, similar to `page.js` and `layout.js`. But there **cannot** be a `route.js` file at the same route segment level as `page.js`.
+
+### Supported HTTP Methods
+
+The following [HTTP methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) are supported: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS`. If an unsupported method is called, Next.js will return a `405 Method Not Allowed` response.
+
+### Extended `NextRequest` and `NextResponse` APIs
+
+In addition to supporting native [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Next.js extends them with
+[`NextRequest`](/docs/app/api-reference/functions/next-request) and [`NextResponse`](/docs/app/api-reference/functions/next-response) to provide convenient helpers for advanced use cases.
+
+## Behavior
+
+### Static Route Handlers
+
+Route Handlers are [statically evaluated](/docs/app/building-your-application/data-fetching#static-and-dynamic-data-fetching) by default when using the `GET` method with the `Response` object.
+
+```ts filename="app/items/route.ts" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ })
+ const data = await res.json()
+
+ return NextResponse.json({ data })
+}
+```
+
+```js filename="app/items/route.js" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ })
+ const data = await res.json()
+
+ return NextResponse.json({ data })
+}
+```
+
+> **TypeScript Warning:** Although `Response.json()` is valid, native TypeScript types currently shows an error, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead.
+
+### Dynamic Route Handlers
+
+Route handlers are evaluated dynamically when:
+
+- Using the `Request` object with the `GET` method.
+- Using any of the other HTTP methods.
+- Using [Dynamic Functions](/#dynamic-functions) like `cookies` and `headers`.
+- The [Segment Config Options](#segment-config-options) manually specifies dynamic mode.
+
+For example:
+
+```ts filename="app/products/api/route.ts" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET(request: Request) {
+ const { searchParams } = new URL(request.url)
+ const id = searchParams.get('id')
+ const res = await fetch(`https://data.mongodb-api.com/product/${id}`, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ })
+ const product = await res.json()
+
+ return NextResponse.json({ product })
+}
+```
+
+```js filename="app/products/api/route.js" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET(request) {
+ const { searchParams } = new URL(request.url)
+ const id = searchParams.get('id')
+ const res = await fetch(`https://data.mongodb-api.com/product/${id}`, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ })
+ const product = await res.json()
+
+ return NextResponse.json({ product })
+}
+```
+
+Similarly, the `POST` method will cause the Route Handler to be evaluated dynamically.
+
+```ts filename="app/items/route.ts" switcher
+import { NextResponse } from 'next/server'
+
+export async function POST() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ body: JSON.stringify({ time: new Date().toISOString() }),
+ })
+
+ const data = await res.json()
+
+ return NextResponse.json(data)
+}
+```
+
+```js filename="app/items/route.js" switcher
+import { NextResponse } from 'next/server'
+
+export async function POST() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'API-Key': process.env.DATA_API_KEY,
+ },
+ body: JSON.stringify({ time: new Date().toISOString() }),
+ })
+
+ const data = await res.json()
+
+ return NextResponse.json(data)
+}
+```
+
+> **Note:** Previously, API Routes could have been used for use cases like handling form submissions. Route Handlers are likely not the solution for these uses cases. We will be recommending the use of [mutations](/docs/app/building-your-application/data-fetching/server-actions) for this when ready.
+
+### Route Resolution
+
+You can consider a `route` the lowest level routing primitive.
+
+- They **do not** participate in layouts or client-side navigations like `page`.
+- There **cannot** be a `route.js` file at the same route as `page.js`.
+
+| Page | Route | Result |
+| -------------------- | ------------------ | ---------------------------- |
+| `app/page.js` | `app/route.js` | Conflict |
+| `app/page.js` | `app/api/route.js` | Valid |
+| `app/[user]/page.js` | `app/api/route.js` | Valid |
+
+Each `route.js` or `page.js` file takes over all HTTP verbs for that route.
+
+```tsx filename="app/page.js"
+export default function Page() {
+ return
Hello, Next.js!
+}
+
+// ❌ Conflict
+// `app/route.js`
+export async function POST(request) {}
+```
+
+## Examples
+
+The following examples show how to combine Route Handlers with other Next.js APIs and features.
+
+### Revalidating Static Data
+
+You can [revalidate static data](/docs/app/building-your-application/data-fetching/revalidating) fetches using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching#revalidating-data) option:
+
+```ts filename="app/items/route.ts" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ next: { revalidate: 60 }, // Revalidate every 60 seconds
+ })
+ const data = await res.json()
+
+ return NextResponse.json(data)
+}
+```
+
+```js filename="app/items/route.js" switcher
+import { NextResponse } from 'next/server'
+
+export async function GET() {
+ const res = await fetch('https://data.mongodb-api.com/...', {
+ next: { revalidate: 60 }, // Revalidate every 60 seconds
+ })
+ const data = await res.json()
+
+ return NextResponse.json(data)
+}
+```
+
+Alternatively, you can use the [`revalidate` segment config option](/docs/app/api-reference/file-conventions/route-segment-config#revalidate):
+
+```ts
+export const revalidate = 60
+```
+
+### Dynamic Functions
+
+Route Handlers can be used with dynamic functions from Next.js, like [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers).
+
+#### Cookies
+
+You can read cookies with [`cookies`](/docs/app/api-reference/functions/cookies) from `next/headers`. This server function can be called directly in a Route Handler, or nested inside of another function.
+
+This `cookies` instance is read-only. To set cookies, you need to return a new `Response` using the [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) header.
+
+```ts filename="app/api/route.ts" switcher
+import { cookies } from 'next/headers'
+
+export async function GET(request: Request) {
+ const cookieStore = cookies()
+ const token = cookieStore.get('token')
+
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: { 'Set-Cookie': `token=${token}` },
+ })
+}
+```
+
+```js filename="app/api/route.js" switcher
+import { cookies } from 'next/headers'
+
+export async function GET(request) {
+ const cookieStore = cookies()
+ const token = cookieStore.get('token')
+
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: { 'Set-Cookie': `token=${token}` },
+ })
+}
+```
+
+Alternatively, you can use abstractions on top of the underlying Web APIs to read cookies ([`NextRequest`](/docs/app/api-reference/functions/next-request)):
+
+```ts filename="app/api/route.ts" switcher
+import { type NextRequest } from 'next/server'
+
+export async function GET(request: NextRequest) {
+ const token = request.cookies.get('token')
+}
+```
+
+```js filename="app/api/route.js" switcher
+export async function GET(request) {
+ const token = request.cookies.get('token')
+}
+```
+
+#### Headers
+
+You can read headers with [`headers`](/docs/app/api-reference/functions/headers) from `next/headers`. This server function can be called directly in a Route Handler, or nested inside of another function.
+
+This `headers` instance is read-only. To set headers, you need to return a new `Response` with new `headers`.
+
+```ts filename="app/api/route.ts" switcher
+import { headers } from 'next/headers'
+
+export async function GET(request: Request) {
+ const headersList = headers()
+ const referer = headersList.get('referer')
+
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: { referer: referer },
+ })
+}
+```
+
+```js filename="app/api/route.js" switcher
+import { headers } from 'next/headers'
+
+export async function GET(request) {
+ const headersList = headers()
+ const referer = headersList.get('referer')
+
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: { referer: referer },
+ })
+}
+```
+
+Alternatively, you can use abstractions on top of the underlying Web APIs to read headers ([`NextRequest`](/docs/app/api-reference/functions/next-request)):
+
+```ts filename="app/api/route.ts" switcher
+import { type NextRequest } from 'next/server'
+
+export async function GET(request: NextRequest) {
+ const requestHeaders = new Headers(request.headers)
+}
+```
+
+```js filename="app/api/route.js" switcher
+export async function GET(request) {
+ const requestHeaders = new Headers(request.headers)
+}
+```
+
+### Redirects
+
+```ts filename="app/api/route.ts" switcher
+import { redirect } from 'next/navigation'
+
+export async function GET(request: Request) {
+ redirect('https://nextjs.org/')
+}
+```
+
+```js filename="app/api/route.js" switcher
+import { redirect } from 'next/navigation'
+
+export async function GET(request) {
+ redirect('https://nextjs.org/')
+}
+```
+
+### Dynamic Route Segments
+
+> We recommend reading the [Defining Routes](/docs/app/building-your-application/routing/defining-routes) page before continuing.
+
+Route Handlers can use [Dynamic Segments](/docs/app/building-your-application/routing/dynamic-routes) to create request handlers from dynamic data.
+
+```ts filename="app/items/[slug]/route.ts" switcher
+export async function GET(
+ request: Request,
+ { params }: { params: { slug: string } }
+) {
+ const slug = params.slug // 'a', 'b', or 'c'
+}
+```
+
+```js filename="app/items/[slug]/route.js" switcher
+export async function GET(request, { params }) {
+ const slug = params.slug // 'a', 'b', or 'c'
+}
+```
+
+| Route | Example URL | `params` |
+| --------------------------- | ----------- | --------------- |
+| `app/items/[slug]/route.js` | `/items/a` | `{ slug: 'a' }` |
+| `app/items/[slug]/route.js` | `/items/b` | `{ slug: 'b' }` |
+| `app/items/[slug]/route.js` | `/items/c` | `{ slug: 'c' }` |
+
+### Streaming
+
+```ts filename="app/api/route.ts" switcher
+// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#convert_async_iterator_to_stream
+function iteratorToStream(iterator: any) {
+ return new ReadableStream({
+ async pull(controller) {
+ const { value, done } = await iterator.next()
+
+ if (done) {
+ controller.close()
+ } else {
+ controller.enqueue(value)
+ }
+ },
+ })
+}
+
+function sleep(time: number) {
+ return new Promise((resolve) => {
+ setTimeout(resolve, time)
+ })
+}
+
+const encoder = new TextEncoder()
+
+async function* makeIterator() {
+ yield encoder.encode('
')
+}
+
+export async function GET() {
+ const iterator = makeIterator()
+ const stream = iteratorToStream(iterator)
+
+ return new Response(stream)
+}
+```
+
+### Request Body
+
+You can read the `Request` body using the standard Web API methods:
+
+```ts filename="app/items/route.ts" switcher
+import { NextResponse } from 'next/server'
+
+export async function POST(request: Request) {
+ const res = await request.json()
+ return NextResponse.json({ res })
+}
+```
+
+```js filename="app/items/route.js" switcher
+import { NextResponse } from 'next/server'
+
+export async function POST(request) {
+ const res = await request.json()
+ return NextResponse.json({ res })
+}
+```
+
+### CORS
+
+You can set CORS headers on a `Response` using the standard Web API methods:
+
+```ts filename="app/api/route.ts" switcher
+export async function GET(request: Request) {
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ },
+ })
+}
+```
+
+```js filename="app/api/route.js" switcher
+export async function GET(request) {
+ return new Response('Hello, Next.js!', {
+ status: 200,
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ },
+ })
+}
+```
+
+### Edge and Node.js Runtimes
+
+Route Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as Pages and Layouts, they support long-awaited features like general-purpose [statically regenerated](/docs/app/building-your-application/data-fetching/revalidating) Route Handlers.
+
+You can use the `runtime` segment config option to specify the runtime:
+
+```ts
+export const runtime = 'edge' // 'nodejs' is the default
+```
+
+### Non-UI Responses
+
+You can use Route Handlers to return non-UI content. Note that [`sitemap.xml`](/docs/app/api-reference/file-conventions/metadata/sitemap#generate-a-sitemap), [`robots.txt`](/docs/app/api-reference/file-conventions/metadata/robots#generate-a-robots-file), [`app icons`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx), and [open graph images](/docs/app/api-reference/file-conventions/metadata/opengraph-image) all have built-in support.
+
+```ts filename="app/rss.xml/route.ts" switcher
+export async function GET() {
+ return new Response(`
+
+
+
+ Next.js Documentation
+ https://nextjs.org/docs
+ The React Framework for the Web
+
+
+`)
+}
+```
+
+```js filename="app/rss.xml/route.js" switcher
+export async function GET() {
+ return new Response(`
+
+
+
+ Next.js Documentation
+ https://nextjs.org/docs
+ The React Framework for the Web
+
+
+`)
+}
+```
+
+### Segment Config Options
+
+Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as pages and layouts.
+
+```ts filename="app/items/route.ts" switcher
+export const dynamic = 'auto'
+export const dynamicParams = true
+export const revalidate = false
+export const fetchCache = 'auto'
+export const runtime = 'nodejs'
+export const preferredRegion = 'auto'
+```
+
+```js filename="app/items/route.js" switcher
+export const dynamic = 'auto'
+export const dynamicParams = true
+export const revalidate = false
+export const fetchCache = 'auto'
+export const runtime = 'nodejs'
+export const preferredRegion = 'auto'
+```
+
+See the [API reference](/docs/app/api-reference/file-conventions/route-segment-config) for more details.
diff --git a/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx
new file mode 100644
index 0000000000000..c85bbe75f7833
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx
@@ -0,0 +1,326 @@
+---
+title: Middleware
+description: Learn how to use Middleware to run code before a request is completed.
+---
+
+Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
+
+Middleware runs before cached content and routes are matched. See [Matching Paths](#matching-paths) for more details.
+
+## Convention
+
+Use the file `middleware.ts` (or `.js`) in the root of your project to define Middleware. For example, at the same level as `pages` or `app`, or inside `src` if applicable.
+
+## Example
+
+```ts filename="middleware.ts"
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+
+// This function can be marked `async` if using `await` inside
+export function middleware(request: NextRequest) {
+ return NextResponse.redirect(new URL('/home', request.url))
+}
+
+// See "Matching Paths" below to learn more
+export const config = {
+ matcher: '/about/:path*',
+}
+```
+
+## Matching Paths
+
+Middleware will be invoked for **every route in your project**. The following is the execution order:
+
+1. `headers` from `next.config.js`
+2. `redirects` from `next.config.js`
+3. Middleware (`rewrites`, `redirects`, etc.)
+4. `beforeFiles` (`rewrites`) from `next.config.js`
+5. Filesystem routes (`public/`, `_next/static/`, `pages/`, `app/`, etc.)
+6. `afterFiles` (`rewrites`) from `next.config.js`
+7. Dynamic Routes (`/blog/[slug]`)
+8. `fallback` (`rewrites`) from `next.config.js`
+
+There are two ways to define which paths Middleware will run on:
+
+1. [Custom matcher config](#matcher)
+2. [Conditional statements](#conditional-statements)
+
+### Matcher
+
+`matcher` allows you to filter Middleware to run on specific paths.
+
+```js filename="middleware.js"
+export const config = {
+ matcher: '/about/:path*',
+}
+```
+
+You can match a single path or multiple paths with an array syntax:
+
+```js filename="middleware.js"
+export const config = {
+ matcher: ['/about/:path*', '/dashboard/:path*'],
+}
+```
+
+The `matcher` config allows full regex so matching like negative lookaheads or character matching is supported. An example of a negative lookahead to match all except specific paths can be seen here:
+
+```js filename="middleware.js"
+export const config = {
+ matcher: [
+ /*
+ * Match all request paths except for the ones starting with:
+ * - api (API routes)
+ * - _next/static (static files)
+ * - _next/image (image optimization files)
+ * - favicon.ico (favicon file)
+ */
+ '/((?!api|_next/static|_next/image|favicon.ico).*)',
+ ],
+}
+```
+
+> **Note**: The `matcher` values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored.
+
+Configured matchers:
+
+1. MUST start with `/`
+2. Can include named parameters: `/about/:path` matches `/about/a` and `/about/b` but not `/about/a/c`
+3. Can have modifiers on named parameters (starting with `:`): `/about/:path*` matches `/about/a/b/c` because `*` is _zero or more_. `?` is _zero or one_ and `+` _one or more_
+4. Can use regular expression enclosed in parenthesis: `/about/(.*)` is the same as `/about/:path*`
+
+Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1) documentation.
+
+> **Note**: For backward compatibility, Next.js always considers `/public` as `/public/index`. Therefore, a matcher of `/public/:path` will match.
+
+### Conditional Statements
+
+```ts filename="middleware.ts"
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+
+export function middleware(request: NextRequest) {
+ if (request.nextUrl.pathname.startsWith('/about')) {
+ return NextResponse.rewrite(new URL('/about-2', request.url))
+ }
+
+ if (request.nextUrl.pathname.startsWith('/dashboard')) {
+ return NextResponse.rewrite(new URL('/dashboard/user', request.url))
+ }
+}
+```
+
+## NextResponse
+
+The `NextResponse` API allows you to:
+
+- `redirect` the incoming request to a different URL
+- `rewrite` the response by displaying a given URL
+- Set request headers for API Routes, `getServerSideProps`, and `rewrite` destinations
+- Set response cookies
+- Set response headers
+
+To produce a response from Middleware, you can:
+
+1. `rewrite` to a route ([Page](/docs/pages/building-your-application/routing/pages-and-layouts) or [Edge API Route](/docs/pages/building-your-application/routing/api-routes)) that produces a response
+2. return a `NextResponse` directly. See [Producing a Response](#producing-a-response)
+
+## Using Cookies
+
+Cookies are regular headers. On a `Request`, they are stored in the `Cookie` header. On a `Response` they are in the `Set-Cookie` header. Next.js provides a convenient way to access and manipulate these cookies through the `cookies` extension on `NextRequest` and `NextResponse`.
+
+1. For incoming requests, `cookies` comes with the following methods: `get`, `getAll`, `set`, and `delete` cookies. You can check for the existence of a cookie with `has` or remove all cookies with `clear`.
+2. For outgoing responses, `cookies` have the following methods `get`, `getAll`, `set`, and `delete`.
+
+```ts filename="middleware.ts"
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+
+export function middleware(request: NextRequest) {
+ // Assume a "Cookie:nextjs=fast" header to be present on the incoming request
+ // Getting cookies from the request using the `RequestCookies` API
+ let cookie = request.cookies.get('nextjs')?.value
+ console.log(cookie) // => 'fast'
+ const allCookies = request.cookies.getAll()
+ console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
+
+ request.cookies.has('nextjs') // => true
+ request.cookies.delete('nextjs')
+ request.cookies.has('nextjs') // => false
+
+ // Setting cookies on the response using the `ResponseCookies` API
+ const response = NextResponse.next()
+ response.cookies.set('vercel', 'fast')
+ response.cookies.set({
+ name: 'vercel',
+ value: 'fast',
+ path: '/',
+ })
+ cookie = response.cookies.get('vercel')
+ console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
+ // The outgoing response will have a `Set-Cookie:vercel=fast;path=/test` header.
+
+ return response
+}
+```
+
+## Setting Headers
+
+You can set request and response headers using the `NextResponse` API (setting _request_ headers is available since Next.js v13.0.0).
+
+```ts filename="middleware.ts" switcher
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+
+export function middleware(request: NextRequest) {
+ // Clone the request headers and set a new header `x-hello-from-middleware1`
+ const requestHeaders = new Headers(request.headers)
+ requestHeaders.set('x-hello-from-middleware1', 'hello')
+
+ // You can also set request headers in NextResponse.rewrite
+ const response = NextResponse.next({
+ request: {
+ // New request headers
+ headers: requestHeaders,
+ },
+ })
+
+ // Set a new response header `x-hello-from-middleware2`
+ response.headers.set('x-hello-from-middleware2', 'hello')
+ return response
+}
+```
+
+```js filename="middleware.js" switcher
+import { NextResponse } from 'next/server'
+
+export function middleware(request) {
+ // Clone the request headers and set a new header `x-hello-from-middleware1`
+ const requestHeaders = new Headers(request.headers)
+ requestHeaders.set('x-hello-from-middleware1', 'hello')
+
+ // You can also set request headers in NextResponse.rewrite
+ const response = NextResponse.next({
+ request: {
+ // New request headers
+ headers: requestHeaders,
+ },
+ })
+
+ // Set a new response header `x-hello-from-middleware2`
+ response.headers.set('x-hello-from-middleware2', 'hello')
+ return response
+}
+```
+
+> **Note**: Avoid setting large headers as it might cause [431 Request Header Fields Too Large](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/431) error depending on your backend web server configuration.
+
+## Producing a Response
+
+You can respond from Middleware directly by returning a `Response` or `NextResponse` instance. (This is available since [Next.js v13.1.0](https://nextjs.org/blog/next-13-1#nextjs-advanced-middleware))
+
+```ts filename="middleware.ts" switcher
+import { NextRequest, NextResponse } from 'next/server'
+import { isAuthenticated } from '@lib/auth'
+
+// Limit the middleware to paths starting with `/api/`
+export const config = {
+ matcher: '/api/:function*',
+}
+
+export function middleware(request: NextRequest) {
+ // Call our authentication function to check the request
+ if (!isAuthenticated(request)) {
+ // Respond with JSON indicating an error message
+ return new NextResponse(
+ JSON.stringify({ success: false, message: 'authentication failed' }),
+ { status: 401, headers: { 'content-type': 'application/json' } }
+ )
+ }
+}
+```
+
+```js filename="middleware.js" switcher
+import { NextResponse } from 'next/server'
+import { isAuthenticated } from '@lib/auth'
+
+// Limit the middleware to paths starting with `/api/`
+export const config = {
+ matcher: '/api/:function*',
+}
+
+export function middleware(request) {
+ // Call our authentication function to check the request
+ if (!isAuthenticated(request)) {
+ // Respond with JSON indicating an error message
+ return new NextResponse(
+ JSON.stringify({ success: false, message: 'authentication failed' }),
+ { status: 401, headers: { 'content-type': 'application/json' } }
+ )
+ }
+}
+```
+
+## Advanced Middleware Flags
+
+In `v13.1` of Next.js two additional flags were introduced for middleware, `skipMiddlewareUrlNormalize` and `skipTrailingSlashRedirect` to handle advanced use cases.
+
+`skipTrailingSlashRedirect` allows disabling Next.js default redirects for adding or removing trailing slashes allowing custom handling inside middleware which can allow maintaining the trailing slash for some paths but not others allowing easier incremental migrations.
+
+```js filename="next.config.js"
+module.exports = {
+ skipTrailingSlashRedirect: true,
+}
+```
+
+```js filename="middleware.js"
+const legacyPrefixes = ['/docs', '/blog']
+
+export default async function middleware(req) {
+ const { pathname } = req.nextUrl
+
+ if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
+ return NextResponse.next()
+ }
+
+ // apply trailing slash handling
+ if (
+ !pathname.endsWith('/') &&
+ !pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
+ ) {
+ req.nextUrl.pathname += '/'
+ return NextResponse.redirect(req.nextUrl)
+ }
+}
+```
+
+`skipMiddlewareUrlNormalize` allows disabling the URL normalizing Next.js does to make handling direct visits and client-transitions the same. There are some advanced cases where you need full control using the original URL which this unlocks.
+
+```js filename="next.config.js"
+module.exports = {
+ skipMiddlewareUrlNormalize: true,
+}
+```
+
+```js filename="middleware.js"
+export default async function middleware(req) {
+ const { pathname } = req.nextUrl
+
+ // GET /_next/data/build-id/hello.json
+
+ console.log(pathname)
+ // with the flag this now /_next/data/build-id/hello.json
+ // without the flag this would be normalized to /hello
+}
+```
+
+## Version History
+
+| Version | Changes |
+| --------- | --------------------------------------------------------------------------------------------- |
+| `v13.1.0` | Advanced Middleware flags added |
+| `v13.0.0` | Middleware can modify request headers, response headers, and send responses |
+| `v12.2.0` | Middleware is stable, please see the [upgrade guide](/docs/messages/middleware-upgrade-guide) |
+| `v12.0.9` | Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) |
+| `v12.0.0` | Middleware (Beta) added |
diff --git a/docs/02-app/01-building-your-application/01-routing/12-colocation.mdx b/docs/02-app/01-building-your-application/01-routing/12-colocation.mdx
new file mode 100644
index 0000000000000..67500ffc3eeca
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/12-colocation.mdx
@@ -0,0 +1,180 @@
+---
+title: Project Organization and File Colocation
+nav_title: Project Organization
+description: Learn how to organize your Next.js project and colocate files.
+related:
+ links:
+ - app/building-your-application/routing/defining-routes
+ - app/building-your-application/routing/route-groups
+ - app/building-your-application/configuring/src-directory
+ - app/building-your-application/configuring/absolute-imports-and-module-aliases
+---
+
+Apart from [routing folder and file conventions](/docs/getting-started/project-structure#app-routing-conventions), Next.js is **unopinionated** about how you organize and colocate your project files.
+
+This page shares default behavior and features you can use to organize your project.
+
+- [Safe colocation by default](#safe-colocation-by-default)
+- [Project organization features](#project-organization-features)
+- [Project organization strategies](#project-organization-strategies)
+
+## Safe colocation by default
+
+In the `app` directory, [nested folder hierarchy](/docs/app/building-your-application/routing#route-segments) defines route structure.
+
+Each folder represents a route segment that is mapped to a corresponding segment in a URL path.
+
+However, even though route structure is defined through folders, a route is **not publically accessible** until a `page.js` or `route.js` file is added to a route segment.
+
+
+
+And, even when a route is made publically accessible, only the **content returned** by `page.js` or `route.js` is sent to the client.
+
+
+
+This means that **project files** can be **safely colocated** inside route segments in the `app` directory without accidentally being routable.
+
+
+
+> **Good to know**:
+>
+> - This is different from the `pages` directory, where any file in `pages` is considered a route.
+> - While you **can** colocate your project files in `app` you don't **have** to. If you prefer, you can [keep them outside the `app` directory](#store-project-files-outside-of-app).
+
+## Project organization features
+
+Next.js provides several features to help you organize your project.
+
+### Private Folders
+
+Private folders can be created by prefixing a folder with an underscore: `_folderName`
+
+This indicates the folder is a private implementation detail and should not be considered by the routing system, thereby **opting the folder and all its subfolders** out of routing.
+
+
+
+Since files in the `app` directory can be [safely colocated by default](#safe-colocation-by-default), private folders are not required for colocation. However, they can be useful for:
+
+- Separating UI logic from routing logic.
+- Consistently organizing internal files across a project and the Next.js ecosystem.
+- Sorting and grouping files in code editors.
+- Avoiding potential naming conflicts with future Next.js file conventions.
+
+> **Good to know**
+>
+> - While not a framework convention, you might also consider marking files outside private folders as "private" using the same underscore pattern.
+> - You can create URL segments that start with an underscore by prefixing the folder name with `%5F` (the URL-encoded form of an underscore): `%5FfolderName`.
+> - If you don't use private folders, it would be helpful to know Next.js [special file conventions](/docs/getting-started/project-structure#routing-files) to prevent unexpected naming conflicts.
+
+### Route Groups
+
+Route groups can be created by wrapping a folder in parenthesis: `(folderName)`
+
+This indicates the folder is for organizational purposes and should **not be included** in the route's URL path.
+
+
+
+Route groups are useful for:
+
+- [Organizing routes into groups](/docs/app/building-your-application/routing/route-groups#organize-routes-without-affecting-the-url-path) e.g. by site section, intent, or team.
+- Enabling nested layouts in the same route segment level:
+ - [Creating multiple nested layouts in the same segment, including multiple root layouts](/docs/app/building-your-application/routing/route-groups#creating-multiple-root-layouts)
+ - [Adding a layout to a subset of routes in a common segment](/docs/app/building-your-application/routing/route-groups#opting-specific-segments-into-a-layout)
+
+### `src` Directory
+
+Next.js supports storing application code (including `app`) inside an optional [`src` directory](/docs/app/building-your-application/configuring/src-directory). This separates application code from project configuration files which mostly live in the root of a project.
+
+
+
+### Module Path Aliases
+
+Next.js supports [Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) which make it easier to read and maintain imports across deeply nested project files.
+
+```tsx filename="app/dashboard/settings/analytics/page.js"
+// before
+import { Button } from '../../../components/button'
+
+// after
+import { Button } from '@/components/button'
+```
+
+## Project organization strategies
+
+There is no "right" or "wrong" way when it comes to organizing your own files and folders in a Next.js project.
+
+The following section lists a very high-level overview of common strategies. The simplest takeaway is to choose a strategy that works for you and your team and be consistent across the project.
+
+> **Note:** In our examples below, we're using `components` and `lib` folders as generalized placeholders, their naming has no special framework significance and your projects might use other folders like `ui`, `utils`, `hooks`, `styles`, etc.
+
+### Store project files outside of `app`
+
+This strategy stores all application code in shared folders in the **root of your project** and keeps the `app` directory purely for routing purposes.
+
+
+
+### Store project files in top-level folders inside of `app`
+
+This strategy stores all application code in shared folders in the **root of the `app` directory**.
+
+
+
+### Split project files by feature or route
+
+This strategy stores globally shared application code in the root `app` directory and **splits** more specific application code into the route segments that use them.
+
+
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
new file mode 100644
index 0000000000000..5e1aa1eb309b8
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/13-internationalization.mdx
@@ -0,0 +1,153 @@
+---
+title: Internationalization
+description: Add support for multiple languages with internationalized routing and localized content.
+---
+
+Next.js enables you to configure the routing and rendering of content to support multiple languages. Making your site adaptive to different locales includes translated content (localization) and internationalized routes.
+
+## Terminology
+
+- **Locale:** An identifier for a set of language and formatting preferences. This usually includes the preferred language of the user and possibly their geographic region.
+ - `en-US`: English as spoken in the United States
+ - `nl-NL`: Dutch as spoken in the Netherlands
+ - `nl`: Dutch, no specific region
+
+## Routing Overview
+
+It’s recommended to use the user’s language preferences in the browser to select which locale to use. Changing your preferred language will modify the incoming `Accept-Language` header to your application.
+
+For example, using the following libraries, you can look at an incoming `Request` to determine which locale to select, based on the `Headers`, locales you plan to support, and the default locale.
+
+```jsx filename="middleware.js"
+import { match } from '@formatjs/intl-localematcher'
+import Negotiator from 'negotiator'
+
+let headers = { 'accept-language': 'en-US,en;q=0.5' }
+let languages = new Negotiator({ headers }).languages()
+let locales = ['en-US', 'nl-NL', 'nl']
+let defaultLocale = 'en-US'
+
+match(languages, locales, defaultLocale) // -> 'en-US'
+```
+
+Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/building-your-application/routing/middleware).
+
+```jsx filename="middleware.js"
+import { NextResponse } from 'next/server'
+
+let locales = ['en-US', 'nl-NL', 'nl']
+
+// Get the preferred locale, similar to above or using a library
+function getLocale(request) { ... }
+
+export function middleware(request) {
+ // Check if there is any supported locale in the pathname
+ const pathname = request.nextUrl.pathname
+ const pathnameIsMissingLocale = locales.every(
+ (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
+ )
+
+ // Redirect if there is no locale
+ if (pathnameIsMissingLocale) {
+ const locale = getLocale(request)
+
+ // e.g. incoming request is /products
+ // The new URL is now /en-US/products
+ return NextResponse.redirect(
+ new URL(`/${locale}/${pathname}`, request.url)
+ )
+ }
+}
+
+export const config = {
+ matcher: [
+ // Skip all internal paths (_next)
+ '/((?!_next).*)',
+ // Optional: only run on root (/) URL
+ // '/'
+ ],
+}
+```
+
+Finally, ensure all special files inside `app/` are nested under `app/[lang]`. This enables the Next.js router to dynamically handle different locales in the route, and forward the `lang` parameter to every layout and page. For example:
+
+```jsx filename="app/[lang]/page.js"
+// You now have access to the current locale
+// e.g. /en-US/products -> `lang` is "en-US"
+export default async function Page({ params: { lang } }) {
+ return ...
+}
+```
+
+The root layout can also be nested in the new folder (e.g. `app/[lang]/layout.js`).
+
+## Localization
+
+Changing displayed content based on the user’s preferred locale, or localization, is not something specific to Next.js. The patterns described below would work the same with any web application.
+
+Let’s assume we want to support both English and Dutch content inside our application. We might maintain two different “dictionaries”, which are objects that give us a mapping from some key to a localized string. For example:
+
+```jsx filename="dictionaries/en.json"
+{
+ "products": {
+ "cart": "Add to Cart"
+ }
+}
+```
+
+```jsx filename="dictionaries/nl.json"
+{
+ "products": {
+ "cart": "Toevoegen aan Winkelwagen"
+ }
+}
+```
+
+We can then create a `getDictionary` function to load the translations for the requested locale:
+
+```jsx filename="app/[lang]/dictionaries.js"
+import 'server-only'
+
+const dictionaries = {
+ en: () => import('./dictionaries/en.json').then((module) => module.default),
+ nl: () => import('./dictionaries/nl.json').then((module) => module.default),
+}
+
+export const getDictionary = async (locale) => dictionaries[locale]()
+```
+
+Given the currently selected language, we can fetch the dictionary inside of a layout or page.
+
+```jsx filename="app/[lang]/page.js"
+import { getDictionary } from './dictionaries'
+
+export default async function Page({ params: { lang } }) {
+ const dict = await getDictionary(lang) // en
+ return // Add to Cart
+}
+```
+
+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.
+
+## Static Generation
+
+To generate static routes for a given set of locales, we can use `generateStaticParams` with any page or layout. This can be global, for example, in the root layout:
+
+```jsx filename="app/[lang]/layout.js"
+export async function generateStaticParams() {
+ return [{ lang: 'en-US' }, { lang: 'de' }]
+}
+
+export default function Root({ children, params }) {
+ return (
+
+ {children}
+
+ )
+}
+```
+
+## Examples
+
+- [Minimal i18n routing and translations](https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing)
+- [next-intl](https://next-intl-docs.vercel.app/docs/next-13)
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
new file mode 100644
index 0000000000000..143af084afa89
--- /dev/null
+++ b/docs/02-app/01-building-your-application/01-routing/index.mdx
@@ -0,0 +1,184 @@
+---
+title: Routing Fundamentals
+nav_title: Routing
+description: Learn the fundamentals of routing for front-end applications.
+---
+
+The skeleton of every application is routing. This page will introduce you to the **fundamental concepts** of routing for the web and how to handle routing in Next.js.
+
+## Terminology
+
+First, you will see these terms being used throughout the documentation. Here's a quick reference:
+
+
+
+- **Tree:** A convention for visualizing a hierarchical structure. For example, a component tree with parent and children components, a folder structure, etc.
+- **Subtree:** Part of a tree, starting at a new root (first) and ending at the leaves (last).
+- **Root**: The first node in a tree or subtree, such as a root layout.
+- **Leaf:** Nodes in a subtree that have no children, such as the last segment in a URL path.
+
+
+
+- **URL Segment:** Part of the URL path delimited by slashes.
+- **URL Path:** Part of the URL that comes after the domain (composed of segments).
+
+## 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.
+
+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.
+
+> **Good to know:** The App Router takes priority over the Pages Router. Routes across directories should not resolve to the same URL path and will cause a build-time error to prevent a conflict.
+
+
+
+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).
+
+> **Recommendation:** Check out the [Server and Client Components](/docs/getting-started/react-essentials) page if you're new to Server Components.
+
+## Roles of Folders and Files
+
+Next.js uses a file-system based router where:
+
+- **Folders** are used to define routes. A route is a single path of nested folders, following the file-system hierarchy from the **root folder** down to a final **leaf folder** that includes a `page.js` file. See [Defining Routes](/docs/app/building-your-application/routing/defining-routes).
+- **Files** are used to create UI that is shown for a route segment. See [special files](#file-conventions).
+
+## Route Segments
+
+Each folder in a route represents a **route segment**. Each route segment is mapped to a corresponding **segment** in a **URL path**.
+
+
+
+## Nested Routes
+
+To create a nested route, you can nest folders inside each other. For example, you can add a new `/dashboard/settings` route by nesting two new folders in the `app` directory.
+
+The `/dashboard/settings` route is composed of three segments:
+
+- `/` (Root segment)
+- `dashboard` (Segment)
+- `settings` (Leaf segment)
+
+## File Conventions
+
+Next.js provides a set of special files to create UI with specific behavior in nested routes:
+
+| | |
+| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| [`layout`](/docs/app/building-your-application/routing/pages-and-layouts#layouts) | Shared UI for a segment and its children |
+| [`page`](/docs/app/building-your-application/routing/pages-and-layouts#pages) | Unique UI of a route and make routes publicly accessible |
+| [`loading`](/docs/app/building-your-application/routing/loading-ui-and-streaming) | Loading UI for a segment and its children |
+| [`not-found`](/docs/app/api-reference/file-conventions/not-found) | Not found UI for a segment and its children |
+| [`error`](/docs/app/building-your-application/routing/error-handling) | Error UI for a segment and its children |
+| [`global-error`](/docs/app/building-your-application/routing/error-handling) | Global Error UI |
+| [`route`](/docs/app/building-your-application/routing/router-handlers) | Server-side API endpoint |
+| [`template`](/docs/app/building-your-application/routing/pages-and-layouts#templates) | Specialized re-rendered Layout UI |
+| [`default`](/docs/app/api-reference/file-conventions/default) | Fallback UI for [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) |
+
+> **Good to know:** `.js`, `.jsx`, or `.tsx` file extensions can be used for special files.
+
+## Component Hierarchy
+
+The React components defined in special files of a route segment are rendered in a specific hierarchy:
+
+- `layout.js`
+- `template.js`
+- `error.js` (React error boundary)
+- `loading.js` (React suspense boundary)
+- `not-found.js` (React error boundary)
+- `page.js` or nested `layout.js`
+
+
+
+In a nested route, the components of a segment will be nested **inside** the components of its parent segment.
+
+
+
+## Colocation
+
+In addition to special files, you have the option to colocate your own files (e.g. components, styles, tests etc) inside folders in the `app` directory.
+
+This is because while folders define routes, only the contents returned by `page.js` or `route.js` are publically addressable.
+
+
+
+Learn more about [Project Organization and Colocation](/docs/app/building-your-application/routing/colocation).
+
+## Server-Centric Routing with Client-side Navigation
+
+Unlike the `pages` directory which uses client-side routing, the App Router uses **server-centric routing** to align with [Server Components](/docs/getting-started/react-essentials#server-components) and [data fetching on the server](/docs/app/building-your-application/data-fetching/fetching). With server-centric routing, the client does not have to download a route map and the same request for Server Components can be used to look up routes. This optimization is useful for all applications, but has a larger impact on applications with many routes.
+
+Although routing is server-centric, the router uses **client-side navigation** with the [Link Component](/docs/app/building-your-application/routing/linking-and-navigating#link-component) - resembling the behavior of a Single-Page Application. This means when a user navigates to a new route, the browser will not reload the page. Instead, the URL will be updated and Next.js will [only render the segments that change](#partial-rendering).
+
+Additionally, as users navigate around the app, the router will store the result of the React Server Component payload in an **in-memory client-side cache**. The cache is split by route segments which allows invalidation at any level and ensures consistency across [React's concurrent renders](https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react). This means that for certain cases, the cache of a previously fetched segment can be re-used, further improving performance.
+
+Learn more about [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating).
+
+## Partial Rendering
+
+When navigating between sibling routes (e.g. `/dashboard/settings` and `/dashboard/analytics` below), Next.js will only fetch and render the layouts and pages in routes that change. It will **not** re-fetch or re-render anything above the segments in the subtree. This means that in routes that share a layout, the layout will be preserved when a user navigates between sibling pages.
+
+
+
+Without partial rendering, each navigation would cause the full page to re-render on the server. Rendering only the segment that’s updating reduces the amount of data transferred and execution time, leading to improved performance.
+
+## Advanced Routing Patterns
+
+The App Router also provides a set conventions to help you implement more advanced routing patterns. These include:
+
+- [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes): Allow you to simultaneously show two or more pages in the same view that can be navigated independently. You can use them for split views that have their own sub-navigation. E.g. Dashboards.
+- [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes): Allow you to intercept a route and show it in the context of another route. You can use these when keeping the context for the current page is important. E.g. Seeing all tasks while editing one task or expanding a photo in a feed.
+
+These patterns allow you to build richer and more complex UIs, democratizing features that were historically complex for small teams and individual developers to implement.
+
+## Next Steps
+
+Now that you understand the fundamentals of routing in Next.js, follow the links below to create your first routes:
diff --git a/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx b/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx
new file mode 100644
index 0000000000000..e9d38195b84a3
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-rendering/01-static-and-dynamic-rendering.mdx
@@ -0,0 +1,56 @@
+---
+title: Static and Dynamic Rendering
+nav_title: Static and Dynamic
+description: Learn about static and dynamic rendering in Next.js.
+---
+
+In Next.js, a route can be statically or dynamically rendered.
+
+- In a **static** route, components are rendered on the server at build time. The result of the work is cached and reused on subsequent requests.
+- In a **dynamic** route, components are rendered on the server at request time.
+
+## Static Rendering (Default)
+
+By default, Next.js statically renders routes to improve performance. This means all the rendering work is done ahead of time and can be served from a Content Delivery Network (CDN) geographically closer to the user.
+
+## Static Data Fetching (Default)
+
+By default, Next.js will cache the result of `fetch()` requests that do not specifically opt out of caching behavior. This means that fetch requests that do not set a `cache` option will use the `force-cache` option.
+
+If any fetch requests in the route use the `revalidate` option, the route will be re-rendered statically during revalidation.
+
+To learn more about caching data fetching requests, see the [Caching and Revalidating](/docs/app/building-your-application/data-fetching/caching) page.
+
+## Dynamic Rendering
+
+During static rendering, if a dynamic function or a dynamic `fetch()` request (no caching) is discovered, Next.js will switch to dynamically rendering the whole route at request time. Any cached data requests can still be re-used during dynamic rendering.
+
+This table summarizes how [dynamic functions](#dynamic-functions) and [caching](#static-data-fetching-default) affect the rendering behavior of a route:
+
+| Data Fetching | Dynamic Functions | Rendering |
+| --------------- | ----------------- | --------- |
+| Static (Cached) | No | Static |
+| Static (Cached) | Yes | Dynamic |
+| Not Cached | No | Dynamic |
+| Not Cached | Yes | Dynamic |
+
+Note how dynamic functions always opt the route into dynamic rendering, regardless of whether the data fetching is cached or not. In other words, static rendering is dependent not only on the data fetching behavior, but also on the dynamic functions used in the route.
+
+> **Note:** In the future, Next.js will introduce hybrid server-side rendering where layouts and pages in a route can be independently statically or dynamically rendered, instead of the whole route.
+
+### Dynamic Functions
+
+Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are:
+
+- Using [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) in a Server Component will opt the whole route into dynamic rendering at request time.
+- Using [`useSearchParams()`](/docs/app/api-reference/functions/use-params) in Client Components will skip static rendering and instead render all Client Components up to the nearest parent Suspense boundary on the client.
+ - We recommend wrapping the Client Component that uses `useSearchParams()` in a `` boundary. This will allow any Client Components above it to be statically rendered. [Example](/docs/app/api-reference/functions/use-search-params#static-rendering).
+- Using the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) [Pages](/docs/app/api-reference/file-conventions/page) prop will opt the page into dynamic rendering at request time.
+
+## Dynamic Data Fetching
+
+Dynamic data fetches are `fetch()` requests that specifically opt out of caching behavior by setting the `cache` option to `'no-store'` or `revalidate` to `0`.
+
+The caching options for all `fetch` requests in a layout or page can also be set using the [segment config](/docs/app/api-reference/file-conventions/route-segment-config) object.
+
+To learn more about Dynamic Data Fetching, see the [Data Fetching](/docs/app/building-your-application/data-fetching/fetching) page.
diff --git a/docs/02-app/01-building-your-application/02-rendering/02-edge-and-nodejs-runtimes.mdx b/docs/02-app/01-building-your-application/02-rendering/02-edge-and-nodejs-runtimes.mdx
new file mode 100644
index 0000000000000..55b798b6693bd
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-rendering/02-edge-and-nodejs-runtimes.mdx
@@ -0,0 +1,71 @@
+---
+title: Edge and Node.js Runtimes
+description: Learn about the switchable runtimes (Edge and Node.js) in Next.js.
+---
+
+In the context of Next.js, "runtime" refers to the set of libraries, APIs, and general functionality available to your code during execution.
+
+Next.js has two server runtimes where you can render parts of your application code:
+
+- [Node.js Runtime](#nodejs-runtime)
+- [Edge Runtime](#edge-runtime)
+
+Each runtime has its own set of APIs. Please refer to the [Node.js Docs](https://nodejs.org/docs/latest/api/) and [Edge Docs](/docs/app/api-reference/edge) for the full list of available APIs. Both runtimes can also support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) depending on your deployment infrastructure.
+
+By default, the `app` directory uses the Node.js runtime. However, you can opt into different runtimes (e.g. Edge) on a per-route basis.
+
+## Runtime Differences
+
+There are many considerations to make when choosing a runtime. This table shows the major differences at a glance. If you want a more in-depth analysis of the differences, check out the sections below.
+
+| | Node | Serverless | Edge |
+| --------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---------- | ---------------- |
+| [Cold Boot](https://vercel.com/docs/concepts/get-started/compute#cold-and-hot-boots?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) | / | ~250ms | Instant |
+| [HTTP Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) | Yes | Yes | Yes |
+| IO | All | All | `fetch` |
+| Scalability | / | High | Highest |
+| Security | Normal | High | High |
+| Latency | Normal | Low | Lowest |
+| npm Packages | All | All | A smaller subset |
+
+### Edge Runtime
+
+In Next.js, the lightweight Edge Runtime is a subset of available Node.js APIs.
+
+The Edge Runtime is ideal if you need to deliver dynamic, personalized content at low latency with small, simple functions. The Edge Runtime's speed comes from its minimal use of resources, but that can be limiting in many scenarios.
+
+For example, code executed in the Edge Runtime [on Vercel cannot exceed between 1 MB and 4 MB](https://vercel.com/docs/concepts/limits/overview#edge-middleware-and-edge-functions-size), this limit includes imported packages, fonts and files, and will vary depending on your deployment infrastructure.
+
+### Node.js Runtime
+
+Using the Node.js runtime gives you access to all Node.js APIs, and all npm packages that rely on them. However, it's not as fast to start up as routes using the Edge runtime.
+
+Deploying your Next.js application to a Node.js server will require managing, scaling, and configuring your infrastructure. Alternatively, you can consider deploying your Next.js application to a serverless platform like Vercel, which will handle this for you.
+
+### Serverless Node.js
+
+Serverless is ideal if you need a scalable solution that can handle more complex computational loads than the Edge Runtime. With Serverless Functions on Vercel, for example, your overall code size is [50MB](https://vercel.com/docs/concepts/limits/overview#serverless-function-size) including imported packages, fonts, and files.
+
+The downside compared to routes using the [Edge](https://vercel.com/docs/concepts/functions/edge-functions) is that it can take hundreds of milliseconds for Serverless Functions to boot up before they begin processing requests. Depending on the amount of traffic your site receives, this could be a frequent occurrence as the functions are not frequently "warm".
+
+
+
+## Examples
+
+### Segment Runtime Option
+
+You can specify a runtime for individual route segments in your Next.js application. To do so, [declare a variable called `runtime` and export it](/docs/app/api-reference/file-conventions/route-segment-config). The variable must be a string, and must have a value of either `'nodejs'` or `'edge'` runtime.
+
+The following example demonstrates a page route segment that exports a `runtime` with a value of `'edge'`:
+
+```tsx filename="app/page.tsx" switcher
+export const runtime = 'edge' // 'nodejs' (default) | 'edge'
+```
+
+```jsx filename="app/page.js" switcher
+export const runtime = 'edge' // 'nodejs' (default) | 'edge'
+```
+
+If the segment runtime is _not_ set, the default `nodejs` runtime will be used. You do not need to use the `runtime` option if you do not plan to change from the Node.js runtime.
+
+
diff --git a/docs/02-app/01-building-your-application/02-rendering/index.mdx b/docs/02-app/01-building-your-application/02-rendering/index.mdx
new file mode 100644
index 0000000000000..5d84de7a46785
--- /dev/null
+++ b/docs/02-app/01-building-your-application/02-rendering/index.mdx
@@ -0,0 +1,73 @@
+---
+title: Rendering
+description: Learn the differences between Next.js rendering environments, strategies, and runtimes.
+---
+
+Rendering converts the code you write into user interfaces.
+
+React 18 and Next.js 13 introduced new ways to render your application. This page will help you understand the differences between rendering environments, strategies, runtimes, and how to opt into them.
+
+## Rendering Environments
+
+There are two environments where your application code can be rendered: the client and the server.
+
+
+
+- The **client** refers to the browser on a user's device that sends a request to a server for your application code. It then turns the response from the server into an interface the user can interact with.
+- The **server** refers to the computer in a data center that stores your application code, receives requests from a client, does some computation, and sends back an appropriate response.
+
+> **Note:** Server can refer to computers in regions where your application is deployed to, the [Edge Network](https://vercel.com/docs/concepts/edge-network/overview) where your application code is distributed, or [Content Delivery Networks (CDNs)](https://developer.mozilla.org/en-US/docs/Glossary/CDN) where the result of the rendering work can be cached.
+
+## Component-level Client and Server Rendering
+
+Before React 18, the primary way to render your application **using React** was entirely on the client.
+
+Next.js provided an easier way to break down your application into **pages** and prerender on the server by generating HTML and sending it to the client to be [hydrated](https://react.dev/reference/react-dom/hydrate#hydrating-server-rendered-html) by React. However, this led to additional JavaScript needed on the client to make the initial HTML interactive.
+
+Now, with [Server and Client Components](/docs/getting-started/react-essentials), React can render on the client **and** the server meaning you can choose the rendering environment at the component level.
+
+By default, the [`app` router uses **Server Components**](/docs/getting-started/react-essentials#server-components), allowing you to easily render components on the server and reducing the amount of JavaScript sent to the client.
+
+## Static and Dynamic Rendering on the Server
+
+In addition to client-side and server-side rendering with React components, Next.js gives you the option to optimize rendering on the server with **Static** and **Dynamic** Rendering.
+
+### Static Rendering
+
+With **Static Rendering**, both Server _and_ Client Components can be prerendered on the server at **build time**. The result of the work is [cached](/docs/app/building-your-application/data-fetching/caching) and reused on subsequent requests. The cached result can also be [revalidated](/docs/app/building-your-application/data-fetching#revalidating-data).
+
+> **Note:** This is equivalent to [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) and [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/rendering/incremental-static-regeneration) in the [Pages Router](/docs/pages/building-your-application/rendering).
+
+Server and Client Components are rendered differently during Static Rendering:
+
+- Client Components have their HTML and JSON prerendered and cached on the server. The cached result is then sent to the client for hydration.
+- Server Components are rendered on the server by React, and their payload is used to generate HTML. The same rendered payload is also used to hydrate the components on the client, resulting in no JavaScript needed on the client.
+
+### Dynamic Rendering
+
+With Dynamic Rendering, both Server _and_ Client Components are rendered on the server at **request time**. The result of the work is not cached.
+
+> **Note:** This is equivalent to [Server-Side Rendering (`getServerSideProps()`)](/docs/pages/building-your-application/rendering/server-side-rendering) in the [Pages Router](/docs/pages/building-your-application/rendering).
+
+To learn more about static and dynamic behavior, see the [Static and Dynamic Rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering) page. To learn more about caching, see the [Caching](/docs/app/building-your-application/data-fetching/caching) sections.
+
+## Edge and Node.js Runtimes
+
+On the server, there are two runtimes where your pages can be rendered:
+
+- The **Node.js Runtime** (default) has access to all Node.js APIs and compatible packages from the ecosystem.
+- The **Edge Runtime** is based on [Web APIs](/docs/app/api-reference/edge).
+
+Both runtimes support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) from the server, depending on your deployment infrastructure.
+
+To learn how to switch between runtimes, see the [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) page.
+
+## Next Steps
+
+Now that you understand the fundamentals of rendering, you can learn more about implementing the different rendering strategies and runtimes:
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx b/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx
new file mode 100644
index 0000000000000..dd8b434fb8ac8
--- /dev/null
+++ b/docs/02-app/01-building-your-application/03-data-fetching/01-fetching.mdx
@@ -0,0 +1,401 @@
+---
+title: Data Fetching
+nav_title: Fetching
+description: Learn how to fetch data in your Next.js application.
+---
+
+The Next.js App Router allows you to fetch data directly in your React components by marking the function as `async` and using `await` for the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
+
+Data fetching is built on top of the [`fetch()` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and React Server Components. When using `fetch()`, requests are [automatically deduped](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) by default.
+
+Next.js extends the `fetch` options object to allow each request to set its own [caching and revalidating](/docs/app/building-your-application/data-fetching/caching).
+
+## `async` and `await` in Server Components
+
+You can use `async` and `await` to fetch data in Server Components.
+
+```tsx filename="app/page.tsx" switcher
+async function getData() {
+ const res = await fetch('https://api.example.com/...')
+ // The return value is *not* serialized
+ // You can return Date, Map, Set, etc.
+
+ // Recommendation: handle errors
+ if (!res.ok) {
+ // This will activate the closest `error.js` Error Boundary
+ throw new Error('Failed to fetch data')
+ }
+
+ return res.json()
+}
+
+export default async function Page() {
+ const data = await getData()
+
+ return
+}
+```
+
+```jsx filename="app/page.js" switcher
+async function getData() {
+ const res = await fetch('https://api.example.com/...')
+ // The return value is *not* serialized
+ // You can return Date, Map, Set, etc.
+
+ // Recommendation: handle errors
+ if (!res.ok) {
+ // This will activate the closest `error.js` Error Boundary
+ throw new Error('Failed to fetch data')
+ }
+
+ return res.json()
+}
+
+export default async function Page() {
+ const data = await getData()
+
+ return
+}
+```
+
+> **Good to know:**
+>
+> To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
+
+### Server Component Functions
+
+Next.js provides helpful server functions you may need when fetching data in Server Components:
+
+- [`cookies()`](/docs/app/api-reference/functions/cookies)
+- [`headers()`](/docs/app/api-reference/functions/headers)
+
+## `use` in Client Components
+
+`use` is a new React function that **accepts a promise** conceptually similar to `await`. `use` **handles the promise** returned by a function in a way that is compatible with components, hooks, and Suspense. Learn more about `use` in the [React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#usepromise).
+
+Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. For now, if you need to fetch data in a Client Component, we recommend using a third-party library such as [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/v4).
+
+> **Note:** We'll be adding more examples once `fetch` and `use` work in Client Components.
+
+## Static Data Fetching
+
+By default, `fetch` will automatically fetch and [cache data](/docs/app/building-your-application/data-fetching/caching) indefinitely.
+
+```ts
+fetch('https://...') // cache: 'force-cache' is the default
+```
+
+### Revalidating Data
+
+To revalidate [cached data](/docs/app/building-your-application/data-fetching/caching) at a timed interval, you can use the `next.revalidate` option in `fetch()` to set the `cache` lifetime of a resource (in seconds).
+
+```ts
+fetch('https://...', { next: { revalidate: 10 } })
+```
+
+See [Revalidating Data](/docs/app/building-your-application/data-fetching/revalidating) for more information.
+
+> **Good to know:**
+>
+> Caching at the fetch level with `revalidate` or `cache: 'force-cache'` stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from `cookies()` or `headers()`)
+
+## Dynamic Data Fetching
+
+To fetch fresh data on every `fetch` request, use the `cache: 'no-store'` option.
+
+```ts
+fetch('https://...', { cache: 'no-store' })
+```
+
+## Data Fetching Patterns
+
+### Parallel Data Fetching
+
+To minimize client-server waterfalls, we recommend this pattern to fetch data in parallel:
+
+```tsx filename="app/artist/[username]/page.tsx" switcher
+import Albums from './albums'
+
+async function getArtist(username: string) {
+ const res = await fetch(`https://api.example.com/artist/${username}`)
+ return res.json()
+}
+
+async function getArtistAlbums(username: string) {
+ const res = await fetch(`https://api.example.com/artist/${username}/albums`)
+ return res.json()
+}
+
+export default async function Page({
+ params: { username },
+}: {
+ params: { username: string }
+}) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumsData = getArtistAlbums(username)
+
+ // Wait for the promises to resolve
+ const [artist, albums] = await Promise.all([artistData, albumsData])
+
+ return (
+ <>
+
{artist.name}
+
+ >
+ )
+}
+```
+
+```jsx filename="app/artist/[username]/page.js" switcher
+import Albums from './albums'
+
+async function getArtist(username) {
+ const res = await fetch(`https://api.example.com/artist/${username}`)
+ return res.json()
+}
+
+async function getArtistAlbums(username) {
+ const res = await fetch(`https://api.example.com/artist/${username}/albums`)
+ return res.json()
+}
+
+export default async function Page({ params: { username } }) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumsData = getArtistAlbums(username)
+
+ // Wait for the promises to resolve
+ const [artist, albums] = await Promise.all([artistData, albumsData])
+
+ return (
+ <>
+
{artist.name}
+
+ >
+ )
+}
+```
+
+By starting the fetch prior to calling `await` in the Server Component, each request can eagerly start to fetch requests at the same time. This sets the components up so you can avoid waterfalls.
+
+We can save time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved.
+
+To improve the user experience, you can add a [suspense boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming) to break up the rendering work and show part of the result as soon as possible:
+
+```tsx filename="artist/[username]/page.tsx" switcher
+import { getArtist, getArtistAlbums, type Album } from './api'
+
+export default async function Page({
+ params: { username },
+}: {
+ params: { username: string }
+}) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumData = getArtistAlbums(username)
+
+ // Wait for the artist's promise to resolve first
+ const artist = await artistData
+
+ return (
+ <>
+
{artist.name}
+ {/* Send the artist information first,
+ and wrap albums in a suspense boundary */}
+ Loading...}>
+
+
+ >
+ )
+}
+
+// Albums Component
+async function Albums({ promise }: { promise: Promise }) {
+ // Wait for the albums promise to resolve
+ const albums = await promise
+
+ return (
+
+ {albums.map((album) => (
+
{album.name}
+ ))}
+
+ )
+}
+```
+
+```jsx filename="artist/[username]/page.js" switcher
+import { getArtist, getArtistAlbums } from './api'
+
+export default async function Page({ params: { username } }) {
+ // Initiate both requests in parallel
+ const artistData = getArtist(username)
+ const albumData = getArtistAlbums(username)
+
+ // Wait for the artist's promise to resolve first
+ const artist = await artistData
+
+ return (
+ <>
+
{artist.name}
+ {/* Send the artist information first,
+ and wrap albums in a suspense boundary */}
+ Loading...}>
+
+
+ >
+ )
+}
+
+// Albums Component
+async function Albums({ promise }) {
+ // Wait for the albums promise to resolve
+ const albums = await promise
+
+ return (
+
+ {albums.map((album) => (
+
{album.name}
+ ))}
+
+ )
+}
+```
+
+Take a look at the [preloading pattern](/docs/app/building-your-application/data-fetching/caching#preload-pattern-with-cache) for more information on improving components structure.
+
+### Sequential Data Fetching
+
+To fetch data sequentially, you can `fetch` directly inside the component that needs it, or you can `await` the result of `fetch` inside the component that needs it:
+
+```tsx filename="app/artist/page.tsx" switcher
+// ...
+
+async function Playlists({ artistID }: { artistID: string }) {
+ // Wait for the playlists
+ const playlists = await getArtistPlaylists(artistID)
+
+ return (
+
+ {playlists.map((playlist) => (
+
{playlist.name}
+ ))}
+
+ )
+}
+
+export default async function Page({
+ params: { username },
+}: {
+ params: { username: string }
+}) {
+ // Wait for the artist
+ const artist = await getArtist(username)
+
+ return (
+ <>
+
+ )
+}
+
+export default async function Page({ params: { username } }) {
+ // Wait for the artist
+ const artist = await getArtist(username)
+
+ return (
+ <>
+
{artist.name}
+ Loading...}>
+
+
+ >
+ )
+}
+```
+
+By fetching data inside the component, each fetch request and nested segment in the route cannot start fetching data and rendering until the previous request or segment has completed.
+
+### Blocking Rendering in a Route
+
+By fetching data in a [layout](/docs/app/building-your-application/routing/pages-and-layouts), rendering for all route segments beneath it can only start once the data has finished loading.
+
+In the `pages` directory, pages using server-rendering would show the browser loading spinner until `getServerSideProps` had finished, then render the React component for that page. This can be described as "all or nothing" data fetching. Either you had the entire data for your page, or none.
+
+In the `app` directory, you have additional options to explore:
+
+1. First, you can use `loading.js` to show an instant loading state from the server while streaming in the result from your data fetching function.
+2. Second, you can move data fetching _lower_ in the component tree to only block rendering for the parts of the page that need it. For example, moving data fetching to a specific component rather than fetching it at the root layout.
+
+Whenever possible, it's best to fetch data in the segment that uses it. This also allows you to show a loading state for only the part of the page that is loading, and not the entire page.
+
+## Data Fetching without `fetch()`
+
+You might not always have the ability to use and configure `fetch` requests directly if you're using a third-party library such as an ORM or database client.
+
+In cases where you cannot use `fetch` but still want to control the caching or revalidating behavior of a layout or page, you can rely on the [default caching behavior](#default-caching-behavior) of the segment or use the [segment cache configuration](#segment-cache-configuration).
+
+### Default Caching Behavior
+
+Any data fetching libraries that do not use `fetch` directly **will not** affect caching of a route, and will be static or dynamic depending on the route segment.
+
+If the segment is static (default), the output of the request will be cached and revalidated (if configured) alongside the rest of the 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:** Dynamic functions like [`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers) will make the route segment dynamic.
+
+### Segment Cache Configuration
+
+As a temporary solution, until the caching behavior of third-party queries can be configured, you can use [segment configuration](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to customize the cache behavior of the entire segment.
+
+```ts filename="app/page.tsx" switcher
+import prisma from './lib/prisma'
+
+export const revalidate = 3600 // revalidate every hour
+
+async function getPosts() {
+ const posts = await prisma.post.findMany()
+ return posts
+}
+
+export default async function Page() {
+ const posts = await getPosts()
+ // ...
+}
+```
+
+```jsx filename="app/page.js" switcher
+import prisma from './lib/prisma'
+
+export const revalidate = 3600 // revalidate every hour
+
+async function getPosts() {
+ const posts = await prisma.post.findMany()
+ return posts
+}
+
+export default async function Page() {
+ const posts = await getPosts()
+ // ...
+}
+```
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/02-caching.mdx b/docs/02-app/01-building-your-application/03-data-fetching/02-caching.mdx
new file mode 100644
index 0000000000000..0d413b86267ce
--- /dev/null
+++ b/docs/02-app/01-building-your-application/03-data-fetching/02-caching.mdx
@@ -0,0 +1,284 @@
+---
+title: Caching Data
+nav_title: Caching
+description: Learn about caching routes in Next.js.
+---
+
+Next.js has built-in support for caching data, both on a per-request basis (recommended) or for an entire route segment.
+
+
+
+## Per-request Caching
+
+### `fetch()`
+
+By default, all `fetch()` requests are cached and deduplicated automatically. This means that if you make the same request twice, the second request will reuse the result from the first request.
+
+```tsx filename="app/page.tsx" switcher
+async function getComments() {
+ const res = await fetch('https://...') // The result is cached
+ return res.json()
+}
+
+// This function is called twice, but the result is only fetched once
+const comments = await getComments() // cache MISS
+
+// The second call could be anywhere in your application
+const comments = await getComments() // cache HIT
+```
+
+```jsx filename="app/page.js" switcher
+async function getComments() {
+ const res = await fetch('https://...') // The result is cached
+ return res.json()
+}
+
+// This function is called twice, but the result is only fetched once
+const comments = await getComments() // cache MISS
+
+// The second call could be anywhere in your application
+const comments = await getComments() // cache HIT
+```
+
+Requests are **not** cached if:
+
+- Dynamic methods (`next/headers`, `export const POST`, or similar) are used and the fetch is a `POST` request (or uses `Authorization` or `cookie` headers)
+- `fetchCache` is configured to skip cache by default
+- `revalidate: 0` or `cache: 'no-store'` is configured on individual `fetch`
+
+Requests made using `fetch` can specify a `revalidate` option to control the revalidation frequency of the request.
+
+```tsx filename="app/page.tsx" switcher
+export default async function Page() {
+ // revalidate this data every 10 seconds at most
+ const res = await fetch('https://...', { next: { revalidate: 10 } })
+ const data = res.json()
+ // ...
+}
+```
+
+```jsx filename="app/page.js" switcher
+export default async function Page() {
+ // revalidate this data every 10 seconds at most
+ const res = await fetch('https://...', { next: { revalidate: 10 } })
+ const data = res.json()
+ // ...
+}
+```
+
+### React `cache()`
+
+React allows you to [`cache()`](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md) and deduplicate requests, memoizing the result of the wrapped function call. The same function called with the same arguments will reuse a cached value instead of re-running the function.
+
+```tsx filename="utils/getUser.ts" switcher
+import { cache } from 'react'
+
+export const getUser = cache(async (id: string) => {
+ const user = await db.user.findUnique({ id })
+ return user
+})
+```
+
+```jsx filename="utils/getUser.js" switcher
+import { cache } from 'react'
+
+export const getUser = cache(async (id) => {
+ const user = await db.user.findUnique({ id })
+ return user
+})
+```
+
+```tsx filename="app/user/[id]/layout.tsx" switcher
+import { getUser } from '@utils/getUser'
+
+export default async function UserLayout({ params: { id } }) {
+ const user = await getUser(id)
+ // ...
+}
+```
+
+```jsx filename="app/user/[id]/layout.js" switcher
+import { getUser } from '@utils/getUser'
+
+export default async function UserLayout({ params: { id } }) {
+ const user = await getUser(id)
+ // ...
+}
+```
+
+```tsx filename="app/user/[id]/page.tsx" switcher
+import { getUser } from '@utils/getUser'
+
+export default async function Page({
+ params: { id },
+}: {
+ params: { id: string }
+}) {
+ const user = await getUser(id)
+ // ...
+}
+```
+
+```jsx filename="app/user/[id]/page.js" switcher
+import { getUser } from '@utils/getUser'
+
+export default async function Page({ params: { id } }) {
+ const user = await getUser(id)
+ // ...
+}
+```
+
+Although the `getUser()` function is called twice in the example above, only one query will be made to the database. This is because `getUser()` is wrapped in `cache()`, so the second request can reuse the result from the first request.
+
+> **Good to know:**
+>
+> - `fetch()` caches requests automatically, so you don't need to wrap functions that use `fetch()` with `cache()`. See [automatic request deduping](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) for more information.
+> - In this new model, we recommend **fetching data directly in the component that needs it**, even if you're requesting the same data in multiple components, rather than passing the data between components as props.
+> - 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.
+
+### `POST` requests and `cache()`
+
+`POST` requests are automatically deduplicated when using `fetch` – unless they are inside of `POST` Route Handler or come after reading `headers()`/`cookies()`. For example, if you are using GraphQL and `POST` requests in the above cases, you can use `cache` to deduplicate requests. The `cache` arguments must be flat and only include primitives. Deep objects won't match for deduplication.
+
+```tsx filename="utils/getUser.ts" switcher
+import { cache } from 'react'
+
+export const getUser = cache(async (id: string) => {
+ const res = await fetch('...', { method: 'POST', body: '...' })
+ // ...
+})
+```
+
+```jsx filename="utils/getUser.js" switcher
+import { cache } from 'react'
+
+export const getUser = cache(async (id) => {
+ const res = await fetch('...', { method: 'POST', body: '...' })
+ // ...
+})
+```
+
+### Preload pattern with `cache()`
+
+As a pattern, we suggest optionally exposing a `preload()` export in utilities or components that do data fetching.
+
+```tsx filename="components/User.tsx" switcher
+import { getUser } from '@utils/getUser'
+
+export const preload = (id: string) => {
+ // void evaluates the given expression and returns undefined
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
+ void getUser(id)
+}
+export default async function User({ id }: { id: string }) {
+ const result = await getUser(id)
+ // ...
+}
+```
+
+```jsx filename="components/User.js" switcher
+import { getUser } from '@utils/getUser'
+
+export const preload = (id) => {
+ // void evaluates the given expression and returns undefined
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
+ void getUser(id)
+}
+export default async function User({ id }) {
+ const result = await getUser(id)
+ // ...
+}
+```
+
+By calling `preload`, you can eagerly start fetching data you're likely going to need.
+
+```tsx filename="app/user/[id]/page.tsx" switcher
+import User, { preload } from '@components/User'
+
+export default async function Page({
+ params: { id },
+}: {
+ params: { id: string }
+}) {
+ preload(id) // starting loading the user data now
+ const condition = await fetchCondition()
+ return condition ? : null
+}
+```
+
+```jsx filename="app/user/[id]/page.js" switcher
+import User, { preload } from '@components/User'
+
+export default async function Page({ params: { id } }) {
+ preload(id) // starting loading the user data now
+ const condition = await fetchCondition()
+ return condition ? : null
+}
+```
+
+> **Good to know**:
+>
+> - The `preload()` function can have any name. It's a pattern, not an API.
+> - This pattern is completely optional and something you can use to optimize on a case-by-case basis.
+> This pattern is a further optimization on top of [parallel data fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-data-fetching). Now you don't have to pass promises down as props and can instead rely on the preload pattern.
+
+### Combining `cache`, `preload`, and `server-only`
+
+You can combine the `cache` function, the `preload` pattern, and the `server-only` package to create a data fetching utility that can be used throughout your app.
+
+```tsx filename="utils/getUser.ts" switcher
+import { cache } from 'react'
+import 'server-only'
+
+export const preload = (id: string) => {
+ void getUser(id)
+}
+
+export const getUser = cache(async (id: string) => {
+ // ...
+})
+```
+
+```jsx filename="utils/getUser.js" switcher
+import { cache } from 'react'
+import 'server-only'
+
+export const preload = (id) => {
+ void getUser(id)
+}
+
+export const getUser = cache(async (id) => {
+ // ...
+})
+```
+
+With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching [only happens on the server](/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning).
+
+The `getUser.ts` exports can be used by layouts, pages, or components to give them control over when a user's data is fetched.
+
+## Segment-level Caching
+
+> **Note:** We recommend using per-request caching for improved granularity and control over caching.
+
+Segment-level caching allows you to cache and revalidate data used in route segments.
+
+This mechanism allows different segments of a path to control the cache lifetime of the entire route. Each `page.tsx` and `layout.tsx` in the route hierarchy can export a `revalidate` value that sets the revalidation time for the route.
+
+```tsx filename="app/page.tsx" switcher
+export const revalidate = 60 // revalidate this segment every 60 seconds
+```
+
+```jsx filename="app/page.js" switcher
+export const revalidate = 60 // revalidate this segment every 60 seconds
+```
+
+> **Good to know:**
+>
+> - If a page, layout, and fetch request inside components all specify a [`revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) frequency, the lowest value of the three will be used.
+> - Advanced: You can set `fetchCache` to `'only-cache'` or `'force-cache'` to ensure that all `fetch` requests opt into caching but the revalidation frequency might still be lowered by individual `fetch` requests. See [`fetchCache`](/docs/app/api-reference/file-conventions/route-segment-config) for more information.
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/03-revalidating.mdx b/docs/02-app/01-building-your-application/03-data-fetching/03-revalidating.mdx
new file mode 100644
index 0000000000000..ca405ef167a80
--- /dev/null
+++ b/docs/02-app/01-building-your-application/03-data-fetching/03-revalidating.mdx
@@ -0,0 +1,103 @@
+---
+title: Revalidating Data
+nav_title: Revalidating
+description: Learn about revalidating data in Next.js using Incremental Static Regeneration.
+---
+
+Next.js allows you to update specific static routes **without needing to rebuild your entire site**. Revalidation (also known as [Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)) allows you to retain the benefits of static while scaling to millions of pages.
+
+There are two types of revalidation in Next.js:
+
+- **Background**: Revalidates the data at a specific time interval.
+- **On-demand**: Revalidates the data based on an event such as an update.
+
+## Background Revalidation
+
+To revalidate cached data at a specific interval, you can use the `next.revalidate` option in `fetch()` to set the `cache` lifetime of a resource (in seconds).
+
+```jsx
+fetch('https://...', { next: { revalidate: 60 } })
+```
+
+If you want to revalidate data that does not use `fetch` (i.e. using an external package or query builder), you can use the [route segment config](/docs/app/api-reference/file-conventions/route-segment-config#revalidate).
+
+```tsx filename="app/page.tsx" switcher
+export const revalidate = 60 // revalidate this page every 60 seconds
+```
+
+```jsx filename="app/page.js" switcher
+export const revalidate = 60 // revalidate this page every 60 seconds
+```
+
+In addition to `fetch`, you can also revalidate data using [`cache`](/docs/app/building-your-application/data-fetching/caching#per-request-caching).
+
+### How it works
+
+1. When a request is made to the route that was statically rendered at build time, it will initially show the cached data.
+2. Any requests to the route after the initial request and before 60 seconds are also cached and instantaneous.
+3. After the 60-second window, the next request will still show the cached (stale) data.
+4. Next.js will trigger a regeneration of the data in the background.
+5. Once the route generates successfully, Next.js will invalidate the cache and show the updated route. If the background regeneration fails, the old data would still be unaltered.
+
+When a request is made to a route segment that hasn’t been generated, Next.js will dynamically render the route on the first request. Future requests will serve the static route segments from the cache.
+
+> **Note**: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. `useCdn: false`), otherwise a revalidation won't be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the `Cache-Control` header. ISR on Vercel [persists the cache globally and handles rollbacks](https://vercel.com/docs/concepts/incremental-static-regeneration/overview).
+
+## On-demand Revalidation
+
+If you set a `revalidate` time of `60`, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is if someone visits the page after the minute has passed.
+
+The Next.js App Router supports revalidating content on-demand based on a route or cache tag. This allows you to manually purge the Next.js cache for specific fetches, making it easier to update your site when:
+
+- Content from your headless CMS is created or updated.
+- Ecommerce metadata changes (price, description, category, reviews, etc).
+
+### Using On-Demand Revalidation
+
+Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)).
+
+For example, the following `fetch` adds the cache tag `collection`:
+
+```tsx filename="app/page.tsx" switcher
+export default async function Page() {
+ const res = await fetch('https://...', { next: { tags: ['collection'] } })
+ const data = await res.json()
+ // ...
+}
+```
+
+```jsx filename="app/page.js" switcher
+export default async function Page() {
+ const res = await fetch('https://...', { next: { tags: ['collection'] } })
+ const data = await res.json()
+ // ...
+}
+```
+
+This cached data can then be revalidated on-demand by calling `revalidateTag` in a [Route Handler](/docs/app/building-your-application/routing/router-handlers).
+
+```tsx filename="app/api/revalidate/route.ts" switcher
+import { NextRequest, NextResponse } from 'next/server'
+import { revalidateTag } from 'next/cache'
+
+export async function GET(request: NextRequest) {
+ const tag = request.nextUrl.searchParams.get('tag')
+ revalidateTag(tag)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+```jsx filename="app/api/revalidate/route.js" switcher
+import { NextResponse } from 'next/server'
+import { revalidateTag } from 'next/cache'
+
+export async function GET(request) {
+ const tag = request.nextUrl.searchParams.get('tag')
+ revalidateTag(tag)
+ return NextResponse.json({ revalidated: true, now: Date.now() })
+}
+```
+
+## Error Handling and Revalidation
+
+If an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data.
diff --git a/docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx b/docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx
new file mode 100644
index 0000000000000..2a40d89671d0d
--- /dev/null
+++ b/docs/02-app/01-building-your-application/03-data-fetching/04-server-actions.mdx
@@ -0,0 +1,548 @@
+---
+title: Server Actions
+nav_title: Server Actions
+description: Use Server Actions to mutate data in your Next.js application.
+related:
+ title: Next Steps
+ description: For more information on what to do next, we recommend the following sections
+ links:
+ - app/api-reference/functions/cookies
+---
+
+[Server Actions](#server-actions) are an **alpha** feature in Next.js, built on top of React [Actions](#actions). They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms. They can be defined inside Server Components and/or called from Client Components:
+
+**With Server Components:**
+
+```jsx filename="app/add-to-cart.jsx" highlight={5, 6, 13}
+import { cookies } from 'next/headers'
+
+// Server action defined inside a Server Component
+export default function AddToCart({ productId }) {
+ async function addItem(data) {
+ 'use server'
+
+ const cartId = cookies().get('cartId')?.value
+ await saveToDb({ cartId, data })
+ }
+
+ return (
+
+ )
+}
+```
+
+**With Client Components:**
+
+```jsx filename="app/actions.js" highlight={1, 3}
+'use server'
+
+async function addItem(data) {
+ const cartId = cookies().get('cartId')?.value
+ await saveToDb({ cartId, data })
+}
+```
+
+```jsx filename="app/add-to-cart.jsx" highlight={1, 3, 8}
+'use client'
+
+import { addItem } from './actions.js'
+
+// Server Action being called inside a Client Component
+export default function AddToCart({ productId }) {
+ return (
+
+ )
+}
+```
+
+## Convention
+
+You can enable Server Actions in your Next.js project by enabling the **experimental** `serverActions` flag.
+
+```js filename="next.config.js"
+module.exports = {
+ experimental: {
+ serverActions: true,
+ },
+}
+```
+
+### Creation
+
+Server Actions can be defined in two places:
+
+- Inside the component that uses it (Server Components only)
+- In a separate file (Client and Server Components), for reusability. You can define multiple Server Actions in a single file.
+
+#### With Server Components
+
+Create a Server Action by defining an asynchronous function with the `"use server"` directive at the top of the function body. This function should have **serializable arguments** and a **serializable return value** based on the React Server Components protocol.
+
+```jsx filename="app/server-component.jsx" highlight={2}
+export default function ServerComponent() {
+ async function myAction() {
+ 'use server'
+ // ...
+ }
+}
+```
+
+#### With Client Components
+
+If you're using a Server Action inside a Client Component, create your action in a separate file with the "use server" directive at the top of the file. Then, import the Server Action into your Client Component:
+
+```jsx filename="app/actions.js" highlight={1}
+'use server'
+
+export async function myAction() {
+ // ...
+}
+```
+
+```jsx filename="app/client-component.jsx" highlight={1}
+|"use client"
+
+import { myAction } from './actions';
+
+export default function ClientComponent() {
+ return (
+
+ );
+}
+```
+
+> **Note:** When using a top-level `"use server"` directive, all exports below will be considered Server Actions. You can have multiple Server Actions in a single file.
+
+### Invocation
+
+You can invoke Server Actions using the following methods:
+
+- Using `action`: React's `action` prop allows invoking a Server Action on a `