use server
Learn how to use the use server directive to execute code on the server.
The use server directive designates a function or file to be executed on the server side. It can be used at the top of a file to indicate that all functions in the file are server-side, or inline at the top of a function to mark the function as a Server Function. This is a React feature.
Using use server at the top of a file
The following example shows a file with a use server directive at the top. All functions in the file are executed on the server.
Using Server Functions in a Client Component
To use Server Functions in Client Components you need to create your Server Functions in a dedicated file using the use server directive at the top of the file. These Server Functions can then be imported into Client and Server Components and executed.
Assuming you have a fetchUsers Server Function in actions.ts:
Then you can import the fetchUsers Server Function into a Client Component and execute it on the client-side.
Using use server inline
In the following example, use server is used inline at the top of a function to mark it as a Server Function:
Security considerations
Design your data access functions as secure primitives: validate inputs, check authentication and authorization, and constrain return types to only what the caller needs. When Server Functions delegate to a Data Access Layer, these guarantees live in one place and apply consistently.
Authentication and authorization
Always authenticate and authorize users before performing sensitive server-side operations. Read authentication from cookies or headers rather than accepting tokens as function parameters.
Return values
Server Function return values are serialized and sent to the client. Only return data the UI needs, not raw database records. See the Data Security guide for more details.
Reference
See the React documentation for more information on use server.