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

Docs: Update Server Actions Docs (#59080)

- [x] Rename page from `forms-and-mutations` to
`server-actions-and-mutations` to account for examples that don't use
forms.
   - [x] Split `/pages` and `/app` content to make easier to edit 
- [x] Add Security Section
  - [x] Recommend tainting
  - [x] Closures and encryption
  - [x] Overwriting encryption keys
  - [x] CSRF protection | Allowed Origins
- [x] Add examples for Server Actions being called outside forms
  - [x] `useEffect`
  - [x] Event handlers
  - [ ] ~3rd party libraries~
- [x] More form examples
   - [x] Add note on calling actions in `<button>` and `<input> `
   - [x] Add `.bind` example | Recommend bind over hidden input field
 - [x] Recommend `try/catch` for error handling
- [x] Create `serverActions` next.config.js page 
   - [x] Document `allowedOrigins`
   - [x] Document `bodySizeLimit`
   - [x] Add note on Server Actions flag for < v14
- [x] Update error message links
- [x] Remove Server Actions from API reference as it's a React feature.
E.g. We don't have API references for Server Components.
- [ ] Set up redirects:

---------
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
Co-authored-by: 's avatarShu Ding <g@shud.in>
Co-authored-by: 's avatarMichael Novotny <manovotny@gmail.com>
parent c9f859e6
...@@ -160,7 +160,7 @@ export async function POST() { ...@@ -160,7 +160,7 @@ export async function POST() {
} }
``` ```
> **Good to know**: Like API Routes, Route Handlers can be used for cases like handling form submissions. A new abstraction for [handling forms and mutations](/docs/app/building-your-application/data-fetching/forms-and-mutations) that integrates deeply with React is being worked on. > **Good to know**: Like API Routes, Route Handlers can be used for cases like handling form submissions. A new abstraction for [handling forms and mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) that integrates deeply with React is being worked on.
### Route Resolution ### Route Resolution
......
...@@ -17,7 +17,7 @@ There are four ways you can fetch data: ...@@ -17,7 +17,7 @@ There are four ways you can fetch data:
Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree. Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree.
You can use `fetch` with `async`/`await` in Server Components, in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). You can use `fetch` with `async`/`await` in Server Components, in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
For example: For example:
...@@ -117,7 +117,7 @@ Learn more about [time-based revalidation](/docs/app/building-your-application/c ...@@ -117,7 +117,7 @@ Learn more about [time-based revalidation](/docs/app/building-your-application/c
#### On-demand Revalidation #### On-demand Revalidation
Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
Next.js has a cache tagging system for invalidating `fetch` requests across routes. Next.js has a cache tagging system for invalidating `fetch` requests across routes.
......
--- ---
title: Data Fetching Patterns title: Patterns and Best Practices
nav_title: Data Fetching Patterns and Best Practices
description: Learn about common data fetching patterns in React and Next.js. description: Learn about common data fetching patterns in React and Next.js.
--- ---
There are a few recommended patterns and best practices for fetching data in React and Next.js. This page will go over some of the most common patterns and how to use them. There are a few recommended patterns and best practices for fetching data in React and Next.js. This page will go over some of the most common patterns and how to use them.
### Fetching Data on the Server ## Fetching Data on the Server
Whenever possible, we recommend fetching data on the server. This allows you to: Whenever possible, we recommend fetching data on the server. This allows you to:
...@@ -16,9 +17,9 @@ Whenever possible, we recommend fetching data on the server. This allows you to: ...@@ -16,9 +17,9 @@ Whenever possible, we recommend fetching data on the server. This allows you to:
- Reduce client-server [waterfalls](#parallel-and-sequential-data-fetching). - Reduce client-server [waterfalls](#parallel-and-sequential-data-fetching).
- Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance. - Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance.
You can fetch data on the server using Server Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). You can fetch data on the server using Server Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
### Fetching Data Where It's Needed ## Fetching Data Where It's Needed
If you need to use the same data (e.g. current user) in multiple components in a tree, you do not have to fetch data globally, nor forward props between components. Instead, you can use `fetch` or React `cache` in the component that needs the data without worrying about the performance implications of making multiple requests for the same data. If you need to use the same data (e.g. current user) in multiple components in a tree, you do not have to fetch data globally, nor forward props between components. Instead, you can use `fetch` or React `cache` in the component that needs the data without worrying about the performance implications of making multiple requests for the same data.
...@@ -26,7 +27,7 @@ This is possible because `fetch` requests are automatically memoized. Learn more ...@@ -26,7 +27,7 @@ This is possible because `fetch` requests are automatically memoized. Learn more
> **Good to know**: This also applies to layouts, since it's not possible to pass data between a parent layout and its children. > **Good to know**: This also applies to layouts, since it's not possible to pass data between a parent layout and its children.
### Streaming ## Streaming
Streaming and [Suspense](https://react.dev/reference/react/Suspense) are React features that allow you to progressively render and incrementally stream rendered units of the UI to the client. Streaming and [Suspense](https://react.dev/reference/react/Suspense) are React features that allow you to progressively render and incrementally stream rendered units of the UI to the client.
...@@ -57,7 +58,7 @@ When fetching data inside React components, you need to be aware of two data fet ...@@ -57,7 +58,7 @@ When fetching data inside React components, you need to be aware of two data fet
- With **sequential data fetching**, requests in a route are dependent on each other and therefore create waterfalls. There may be cases where you want this pattern because one fetch depends on the result of the other, or you want a condition to be satisfied before the next fetch to save resources. However, this behavior can also be unintentional and lead to longer loading times. - With **sequential data fetching**, requests in a route are dependent on each other and therefore create waterfalls. There may be cases where you want this pattern because one fetch depends on the result of the other, or you want a condition to be satisfied before the next fetch to save resources. However, this behavior can also be unintentional and lead to longer loading times.
- With **parallel data fetching**, requests in a route are eagerly initiated and will load data at the same time. This reduces client-server waterfalls and the total time it takes to load data. - With **parallel data fetching**, requests in a route are eagerly initiated and will load data at the same time. This reduces client-server waterfalls and the total time it takes to load data.
#### Sequential Data Fetching ### Sequential Data Fetching
If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are different (this doesn't apply to requests for the same data as they are automatically [memoized](/docs/app/building-your-application/caching#request-memoization)). If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are different (this doesn't apply to requests for the same data as they are automatically [memoized](/docs/app/building-your-application/caching#request-memoization)).
...@@ -139,7 +140,7 @@ This will prevent the whole route from being blocked by data fetching, and the u ...@@ -139,7 +140,7 @@ This will prevent the whole route from being blocked by data fetching, and the u
> >
> Any fetch requests with `await` will block rendering and data fetching for the entire tree beneath it, unless they are wrapped in a `<Suspense>` boundary or `loading.js` is used. Another alternative is to use [parallel data fetching](#parallel-data-fetching) or the [preload pattern](#preloading-data). > Any fetch requests with `await` will block rendering and data fetching for the entire tree beneath it, unless they are wrapped in a `<Suspense>` boundary or `loading.js` is used. Another alternative is to use [parallel data fetching](#parallel-data-fetching) or the [preload pattern](#preloading-data).
#### Parallel Data Fetching ### Parallel Data Fetching
To fetch data in parallel, you can eagerly initiate requests by defining them outside the components that use the data, then calling them from inside the component. This saves time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved. To fetch data in parallel, you can eagerly initiate requests by defining them outside the components that use the data, then calling them from inside the component. This saves time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved.
...@@ -211,7 +212,7 @@ export default async function Page({ params: { username } }) { ...@@ -211,7 +212,7 @@ export default async function Page({ params: { username } }) {
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. To improve the user experience, you can add a [Suspense Boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming) to break up the rendering work and show part of the result as soon as possible.
### Preloading Data ## Preloading Data
Another way to prevent waterfalls is to use the preload pattern. You can optionally create a `preload` function to further optimize parallel data fetching. With this approach, you don't have to pass promises down as props. The `preload` function can also have any name as it's a pattern, not an API. Another way to prevent waterfalls is to use the preload pattern. You can optionally create a `preload` function to further optimize parallel data fetching. With this approach, you don't have to pass promises down as props. The `preload` function can also have any name as it's a pattern, not an API.
...@@ -310,3 +311,93 @@ The `utils/get-item` exports can be used by Layouts, Pages, or other components ...@@ -310,3 +311,93 @@ The `utils/get-item` exports can be used by Layouts, Pages, or other components
> **Good to know:** > **Good to know:**
> >
> - We recommend using the [`server-only` package](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment) to make sure server data fetching functions are never used on the client. > - We recommend using the [`server-only` package](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment) to make sure server data fetching functions are never used on the client.
## Preventing sensitive data from being exposed to the client
We recommend using React's taint APIs, [`taintObjectReference`](https://react.dev/reference/react/experimental_taintObjectReference) and [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue), to prevent whole object instances or sensitive values from being passed to the client.
To enable tainting in your application, set the Next.js Config `experimental.taint` option to `true`:
```js filename="next.config.js"
module.exports = {
experimental: {
taint: true,
},
}
```
Then pass the object or value you want to taint to the `experimental_taintObjectReference` or `experimental_taintUniqueValue` functions:
```ts filename="app/utils.ts" switcher
import { queryDataFromDB } from './api'
import {
experimental_taintObjectReference,
experimental_taintUniqueValue,
} from 'react'
export async function getUserData() {
const data = await queryDataFromDB()
experimental_taintObjectReference(
'Do not pass the whole user object to the client',
data
)
experimental_taintUniqueValue(
"Do not pass the user's phone number to the client",
data,
data.phoneNumber
)
return data
}
```
```js filename="app/utils.js" switcher
import { queryDataFromDB } from './api'
import {
experimental_taintObjectReference,
experimental_taintUniqueValue,
} from 'react'
export async function getUserData() {
const data = await queryDataFromDB()
experimental_taintObjectReference(
'Do not pass the whole user object to the client',
data
)
experimental_taintUniqueValue(
"Do not pass the user's phone number to the client",
data,
data.phoneNumber
)
return data
}
```
```tsx filename="app/page.tsx" switcher
import { getUserData } from './data'
export async function Page() {
const userData = getUserData()
return (
<ClientComponent
user={userData} // this will cause an error because of taintObjectReference
phoneNumber={userData.phoneNumber} // this will cause an error because of taintUniqueValue
/>
)
}
```
```jsx filename="app/page.js" switcher
import { getUserData } from './data'
export async function Page() {
const userData = getUserData()
return (
<ClientComponent
user={userData} // this will cause an error because of taintObjectReference
phoneNumber={userData.phoneNumber} // this will cause an error because of taintUniqueValue
/>
)
}
```
Learn more about [Security and Server Actions](https://nextjs.org/blog/security-nextjs-server-components-actions).
...@@ -103,4 +103,4 @@ This means the Client Component JavaScript bundle is downloaded and parsed. Once ...@@ -103,4 +103,4 @@ This means the Client Component JavaScript bundle is downloaded and parsed. Once
Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server. Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server.
You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information. You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information.
...@@ -394,7 +394,7 @@ When configuring the different caching mechanisms, it's important to understand ...@@ -394,7 +394,7 @@ When configuring the different caching mechanisms, it's important to understand
### Data Cache and Client-side Router cache ### Data Cache and Client-side Router cache
- Revalidating the Data Cache in a [Route Handler](/docs/app/building-your-application/routing/route-handlers) **will not** immediately invalidate the Router Cache as the Route Handler isn't tied to a specific route. This means Router Cache will continue to serve the previous payload until a hard refresh, or the automatic invalidation period has elapsed. - Revalidating the Data Cache in a [Route Handler](/docs/app/building-your-application/routing/route-handlers) **will not** immediately invalidate the Router Cache as the Route Handler isn't tied to a specific route. This means Router Cache will continue to serve the previous payload until a hard refresh, or the automatic invalidation period has elapsed.
- To immediately invalidate the Data Cache and Router cache, you can use [`revalidatePath`](#revalidatepath) or [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) in a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations). - To immediately invalidate the Data Cache and Router cache, you can use [`revalidatePath`](#revalidatepath) or [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
## APIs ## APIs
...@@ -500,7 +500,7 @@ revalidateTag('a') ...@@ -500,7 +500,7 @@ revalidateTag('a')
There are two places you can use `revalidateTag`, depending on what you're trying to achieve: There are two places you can use `revalidateTag`, depending on what you're trying to achieve:
1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response of a third party event (e.g. webhook). This will not invalidate the Router Cache immediately as the Router Handler isn't tied to a specific route. 1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response of a third party event (e.g. webhook). This will not invalidate the Router Cache immediately as the Router Handler isn't tied to a specific route.
2. [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations) - to revalidate data after a user action (e.g. form submission). This will invalidate the Router Cache for the associated route. 2. [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - to revalidate data after a user action (e.g. form submission). This will invalidate the Router Cache for the associated route.
### `revalidatePath` ### `revalidatePath`
...@@ -513,7 +513,7 @@ revalidatePath('/') ...@@ -513,7 +513,7 @@ revalidatePath('/')
There are two places you can use `revalidatePath`, depending on what you're trying to achieve: There are two places you can use `revalidatePath`, depending on what you're trying to achieve:
1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response to a third party event (e.g. webhook). 1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response to a third party event (e.g. webhook).
2. [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations) - to revalidate data after a user interaction (e.g. form submission, clicking a button). 2. [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - to revalidate data after a user interaction (e.g. form submission, clicking a button).
See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) for more information. See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) for more information.
......
...@@ -5,10 +5,10 @@ related: ...@@ -5,10 +5,10 @@ related:
title: Next Steps title: Next Steps
description: For more information on what to do next, we recommend the following sections description: For more information on what to do next, we recommend the following sections
links: links:
- app/building-your-application/data-fetching/forms-and-mutations - app/building-your-application/data-fetching/server-actions-and-mutations
--- ---
The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/app/building-your-application/rendering/server-components) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/app/building-your-application/rendering/server-components) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
> **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering)** at request time. > **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering)** at request time.
...@@ -62,7 +62,7 @@ export default function Page() { ...@@ -62,7 +62,7 @@ export default function Page() {
A method that takes a cookie name, value, and options and sets the outgoing request cookie. A method that takes a cookie name, value, and options and sets the outgoing request cookie.
> **Good to know**: HTTP does not allow setting cookies after streaming starts, so you must use `.set()` in a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). > **Good to know**: HTTP does not allow setting cookies after streaming starts, so you must use `.set()` in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
```js filename="app/actions.js" ```js filename="app/actions.js"
'use server' 'use server'
...@@ -85,7 +85,7 @@ async function create(data) { ...@@ -85,7 +85,7 @@ async function create(data) {
## Deleting cookies ## Deleting cookies
> **Good to know**: You can only delete cookies in a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). > **Good to know**: You can only delete cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
There are several options for deleting a cookie: There are several options for deleting a cookie:
...@@ -117,7 +117,7 @@ async function create(data) { ...@@ -117,7 +117,7 @@ async function create(data) {
} }
``` ```
> **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). > **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
### `cookies().set(name, value, { maxAge: 0 })` ### `cookies().set(name, value, { maxAge: 0 })`
......
...@@ -3,7 +3,7 @@ title: permanentRedirect ...@@ -3,7 +3,7 @@ title: permanentRedirect
description: API Reference for the permanentRedirect function. description: API Reference for the permanentRedirect function.
--- ---
The `permanentRedirect` function allows you to redirect the user to another URL. `permanentRedirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). The `permanentRedirect` function allows you to redirect the user to another URL. `permanentRedirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 308 (Permanent) HTTP redirect response to the caller. When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 308 (Permanent) HTTP redirect response to the caller.
...@@ -24,7 +24,7 @@ permanentRedirect(path, type) ...@@ -24,7 +24,7 @@ permanentRedirect(path, type)
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
The `type` parameter has no effect when used in Server Components. The `type` parameter has no effect when used in Server Components.
......
...@@ -3,7 +3,7 @@ title: redirect ...@@ -3,7 +3,7 @@ title: redirect
description: API Reference for the redirect function. description: API Reference for the redirect function.
--- ---
The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
When used in a [streaming context](/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller. When used in a [streaming context](/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller.
...@@ -24,7 +24,7 @@ redirect(path, type) ...@@ -24,7 +24,7 @@ redirect(path, type)
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
The `type` parameter has no effect when used in Server Components. The `type` parameter has no effect when used in Server Components.
......
---
title: Server Actions
nav_title: Server Actions
description: API Reference for Next.js Server Actions.
related:
title: Next Steps
description: For more information on what to do next, we recommend the following sections
links:
- app/building-your-application/data-fetching/forms-and-mutations
---
{/* TODO: This page will need to link back to React docs mentioned at the bottom */}
Next.js integrates with React Actions to provide a built-in solution for [server mutations](/docs/app/building-your-application/data-fetching/forms-and-mutations).
## Convention
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"`](https://react.dev/reference/react/use-server) directive at the top of the function body. `"use server"` ensures this function is only ever executed on the server.
This function should have [serializable arguments](https://developer.mozilla.org/docs/Glossary/Serialization) and a [serializable return value](https://developer.mozilla.org/docs/Glossary/Serialization).
```jsx filename="app/page.js" highlight={2}
export default function ServerComponent() {
async function myAction() {
'use server'
// ...
}
}
```
### With Client Components
#### Import
Create your Server 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:
```js 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 (
<form action={myAction}>
<button type="submit">Add to Cart</button>
</form>
)
}
```
> **Good to know**: 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.
#### Props
In some cases, you might want to pass down a Server Action to a Client Component as a prop.
```jsx
<ClientComponent myAction={updateItem} />
```
```jsx filename="app/client-component.jsx"
'use client'
export default function ClientComponent({ myAction }) {
return (
<form action={myAction}>
<input type="text" name="name" />
<button type="submit">Update Item</button>
</form>
)
}
```
### Binding Arguments
You can bind arguments to a Server Action using the `bind` method. This allows you to create a new Server Action with some arguments already bound. This is beneficial when you want to pass extra arguments to a Server Action.
```jsx filename="app/client-component.jsx" highlight={6}
'use client'
import { updateUser } from './actions'
export function UserProfile({ userId }) {
const updateUserWithId = updateUser.bind(null, userId)
return (
<form action={updateUserWithId}>
<input type="text" name="name" />
<button type="submit">Update User Name</button>
</form>
)
}
```
And then, the `updateUser` Server Action will always receive the `userId` argument, in addition to the form data:
```js filename="app/actions.js"
'use server'
export async function updateUser(userId, formData) {
// ...
}
```
> **Good to know**: `.bind` of a Server Action works in both Server and Client Components. It also supports [Progressive Enhancement](#progressive-enhancement).
## Invocation
You can invoke Server Actions using the following methods:
- Using `action`: React's `action` prop allows invoking a Server Action on a `<form>` element.
- Using `formAction`: React's `formAction` prop allows handling `<button>`, `<input type="submit">`, and `<input type="image">` elements in a `<form>`.
- Custom Invocation with `startTransition`: Invoke Server Actions without using `action` or `formAction` by using `startTransition`. This method **disables [Progressive Enhancement](#progressive-enhancement)**.
## Progressive Enhancement
Progressive enhancement allows a `<form>` to function properly without JavaScript, or with JavaScript disabled. This allows users to interact with the form and submit data even if the JavaScript for the form hasn't been loaded yet or if it fails to load.
React Actions (both server and client) support progressive enhancement, using one of two strategies:
- If a **Server Action** is passed directly to a `<form>`, the form is interactive **even if JavaScript is disabled**.
- If a **Client Action** is passed to a `<form>`, the form is still interactive, but the action will be placed in a queue until the form has hydrated. React prioritizes the action, so it still happens quickly.
In both cases, the form is interactive before hydration occurs. Although Server Actions have the additional benefit of not relying on client JavaScript, you can still compose additional behavior with Client Actions where desired without sacrificing interactivity.
## Size Limitation
By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data.
However, you can configure this limit using the `serverActions.bodySizeLimit` option. It can take the number of bytes or any string format supported by bytes, for example `1000`, `'500kb'` or `'3mb'`.
```js filename="next.config.js"
module.exports = {
experimental: {
serverActions: {
bodySizeLimit: '2mb',
},
},
}
```
## Additional Resources
The following React API pages are currently being documented:
- [`"use server"`](https://react.dev/reference/react/use-server)
- [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus)
- [`useFormState`](https://react.dev/reference/react-dom/hooks/useFormState)
- [`useOptimistic`](https://react.dev/reference/react/useOptimistic)
- [`<form>`](https://react.dev/reference/react-dom/components/form)
---
title: serverActions
description: Configure Server Actions behavior in your Next.js application.
---
Options for configuring Server Actions behavior in your Next.js application.
## `allowedOrigins`
A list of extra safe origin domains from which Server Actions can be invoked. Next.js compares the origin of a Server Action request with the host domain, ensuring they match to prevent CSRF attacks. If not provided, only the same origin is allowed.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
serverActions: {
allowedOrigins: ['my-proxy.com'],
},
},
}
```
## `bodySizeLimit`
By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data, as well as potential DDoS attacks.
However, you can configure this limit using the `serverActions.bodySizeLimit` option. It can take the number of bytes or any string format supported by bytes, for example `1000`, `'500kb'` or `'3mb'`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
serverActions: {
bodySizeLimit: '2mb',
},
},
}
```
## Enabling Server Actions (v13)
Server Actions became a stable feature in Next.js 14, and are enabled by default. However, if you are using an earlier version of Next.js, you can enable them by setting `experimental.serverActions` to `true`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const config = {
experimental: {
serverActions: true,
},
}
module.exports = config
```
...@@ -44,7 +44,7 @@ Here are some common authentication solutions that support the App Router: ...@@ -44,7 +44,7 @@ Here are some common authentication solutions that support the App Router:
### How can I set cookies? ### How can I set cookies?
You can set cookies in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations#setting-cookies) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) using the [`cookies`](/docs/app/api-reference/functions/cookies) function. You can set cookies in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations#cookies) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) using the [`cookies`](/docs/app/api-reference/functions/cookies) function.
Since HTTP does not allow setting cookies after streaming starts, you cannot set cookies from a page or layout directly. You can also set cookies from [Middleware](/docs/app/building-your-application/routing/middleware#using-cookies). Since HTTP does not allow setting cookies after streaming starts, you cannot set cookies from a page or layout directly. You can also set cookies from [Middleware](/docs/app/building-your-application/routing/middleware#using-cookies).
...@@ -64,7 +64,7 @@ Yes. You can view [Next.js Commerce](https://vercel.com/templates/next.js/nextjs ...@@ -64,7 +64,7 @@ Yes. You can view [Next.js Commerce](https://vercel.com/templates/next.js/nextjs
- [Routing Fundamentals](/docs/app/building-your-application/routing) - [Routing Fundamentals](/docs/app/building-your-application/routing)
- [Data Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) - [Data Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating)
- [Forms and Mutations](/docs/app/building-your-application/data-fetching/forms-and-mutations) - [Forms and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations)
- [Caching](/docs/app/building-your-application/caching) - [Caching](/docs/app/building-your-application/caching)
- [Rendering Fundamentals](/docs/app/building-your-application/rendering) - [Rendering Fundamentals](/docs/app/building-your-application/rendering)
- [Server Components](/docs/app/building-your-application/rendering/server-components) - [Server Components](/docs/app/building-your-application/rendering/server-components)
......
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