"use server"
Edit this page"use server"
will enable functions that only run on the server.
Note: "use server"
functions must be marked async or at least return a promise.
Basic usage
When using "use server"
, regardless of whether server rendering is enabled, the functions it apply to will only run on the server.
To do this, compilation is used to transform the "use server"
function into an RPC call to the server.
If "use server"
is inserted as the first line in a file, the entire file will become server-only.
However, if "use server"
is inserted as the first line of a function, only that function will be server-only:
In both of these examples, the logHello
function, it would only show in the server console regardless of whether rendering was on the server or in the browser.
Usage with Data APIs
Server functions can be used for fetching data and performing actions on the server. The following examples show how to use server functions alongside solid-router's data APIs.
When getUser
or updateUser
are invoked on the client, an http request will be made to the server, which calls the corresponding server function.
Single-flight actions
In the above example, when the updateUser
action is called, a redirect is thrown on the server.
Solid Start can handle this redirect on the server instead of propagating it to the client.
The data for the redirected page is fetched and streamed to the client in the same http request as the updateUser
action, rather than the client requiring a separate http request for the redirected page.
Serialization
Server functions allow the serialization of many different data types in the response, using the Seroval serializer. The full list is available in Seroval's source code.
Meta information
To get a stable function-specific identifier, even for parallel processes or multiple cpu cores or workers, use the getServerFunctionMeta