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

docs: update `Getting Started` Section (#77921)

Closes: https://linear.app/vercel/issue/DOC-4467/review-and-clean-up

Also addressed user feedback from vercel/feedback
parent 46fe103d
......@@ -8,12 +8,14 @@ description: Create a new Next.js application with the `create-next-app` CLI, an
## System requirements
Before you begin, make sure your system meets the following requirements:
- [Node.js 18.18](https://nodejs.org/) or later.
- macOS, Windows (including WSL), and Linux are supported.
- macOS, Windows (including WSL), or Linux.
## Automatic installation
We recommend starting a new Next.js app using [`create-next-app`](/docs/app/api-reference/cli/create-next-app), which sets up everything automatically for you. To create a project, run:
The quickest way to create a new Next.js app is using [`create-next-app`](/docs/app/api-reference/cli/create-next-app), which sets up everything automatically for you. To create a project, run:
```bash filename="Terminal"
npx create-next-app@latest
......@@ -43,7 +45,7 @@ To manually create a new Next.js app, install the required packages:
npm install next@latest react@latest react-dom@latest
```
Open your `package.json` file and add the following `scripts`:
Then, add the following scripts to your `package.json` file:
```json filename="package.json"
{
......@@ -58,10 +60,10 @@ Open your `package.json` file and add the following `scripts`:
These scripts refer to the different stages of developing an application:
- `dev`: runs [`next dev`](/docs/app/api-reference/cli/next#next-dev-options) to start Next.js in development mode.
- `build`: runs [`next build`](/docs/app/api-reference/cli/next#next-build-options) to build the application for production usage.
- `start`: runs [`next start`](/docs/app/api-reference/cli/next#next-start-options) to start a Next.js production server.
- `lint`: runs [`next lint`](/docs/app/api-reference/cli/next#next-lint-options) to set up Next.js' built-in ESLint configuration.
- `next dev`: Starts the development server.
- `next build`: Builds the application for production.
- `next start`: Starts the production server.
- `next lint`: Runs ESLint.
<AppOnly>
......@@ -69,17 +71,7 @@ These scripts refer to the different stages of developing an application:
Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files.
Create an `app` folder, then add a `layout.tsx` and `page.tsx` file. These will be rendered when the user visits the root of your application (`/`).
<Image
alt="App Folder Structure"
srcLight="/docs/light/app-getting-started.png"
srcDark="/docs/dark/app-getting-started.png"
width="1600"
height="363"
/>
Create a [root layout](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required) inside `app/layout.tsx` with the required `<html>` and `<body>` tags:
Create an `app` folder. Then, inside `app`, create a `layout.tsx` file. This file is the [root layout](/docs/app/api-reference/file-conventions/layout#root-layouts). It's required and must contain the `<html>` and `<body>` tags.
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({
......@@ -105,7 +97,7 @@ export default function RootLayout({ children }) {
}
```
Finally, create a home page `app/page.tsx` with some initial content:
Create a home page `app/page.tsx` with some initial content:
```tsx filename="app/page.tsx" switcher
export default function Page() {
......@@ -119,9 +111,19 @@ export default function Page() {
}
```
Both `layout.tsx` and `page.tsx` will be rendered when the user visits the root of your application (`/`).
<Image
alt="App Folder Structure"
srcLight="/docs/light/app-getting-started.png"
srcDark="/docs/dark/app-getting-started.png"
width="1600"
height="363"
/>
> **Good to know**:
>
> - If you forget to create `layout.tsx`, Next.js will automatically create this file when running the development server with `next dev`.
> - If you forget to create the root layout, Next.js will automatically create this file when running the development server with `next dev`.
> - You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files.
</AppOnly>
......@@ -200,7 +202,25 @@ export default function Document() {
### Create the `public` folder (optional)
You can optionally create a [`public` folder](/docs/app/building-your-application/optimizing/static-assets) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`).
Create a [`public` folder](/docs/app/building-your-application/optimizing/static-assets) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`).
You can then reference these assets using the root path (`/`). For example, `public/profile.png` can be referenced as `/profile.png`:
```tsx filename="app/page.tsx" highlight={4} switcher
import Image from 'next/image'
export default function Page() {
return <Image src="/profile.png" alt="Profile" width={100} height={100} />
}
```
```jsx filename="app/page.js" highlight={4} switcher
import Image from 'next/image'
export default function Page() {
return <Image src="/profile.png" alt="Profile" width={100} height={100} />
}
```
## Run the development server
......@@ -212,7 +232,7 @@ You can optionally create a [`public` folder](/docs/app/building-your-applicatio
> Minimum TypeScript version: `v4.5.2`
Next.js comes with built-in TypeScript support. To add TypeScript to your project, rename a file to `.ts` / `.tsx`. Run `next dev`, Next.js will automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options.
Next.js comes with built-in TypeScript support. To add TypeScript to your project, rename a file to `.ts` / `.tsx` and run `next dev`. Next.js will automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options.
<AppOnly>
......@@ -234,17 +254,15 @@ You can enable the plugin in VS Code by:
height="637"
/>
Now, when editing files, the custom plugin will be enabled. When running `next build`, the custom type checker will be used.
</AppOnly>
See the [TypeScript configuration](/docs/app/api-reference/config/next-config-js/typescript) page for more information on how to use TypeScript in your project.
See the [TypeScript reference](/docs/app/api-reference/config/next-config-js/typescript) page for more information.
## Set up ESLint
Next.js comes with built-in ESLint, automatically installing the necessary packages and configuring the proper settings when you create a new project with `create-next-app`.
Next.js comes with built-in ESLint. It automatically installs the necessary packages and configures the proper settings when you create a new project with `create-next-app`.
To add ESLint to an existing project, add `next lint` as a script to `package.json`:
To manually add ESLint to an existing project, add `next lint` as a script to `package.json`:
```json filename="package.json"
{
......@@ -270,17 +288,19 @@ You'll see a prompt like this:
- **Strict**: Includes Next.js' base ESLint configuration along with a stricter Core Web Vitals rule-set. This is the recommended configuration for developers setting up ESLint for the first time.
- **Base**: Includes Next.js' base ESLint configuration.
- **Cancel**: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration.
- **Cancel**: Skip configuration. Select this option if you plan on setting up your own custom ESLint configuration.
If either of the two configuration options are selected, Next.js will automatically install `eslint` and `eslint-config-next` as dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration.
If `Strict` or `Base` are selected, Next.js will automatically install `eslint` and `eslint-config-next` as dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration.
You can now run `next lint` every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (`next build`). Errors will fail the build, while warnings will not.
See the [ESLint Plugin](/docs/app/api-reference/config/next-config-js/eslint) page for more information on how to configure ESLint in your project.
See the [ESLint Plugin](/docs/app/api-reference/config/next-config-js/eslint) page for more information.
## Set up Absolute Imports and Module Path Aliases
Next.js has in-built support for the `"paths"` and `"baseUrl"` options of `tsconfig.json` and `jsconfig.json` files. These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:
Next.js has in-built support for the `"paths"` and `"baseUrl"` options of `tsconfig.json` and `jsconfig.json` files.
These options allow you to alias project directories to absolute paths, making it easier and cleaner to import modules. For example:
```jsx
// Before
......@@ -316,32 +336,4 @@ For example, the following configuration maps `@/components/*` to `components/*`
}
```
Each of the `"paths"` are relative to the `baseUrl` location. For example:
```tsx filename="src/app/page.tsx" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}
```
```jsx filename="src/app/page.js" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}
```
Each of the `"paths"` are relative to the `baseUrl` location.
......@@ -4,7 +4,7 @@ nav_title: Project Structure
description: An overview of the folder and file conventions in Next.js, and how to organize your project.
---
This page provides an overview of the folder and file conventions in Next.js, as well as tips for organizing your project.
This page provides an overview of **all** the folder and file conventions in Next.js, and recommendations for organizing your project.
## Folder and file conventions
......@@ -168,9 +168,13 @@ Top-level files are used to configure your application, manage dependencies, run
<AppOnly>
## Component hierarchy
## Organizing your project
Next.js is **unopinionated** about how you organize and colocate your project files. But it does provide several features to help you organize your project.
### Component hierarchy
The React components defined in special files of a route segment are rendered in a specific hierarchy:
The components defined in special files are rendered in a specific hierarchy:
- `layout.js`
- `template.js`
......@@ -187,7 +191,7 @@ The React components defined in special files of a route segment are rendered in
height="643"
/>
In a nested route, the components of a segment will be nested **inside** the components of its parent segment.
The components are rendered recursively in nested routes, meaning the components of a route segment will be nested **inside** the components of its parent segment.
<Image
alt="Nested File Conventions Component Hierarchy"
......@@ -197,10 +201,6 @@ In a nested route, the components of a segment will be nested **inside** the com
height="863"
/>
## Organizing your project
Apart from [folder and file conventions](/docs/app/getting-started/project-structure), Next.js is **unopinionated** about how you organize and colocate your project files. But it does provide several features to help you organize your project.
### Colocation
In the `app` directory, nested folders define route structure. Each folder represents a route segment that is mapped to a corresponding segment in a URL path.
......@@ -235,9 +235,7 @@ This means that **project files** can be **safely colocated** inside route segme
height="1011"
/>
> **Good to know**:
>
> - 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).
> **Good to know**: 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).
### Private folders
......@@ -282,10 +280,10 @@ This indicates the folder is for organizational purposes and should **not be inc
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.
- Organizing routes by site section, intent, or team. e.g. marketing pages, admin pages, etc.
- 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)
- [Creating multiple nested layouts in the same segment, including multiple root layouts](#creating-multiple-root-layouts)
- [Adding a layout to a subset of routes in a common segment](#opting-specific-segments-into-a-layout)
### `src` directory
......@@ -299,7 +297,7 @@ Next.js supports storing application code (including `app`) inside an optional [
height="687"
/>
### Common strategies
### Examples
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.
......@@ -341,4 +339,66 @@ This strategy stores globally shared application code in the root `app` director
height="1011"
/>
### Organize routes without affecting the URL path
To organize routes without affecting the URL, create a group to keep related routes together. The folders in parenthesis will be omitted from the URL (e.g. `(marketing)` or `(shop)`).
<Image
alt="Organizing Routes with Route Groups"
srcLight="/docs/light/route-group-organisation.png"
srcDark="/docs/dark/route-group-organisation.png"
width="1600"
height="930"
/>
Even though routes inside `(marketing)` and `(shop)` share the same URL hierarchy, you can create a different layout for each group by adding a `layout.js` file inside their folders.
<Image
alt="Route Groups with Multiple Layouts"
srcLight="/docs/light/route-group-multiple-layouts.png"
srcDark="/docs/dark/route-group-multiple-layouts.png"
width="1600"
height="768"
/>
### Opting specific segments into a layout
To opt specific routes into a layout, create a new route group (e.g. `(shop)`) and move the routes that share the same layout into the group (e.g. `account` and `cart`). The routes outside of the group will not share the layout (e.g. `checkout`).
<Image
alt="Route Groups with Opt-in Layouts"
srcLight="/docs/light/route-group-opt-in-layouts.png"
srcDark="/docs/dark/route-group-opt-in-layouts.png"
width="1600"
height="930"
/>
### Opting for loading skeletons on a specific route
To apply a [loading skeleton](/docs/app/building-your-application/routing/loading-ui-and-streaming) via a `loading.js` file to a specific route, create a new route group (e.g., `/(overview)`) and then move your `loading.tsx` inside that route group.
<Image
alt="Folder structure showing a loading.tsx and a page.tsx inside the route group"
srcLight="/docs/light/route-group-loading.png"
srcDark="/docs/dark/route-group-loading.png"
width="1600"
height="444"
/>
Now, the `loading.tsx` file will only apply to your dashboard → overview page instead of all your dashboard pages without affecting the URL path structure.
### Creating multiple root layouts
To create multiple [root layouts](/docs/app/api-reference/file-conventions/layout#root-layouts), remove the top-level `layout.js` file, and add a `layout.js` file inside each route group. This is useful for partitioning an application into sections that have a completely different UI or experience. The `<html>` and `<body>` tags need to be added to each root layout.
<Image
alt="Route Groups with Multiple Root Layouts"
srcLight="/docs/light/route-group-multiple-root-layouts.png"
srcDark="/docs/dark/route-group-multiple-root-layouts.png"
width="1600"
height="687"
/>
In the example above, both `(marketing)` and `(shop)` have their own root layout.
</AppOnly>
......@@ -100,7 +100,7 @@ In Next.js:
- **Folders** are used to define the route segments that map to URL segments.
- **Files** (like `page` and `layout`) are used to create UI that is shown for a segment.
To create nested routes, you can nest folders inside each other. For example, to add a route for `/blog`, create a folder called `blog` in the `app` directory. Then, to make `/blog` publicly accessible, add a `page` file:
To create nested routes, you can nest folders inside each other. For example, to add a route for `/blog`, create a folder called `blog` in the `app` directory. Then, to make `/blog` publicly accessible, add a `page.tsx` file:
<Image
alt="File hierarchy showing blog folder and a page.js file"
......@@ -111,6 +111,7 @@ To create nested routes, you can nest folders inside each other. For example, to
/>
```tsx filename="app/blog/page.tsx" switcher
// Dummy imports
import { getPosts } from '@/lib/posts'
import { Post } from '@/ui/post'
......@@ -128,6 +129,7 @@ export default async function Page() {
```
```jsx filename="app/blog/[slug]/page.js" switcher
// Dummy imports
import { getPosts } from '@/lib/posts'
import { Post } from '@/ui/post'
......@@ -170,7 +172,7 @@ export default function Page() {
}
```
> **Good to know**: Wrapping a folder name in square brackets (e.g. `[slug]`) creates a special [dynamic route segment](/docs/app/building-your-application/routing/dynamic-routes) used to generate multiple pages from data. This is useful for blog posts, product pages, etc.
Wrapping a folder name in square brackets (e.g. `[slug]`) creates a [dynamic route segment](/docs/app/building-your-application/routing/dynamic-routes) which is used to generate multiple pages from data. e.g. blog posts, product pages, etc.
## Nesting layouts
......@@ -206,7 +208,7 @@ If you were to combine the two layouts above, the root layout (`app/layout.js`)
## Linking between pages
You can use the [`<Link>` component](/docs/app/api-reference/components/link) to navigate between routes. `<Link>` is a built-in Next.js component that extends the HTML `<a>` tag to provide prefetching and client-side navigation.
You can use the [`<Link>` component](/docs/app/api-reference/components/link) to navigate between routes. `<Link>` is a built-in Next.js component that extends the HTML `<a>` tag to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) and [client-side navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation).
For example, to generate a list of blog posts, import `<Link>` from `next/link` and pass a `href` prop to the component:
......
......@@ -10,19 +10,7 @@ related:
- app/api-reference/components/image
---
Next.js comes with automatic image and font optimization for better performance and user experience. This page will guide you through how to start using them.
## Handling static assets
You can store static files, like images and fonts, under a folder called `public` in the root directory. Files inside `public` can then be referenced by your code starting from the base URL (`/`).
<Image
alt="Folder structure showing app and public folders"
srcLight="/docs/light/public-folder.png"
srcDark="/docs/dark/public-folder.png"
width="1600"
height="282"
/>
Next.js comes with automatic image and font optimization. This page will guide you through how to start using them.
## Optimizing images
......@@ -55,7 +43,15 @@ The `src` property can be a [local](#local-images) or [remote](#remote-images) i
### Local images
To use a local image, `import` your `.jpg`, `.png`, or `.webp` image files from your [`public` folder](#handling-static-assets).
You can store static files, like images and fonts, under a folder called `public` in the root directory. Files inside `public` can then be referenced by your code starting from the base URL (`/`).
<Image
alt="Folder structure showing app and public folders"
srcLight="/docs/light/public-folder.png"
srcDark="/docs/dark/public-folder.png"
width="1600"
height="282"
/>
```tsx filename="app/page.tsx" switcher
import Image from 'next/image'
......@@ -129,9 +125,9 @@ export default function Page() {
}
```
Since Next.js does not have access to remote files during the build process, you'll need to provide the [`width`](/docs/app/api-reference/components/image#width), [`height`](/docs/app/api-reference/components/image#height) and optional [`blurDataURL`](/docs/app/api-reference/components/image#blurdataurl) props manually. The `width` and `height` attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in.
Since Next.js does not have access to remote files during the build process, you'll need to provide the [`width`](/docs/app/api-reference/components/image#width), [`height`](/docs/app/api-reference/components/image#height) and optional [`blurDataURL`](/docs/app/api-reference/components/image#blurdataurl) props manually. The `width` and `height` are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in.
Then, to safely allow images from remote servers, you need to define a list of supported URL patterns in [`next.config.js`](/docs/app/api-reference/config/next-config-js). Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
To safely allow images from remote servers, you need to define a list of supported URL patterns in [`next.config.js`](/docs/app/api-reference/config/next-config-js). Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
```ts filename="next.config.ts" switcher
import { NextConfig } from 'next'
......@@ -173,7 +169,7 @@ module.exports = {
The [`next/font`](/docs/app/api-reference/components/font) module automatically optimizes your fonts and removes external network requests for improved privacy and performance.
It includes **built-in automatic self-hosting** for _any_ font file. This means you can optimally load web fonts with no layout shift.
It includes **built-in self-hosting** for any font file. This means you can optimally load web fonts with no layout shift.
To start using `next/font`, import it from [`next/font/local`](#local-fonts) or [`next/font/google`](#google-fonts), call it as a function with the appropriate options, and set the `className` of the element you want to apply the font to. For example:
......@@ -251,9 +247,9 @@ export default function RootLayout({ children }) {
}
```
We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility. But if you can't use a variable font, you will **need to specify a weight**:
We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility. But if you can't use a variable font, you will need to specify a weight:
```tsx filename="app/layout.tsx" switcher
```tsx filename="app/layout.tsx" highlight={4} switcher
import { Roboto } from 'next/font/google'
const roboto = Roboto({
......@@ -274,7 +270,7 @@ export default function RootLayout({
}
```
```jsx filename="app/layout.js" highlight={1,3-5,9} switcher
```jsx filename="app/layout.js" highlight={4} switcher
import { Roboto } from 'next/font/google'
const roboto = Roboto({
......@@ -293,7 +289,7 @@ export default function RootLayout({ children }) {
### Local fonts
To use a local font, import your font from `next/font/local` and specify the `src` of your local font file in the [`public` folder](#handling-static-assets).
To use a local font, import your font from `next/font/local` and specify the [`src`](/docs/app/api-reference/components/font#src) of your local font file.
```tsx filename="app/layout.tsx" switcher
import localFont from 'next/font/local'
......
......@@ -23,7 +23,7 @@ This page will guide you through how to use each of these approaches.
## CSS Modules
CSS Modules locally scope CSS by generating unique class names. This allows you to use the same class in different files without worrying about collisions.
CSS Modules locally scope CSS by generating unique class names. This allows you to use the same class in different files without worrying about naming collisions.
To start using CSS Modules, create a new file with the extension `.module.css` and import it into any component inside the `app` directory:
......@@ -53,7 +53,7 @@ export default function Page({ children }) {
You can use global CSS to apply styles across your application.
To use global styles, create a new CSS file, for example `app/global.css`:
To use global styles, create a `app/global.css` file and import it in the root layout to apply the styles to **every route** in your application:
```css filename="app/global.css"
body {
......@@ -63,8 +63,6 @@ body {
}
```
Import the file in the root layout (`app/layout.js`) to apply the styles to **every route** in your application:
```tsx filename="app/layout.tsx" switcher
// These styles apply to every route in the application
import './global.css'
......@@ -95,7 +93,7 @@ export default function RootLayout({ children }) {
}
```
> **Good to know:** Global styles can be imported into any layout, page, or component inside the `app` directory. However, since Next.js uses React's built-in support for stylesheets to integrate with Suspense. This built-in support currently does not remove stylesheets as you navigate between routes. Therefore, we recommend using global styles for _truly_ global CSS, and [CSS Modules](#css-modules) for scoped CSS.
> **Good to know:** Global styles can be imported into any layout, page, or component inside the `app` directory. However, since Next.js uses React's built-in support for stylesheets to integrate with Suspense, this currently does not remove stylesheets as you navigate between routes which can lead to conflicts. We recommend using global styles for _truly_ global CSS, and [CSS Modules](#css-modules) for scoped CSS.
## Tailwind CSS
......@@ -106,7 +104,7 @@ export default function RootLayout({ children }) {
To start using Tailwind, install the necessary Tailwind CSS packages:
```bash filename="Terminal"
npm install -D tailwindcss @tailwindcss/postcss postcss
npm install tailwindcss @tailwindcss/postcss postcss
```
### Configuring Tailwind
......@@ -134,7 +132,6 @@ Then, import the styles in the [root layout](/docs/app/api-reference/file-conven
```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next'
// These styles apply to every route in the application
import './globals.css'
......@@ -174,7 +171,7 @@ export default function RootLayout({ children }) {
}
```
Lastly, you can start writing Tailwind's utility classes in your application.
You can then start writing Tailwind's utility classes in your application.
```tsx filename="app/page.tsx" switcher
export default function Page() {
......
......@@ -55,7 +55,7 @@ export default async function Page() {
#### With an ORM or database
You can fetch data with an ORM or database by turning your component into an asynchronous function, and awaiting the call:
Since Server Components are rendered on the server, you can safely make database queries using an ORM or database client. Turn your component into an asynchronous function, and await the call:
```tsx filename="app/blog/page.tsx" switcher
import { db, posts } from '@/lib/db'
......
......@@ -15,22 +15,44 @@ You can update data in Next.js using React's [Server Functions](https://react.de
## Creating Server Functions
A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file. We recommend using a separate file in most instances.
A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file.
```ts filename="app/lib/actions.ts" switcher
'use server'
export async function createPost(formData: FormData) {
'use server'
const title = formData.get('title')
const content = formData.get('content')
// Update data
// Revalidate cache
}
export async function createPost(formData: FormData) {}
export async function deletePost(formData: FormData) {
'use server'
const id = formData.get('id')
export async function deletePost(formData: FormData) {}
// Update data
// Revalidate cache
}
```
```js filename="app/lib/actions.js" switcher
'use server'
export async function createPost(formData) {
'use server'
const title = formData.get('title')
const content = formData.get('content')
export async function createPost(formData) {}
// Update data
// Revalidate cache
}
export async function deletePost(formData) {}
export async function deletePost(formData) {
'use server'
const id = formData.get('id')
// Update data
// Revalidate cache
}
```
### Server Components
......@@ -40,9 +62,8 @@ Server Functions can be inlined in Server Components by adding the `"use server"
```tsx filename="app/page.tsx" switcher
export default function Page() {
// Server Action
async function createPost() {
async function createPost(formData: FormData) {
'use server'
// Update data
// ...
}
......@@ -53,9 +74,8 @@ export default function Page() {
```jsx filename="app/page.js" switcher
export default function Page() {
// Server Action
async function createPost() {
async function createPost(formData: FormData) {
'use server'
// Update data
// ...
}
......@@ -220,6 +240,8 @@ export default function LikeButton({ initialLikes }) {
}
```
## Examples
### Showing a pending state
While executing a Server Function, you can show a loading indicator with React's [`useActionState`](https://react.dev/reference/react/useActionState) hook. This hook returns a `pending` boolean:
......@@ -265,11 +287,10 @@ export function Button() {
After performing an update, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function:
```ts filename="app/lib/actions.ts" switcher
'use server'
import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) {
'use server'
// Update data
// ...
......@@ -278,11 +299,10 @@ export async function createPost(formData: FormData) {
```
```js filename="app/actions.js" switcher
'use server'
import { revalidatePath } from 'next/cache'
export async function createPost(formData) {
'use server'
// Update data
// ...
revalidatePath('/posts')
......
......@@ -18,9 +18,11 @@ Errors can be divided into two categories: [expected errors](#handling-expected-
Expected errors are those that can occur during the normal operation of the application, such as those from [server-side form validation](/docs/app/building-your-application/data-fetching/server-actions-and-mutations#server-side-form-validation) or failed requests. These errors should be handled explicitly and returned to the client.
### Server Actions
### Server Functions
You can use the [`useActionState`](https://react.dev/reference/react/useActionState) hook to manage the state of [Server Functions](https://react.dev/reference/rsc/server-functions) and handle expected errors. Avoid using `try`/`catch` blocks for expected errors. Instead, you can model expected errors as return values, not as thrown exceptions.
You can use the [`useActionState`](https://react.dev/reference/react/useActionState) hook to handle expected errors in [Server Functions](https://react.dev/reference/rsc/server-functions).
For these errors, avoid using `try`/`catch` blocks and throw errors. Instead, model expected errors as return values.
```ts filename="app/actions.ts" switcher
'use server'
......@@ -60,7 +62,7 @@ export async function createPost(prevState, formData) {
}
```
Then, you can pass your action to the `useActionState` hook and use the returned `state` to display an error message.
You can pass your action to the `useActionState` hook and use the returned `state` to display an error message.
```tsx filename="app/ui/form.tsx" highlight={11,19} switcher
'use client'
......
......@@ -117,7 +117,7 @@ Behind-the-scenes, Next.js will stream metadata separately from the UI and injec
There may be cases where you need to fetch the **same** data for metadata and the page itself. To avoid duplicate requests, you can use React's [`cache` function](https://react.dev/reference/react/cache) to memoize the return value and only fetch the data once. For example, to fetch the blog post information for both the metadata and the page:
```tsx filename="app/lib/data.ts" highlight={4} switcher
```tsx filename="app/lib/data.ts" highlight={5} switcher
import { cache } from 'react'
import { db } from '@/app/lib/db'
......@@ -128,7 +128,7 @@ export const getPost = cache(async (slug: string) => {
})
```
```jsx filename="app/lib/data.js" highlight={4} switcher
```jsx filename="app/lib/data.js" highlight={5} switcher
import { cache } from 'react'
import { db } from '@/app/lib/db'
......
......@@ -5,7 +5,6 @@ related:
title: Version guides
description: See the version guides for in-depth upgrade instructions.
links:
- app/building-your-application/upgrading/canary
- app/building-your-application/upgrading/version-15
- app/building-your-application/upgrading/version-14
---
......
......@@ -140,7 +140,7 @@ The two layouts would be nested as such:
> - Layouts do not have access to `pathname` ([learn more](/docs/app/api-reference/file-conventions/layout)). But imported Client Components can access the pathname using [`usePathname`](/docs/app/api-reference/functions/use-pathname) hook.
> - Layouts do not have access to the route segments below itself. To access all 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.
> - You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts.
> - 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).
> - You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to create multiple root layouts. See an [example here](/docs/app/getting-started/project-structure#creating-multiple-root-layouts).
> - **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).
## Templates
......
......@@ -9,82 +9,16 @@ This allows you to organize your route segments and project files into logical g
Route groups are useful for:
- [Organizing routes into groups](#organize-routes-without-affecting-the-url-path) e.g. by site section, intent, or team.
- Enabling [nested layouts](/docs/app/building-your-application/routing/layouts-and-templates) in the same route segment level:
- [Creating multiple nested layouts in the same segment, including multiple root layouts](#creating-multiple-root-layouts)
- [Adding a layout to a subset of routes in a common segment](#opting-specific-segments-into-a-layout)
- [Adding a loading skeleton to specific route in a common segment](#opting-for-loading-skeletons-on-a-specific-route)
- Organizing routes into groups 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
- Opting specific segments into a layout
- Opting for loading skeletons on a specific route
## Convention
A route group can be created by wrapping a folder's name in parenthesis: `(folderName)`
## Examples
### Organize routes without affecting the URL path
To organize routes without affecting the URL, create a group to keep related routes together. The folders in parenthesis will be omitted from the URL (e.g. `(marketing)` or `(shop)`.
<Image
alt="Organizing Routes with Route Groups"
srcLight="/docs/light/route-group-organisation.png"
srcDark="/docs/dark/route-group-organisation.png"
width="1600"
height="930"
/>
Even though routes inside `(marketing)` and `(shop)` share the same URL hierarchy, you can create a different layout for each group by adding a `layout.js` file inside their folders.
<Image
alt="Route Groups with Multiple Layouts"
srcLight="/docs/light/route-group-multiple-layouts.png"
srcDark="/docs/dark/route-group-multiple-layouts.png"
width="1600"
height="768"
/>
### Opting specific segments into a layout
To opt specific routes into a layout, create a new route group (e.g. `(shop)`) and move the routes that share the same layout into the group (e.g. `account` and `cart`). The routes outside of the group will not share the layout (e.g. `checkout`).
<Image
alt="Route Groups with Opt-in Layouts"
srcLight="/docs/light/route-group-opt-in-layouts.png"
srcDark="/docs/dark/route-group-opt-in-layouts.png"
width="1600"
height="930"
/>
### Opting for loading skeletons on a specific route
To apply a [loading skeleton](/docs/app/building-your-application/routing/loading-ui-and-streaming) via a `loading.js` file to a specific route, create a new route group (e.g., `/(overview)`) and then move your `loading.tsx` inside that route group.
<Image
alt="Folder structure showing a loading.tsx and a page.tsx inside the route group"
srcLight="/docs/light/route-group-loading.png"
srcDark="/docs/dark/route-group-loading.png"
width="1600"
height="444"
/>
Now, the `loading.tsx` file will only apply to your dashboard → overview page instead of all your dashboard pages without affecting the URL path structure.
### Creating multiple root layouts
To create multiple [root layouts](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required), remove the top-level `layout.js` file, and add a `layout.js` file inside each route group. This is useful for partitioning an application into sections that have a completely different UI or experience. The `<html>` and `<body>` tags need to be added to each root layout.
<Image
alt="Route Groups with Multiple Root Layouts"
srcLight="/docs/light/route-group-multiple-root-layouts.png"
srcDark="/docs/dark/route-group-multiple-root-layouts.png"
width="1600"
height="687"
/>
In the example above, both `(marketing)` and `(shop)` have their own root layout.
---
> **Good to know**:
>
> - The naming of route groups has no special significance other than for organization. They do not affect the URL path.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment