'use server'This feature is available in the latest Canary

Canary

'use server' sólo es necesario si estás usando React Server Components o construyendo una librería compatible con ellos.

'use server' marca funciones del lado del servidor que pueden llamarse desde el código del lado del cliente.


Referencia

'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.

async function addToCart(data) {
'use server';
// ...
}

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.

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.

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.
  • To import a server action from client code, 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.
  • Server actions should be called in a transition. Server actions passed to <form action> or formAction 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.

Security considerations

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.

In any server action, make sure to validate that the logged-in user is allowed to perform that action.

En construcción

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.

See experimental_taintUniqueValue and experimental_taintObjectReference.

Serializable arguments and return values

As client code calls the server action over the network, any arguments passed will need to be serializable.

Here are supported types for server action arguments:

Notably, these are not supported:

  • React elements, or JSX
  • Functions, including component functions or any other function that is not a server action
  • Classes
  • Objects that are instances of any class (other than the built-ins mentioned) or objects with a null prototype
  • Symbols not registered globally, ex. Symbol('my new symbol')

Supported serializable return values are the same as serializable props for a boundary Client Component.

Uso

Server actions in forms

The most common use case of server actions will be calling server functions that mutate data. On the browser, the HTML form element 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.

Here is a form that allows a user to request a username.

// App.js

async function requestUsername(formData) {
'use server';
const username = formData.get('username');
// ...
}

export default App() {
<form action={requestUsername}>
<input type="text" name="username" />
<button type="submit">Request</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 FormData as the first argument to the server action.

By passing a server action to the form action, React can progressively enhance the form. This means that forms can be submitted before the JavaScript bundle is loaded.

Handling return values in forms

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.

To update the UI based on the result of a server action while supporting progressive enhancement, use useFormState.

// requestUsername.js
'use server';

export default async function requestUsername(formData) {
const username = formData.get('username');
if (canRequest(username)) {
// ...
return 'successful';
}
return 'failed';
}
// UsernameForm.js
'use client';

import {useFormState} from 'react-dom';
import requestUsername from './requestUsername';

function UsernameForm() {
const [returnValue, action] = useFormState(requestUsername, 'n/a');

return (
<>
<form action={action}>
<input type="text" name="username" />
<button type="submit">Request</button>
</form>
<p>Last submission request returned: {returnValue}</p>
</>
);
}

Note that like most Hooks, useFormState can only be called in client code.

Calling a server action outside of <form>

Server actions are exposed server endpoints and can be called anywhere in client code.

When using a server action outside of a form, call the server action in a transition, which allows you to display a loading indicator, show optimistic state updates, and handle unexpected errors. Forms will automatically wrap server actions in transitions.

import incrementLike from './actions';
import { useState, useTransition } from 'react';

function LikeButton() {
const [isPending, startTransition] = useTransition();
const [likeCount, setLikeCount] = useState(0);

const onClick = () => {
startTransition(async () => {
const currentCount = await incrementLike();
setLikeCount(currentCount);
});
};

return (
<>
<p>Total Likes: {likeCount}</p>
<button onClick={onClick} disabled={isPending}>Like</button>;
</>
);
}
// actions.js
'use server';

let likeCount = 0;
export default async incrementLike() {
likeCount++;
return likeCount;
}

To read a server action return value, you’ll need to await the promise returned.