Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 57 additions & 58 deletions src/content/reference/rsc/use-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,26 @@ canary: true

<Canary>

`'use server'` is needed only if you're [using React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) or building a library compatible with them.
`'use server'` é necessário apenas se você estiver [usando Componentes de Servidor React](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) ou construindo uma biblioteca compatível com eles.

</Canary>


<Intro>

`'use server'` marks server-side functions that can be called from client-side code.
`'use server'` marca funções do lado do servidor que podem ser chamadas a partir de código do lado do cliente.

</Intro>

<InlineToc />

---

## Reference {/*reference*/}
## Referência {/*reference*/}

### `'use server'` {/*use-server*/}

Add `'use server'` at the top of an async function body to mark the function as callable by the client. We call these functions _Server Actions_.
Adicione `'use server'` no início do corpo de uma função assíncrona para marcar a função como chamável pelo cliente. Chamamos essas funções de _Ações do Servidor_.

```js {2}
async function addToCart(data) {
Expand All @@ -34,77 +34,76 @@ async function addToCart(data) {
}
```

When calling a Server Action on the client, it will make a network request to the server that includes a serialized copy of any arguments passed. If the Server Action returns a value, that value will be serialized and returned to the client.
Ao chamar uma Ação do Servidor no cliente, isso fará uma solicitação de rede ao servidor que inclui uma cópia serializada de quaisquer argumentos passados. Se a Ação do Servidor retornar um valor, esse valor será serializado e retornado ao cliente.

Instead of individually marking functions with `'use server'`, you can add the directive to the top of a file to mark all exports within that file as Server Actions that can be used anywhere, including imported in client code.
Em vez de marcar individualmente funções com `'use server'`, você pode adicionar a diretiva ao topo de um arquivo para marcar todas as exportações dentro desse arquivo como Ações do Servidor que podem ser usadas em qualquer lugar, incluindo importadas no código do cliente.

#### Caveats {/*caveats*/}
* `'use server'` must be at the very beginning of their function or module; above any other code including imports (comments above directives are OK). They must be written with single or double quotes, not backticks.
* `'use server'` can only be used in server-side files. The resulting Server Actions can be passed to Client Components through props. See supported [types for serialization](#serializable-parameters-and-return-values).
* To import a Server Action from [client code](/reference/rsc/use-client), the directive must be used on a module level.
* Because the underlying network calls are always asynchronous, `'use server'` can only be used on async functions.
* Always treat arguments to Server Actions as untrusted input and authorize any mutations. See [security considerations](#security).
* Server Actions should be called in a [Transition](/reference/react/useTransition). Server Actions passed to [`<form action>`](/reference/react-dom/components/form#props) or [`formAction`](/reference/react-dom/components/input#props) will automatically be called in a transition.
* Server Actions are designed for mutations that update server-side state; they are not recommended for data fetching. Accordingly, frameworks implementing Server Actions typically process one action at a time and do not have a way to cache the return value.
#### Ressalvas {/*caveats*/}
* `'use server'` deve estar no início de sua função ou módulo; acima de qualquer outro código, incluindo imports (comentários acima das diretivas são OK). Devem ser escritas com aspas simples ou duplas, não com crase.
* `'use server'` só pode ser usado em arquivos do lado do servidor. As Ações do Servidor resultantes podem ser passadas para Componentes do Cliente através de props. Veja os tipos suportados para [serialização](#serializable-parameters-and-return-values).
* Para importar uma Ação do Servidor do [código do cliente](/reference/rsc/use-client), a diretiva deve ser usada em nível de módulo.
* Como as chamadas de rede subjacentes são sempre assíncronas, `'use server'` só pode ser usado em funções assíncronas.
* Sempre trate os argumentos das Ações do Servidor como entrada não confiável e autorize quaisquer mutações. Veja [considerações de segurança](#security).
* As Ações do Servidor devem ser chamadas em uma [Transição](/reference/react/useTransition). Ações do Servidor passadas para [`<form action>`](/reference/react-dom/components/form#props) ou [`formAction`](/reference/react-dom/components/input#props) serão automaticamente chamadas em uma transição.
* As Ações do Servidor são projetadas para mutações que atualizam o estado do lado do servidor; não são recomendadas para busca de dados. Assim, frameworks que implementam Ações do Servidor geralmente processam uma ação por vez e não têm uma maneira de armazenar em cache o valor de retorno.

### Security considerations {/*security*/}
### Considerações de segurança {/*security*/}

Arguments to Server Actions are fully client-controlled. For security, always treat them as untrusted input, and make sure to validate and escape arguments as appropriate.
Os argumentos das Ações do Servidor são totalmente controlados pelo cliente. Para segurança, sempre trate-os como entrada não confiável e certifique-se de validar e escapar os argumentos conforme apropriado.

In any Server Action, make sure to validate that the logged-in user is allowed to perform that action.
Em qualquer Ação do Servidor, certifique-se de validar se o usuário logado tem permissão para executar essa ação.

<Wip>

To prevent sending sensitive data from a Server Action, there are experimental taint APIs to prevent unique values and objects from being passed to client code.
Para evitar o envio de dados sensíveis de uma Ação do Servidor, existem APIs experimentais de contaminação para impedir valores e objetos exclusivos de serem passados para o código do cliente.

See [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) and [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).
Veja [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) e [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).

</Wip>

### Serializable arguments and return values {/*serializable-parameters-and-return-values*/}
### Argumentos e valores de retorno serializáveis {/*serializable-parameters-and-return-values*/}

As client code calls the Server Action over the network, any arguments passed will need to be serializable.
Conforme o código do cliente chama a Ação do Servidor pela rede, quaisquer argumentos passados precisarão ser serializáveis.

Here are supported types for Server Action arguments:
Aqui estão os tipos suportados para os argumentos da Ação do Servidor:

* Primitives
* Primitivos
* [string](https://developer.mozilla.org/en-US/docs/Glossary/String)
* [number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
* [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
* [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
* [null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
* [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
* Iterables containing serializable values
* [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), apenas símbolos registrados no registro global de Símbolos via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
* Iteráveis contendo valores serializáveis
* [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
* [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
* [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
* [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) and [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) e [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instances
* Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties
* Functions that are Server Actions
* instâncias de [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* [objetos](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) simples: aqueles criados com [inicializadores de objeto](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), com propriedades serializáveis
* Funções que são Ações do Servidor
* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

Notably, these are not supported:
* React elements, or [JSX](/learn/writing-markup-with-jsx)
* Functions, including component functions or any other function that is not a Server Action
Notavelmente, esses não são suportados:
* Elementos React, ou [JSX](/learn/writing-markup-with-jsx)
* Funções, incluindo funções de componente ou qualquer outra função que não seja uma Ação do Servidor
* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
* Objects that are instances of any class (other than the built-ins mentioned) or objects with [a null prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)
* Symbols not registered globally, ex. `Symbol('my new symbol')`
* Objetos que são instâncias de qualquer classe (exceto os built-ins mencionados) ou objetos com [um protótipo nulo](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)
* Símbolos que não estão registrados globalmente, ex. `Symbol('meu novo símbolo')`

Os valores de retorno serializáveis suportados são os mesmos que [props serializáveis](/reference/rsc/use-client#passing-props-from-server-to-client-components) para um componente de cliente de limite.

Supported serializable return values are the same as [serializable props](/reference/rsc/use-client#passing-props-from-server-to-client-components) for a boundary Client Component.

## Uso {/*usage*/}

## Usage {/*usage*/}
### Ações do Servidor em formulários {/*server-actions-in-forms*/}

### Server Actions in forms {/*server-actions-in-forms*/}
O caso de uso mais comum das Ações do Servidor será chamar funções do servidor que mutam dados. No navegador, o [elemento de formulário HTML](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) é a abordagem tradicional para um usuário enviar uma mutação. Com Componentes de Servidor React, o React introduz suporte em primeira classe para Ações do Servidor em [formulários](/reference/react-dom/components/form).

The most common use case of Server Actions will be calling server functions that mutate data. On the browser, the [HTML form element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) is the traditional approach for a user to submit a mutation. With React Server Components, React introduces first-class support for Server Actions in [forms](/reference/react-dom/components/form).

Here is a form that allows a user to request a username.
Aqui está um formulário que permite a um usuário solicitar um nome de usuário.

```js [[1, 3, "formData"]]
// App.js
Expand All @@ -119,21 +118,21 @@ export default function App() {
return (
<form action={requestUsername}>
<input type="text" name="username" />
<button type="submit">Request</button>
<button type="submit">Solicitar</button>
</form>
);
}
```

In this example `requestUsername` is a Server Action passed to a `<form>`. When a user submits this form, there is a network request to the server function `requestUsername`. When calling a Server Action in a form, React will supply the form's <CodeStep step={1}>[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)</CodeStep> as the first argument to the Server Action.
Neste exemplo, `requestUsername` é uma Ação do Servidor passada para um `<form>`. Quando um usuário envia este formulário, há uma solicitação de rede para a função do servidor `requestUsername`. Ao chamar uma Ação do Servidor em um formulário, o React fornecerá o <CodeStep step={1}>[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)</CodeStep> do formulário como o primeiro argumento para a Ação do Servidor.

By passing a Server Action to the form `action`, React can [progressively enhance](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) the form. This means that forms can be submitted before the JavaScript bundle is loaded.
Ao passar uma Ação do Servidor para a ação do formulário, o React pode [melhorar progressivamente](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) o formulário. Isso significa que os formulários podem ser enviados antes que o pacote JavaScript seja carregado.

#### Handling return values in forms {/*handling-return-values*/}
#### Tratamento de valores de retorno em formulários {/*handling-return-values*/}

In the username request form, there might be the chance that a username is not available. `requestUsername` should tell us if it fails or not.
No formulário de solicitação de nome de usuário, pode haver a chance de que um nome de usuário não esteja disponível. `requestUsername` deve nos informar se falha ou não.

To update the UI based on the result of a Server Action while supporting progressive enhancement, use [`useActionState`](/reference/react/useActionState).
Para atualizar a UI com base no resultado de uma Ação do Servidor, enquanto suporta melhoria progressiva, use [`useActionState`](/reference/react/useActionState).

```js
// requestUsername.js
Expand All @@ -143,9 +142,9 @@ export default async function requestUsername(formData) {
const username = formData.get('username');
if (canRequest(username)) {
// ...
return 'successful';
return 'bem-sucedido';
}
return 'failed';
return 'falhou';
}
```

Expand All @@ -157,27 +156,27 @@ import { useActionState } from 'react';
import requestUsername from './requestUsername';

function UsernameForm() {
const [state, action] = useActionState(requestUsername, null, 'n/a');
const [state, action] = useActionState(requestUsername, null, 'n/d');

return (
<>
<form action={action}>
<input type="text" name="username" />
<button type="submit">Request</button>
<button type="submit">Solicitar</button>
</form>
<p>Last submission request returned: {state}</p>
<p>Última solicitação de envio retornou: {state}</p>
</>
);
}
```

Note that like most Hooks, `useActionState` can only be called in <CodeStep step={1}>[client code](/reference/rsc/use-client)</CodeStep>.
Observe que assim como a maioria dos Hooks, `useActionState` só pode ser chamado em <CodeStep step={1}>[código do cliente](/reference/rsc/use-client)</CodeStep>.

### Calling a Server Action outside of `<form>` {/*calling-a-server-action-outside-of-form*/}
### Chamando uma Ação do Servidor fora de `<form>` {/*calling-a-server-action-outside-of-form*/}

Server Actions are exposed server endpoints and can be called anywhere in client code.
As Ações do Servidor são endpoints de servidor expostos e podem ser chamadas em qualquer lugar no código do cliente.

When using a Server Action outside of a [form](/reference/react-dom/components/form), call the Server Action in a [Transition](/reference/react/useTransition), which allows you to display a loading indicator, show [optimistic state updates](/reference/react/useOptimistic), and handle unexpected errors. Forms will automatically wrap Server Actions in transitions.
Ao usar uma Ação do Servidor fora de um [formulário](/reference/react-dom/components/form), chame a Ação do Servidor em uma [Transição](/reference/react/useTransition), que permite exibir um indicador de carregamento, mostrar [atualizações de estado otimista](/reference/react/useOptimistic) e lidar com erros inesperados. Os formulários envolverão automaticamente as Ações do Servidor em transições.

```js {9-12}
import incrementLike from './actions';
Expand All @@ -196,8 +195,8 @@ function LikeButton() {

return (
<>
<p>Total Likes: {likeCount}</p>
<button onClick={onClick} disabled={isPending}>Like</button>;
<p>Total de Likes: {likeCount}</p>
<button onClick={onClick} disabled={isPending}>Curtir</button>;
</>
);
}
Expand All @@ -214,4 +213,4 @@ export default async function incrementLike() {
}
```

To read a Server Action return value, you'll need to `await` the promise returned.
Para ler um valor de retorno de uma Ação do Servidor, você precisará usar `await` na promessa retornada.
Loading