#[server]
Expand description
Declares that a function is a server function.
This means that its body will only run on the server, i.e., when the ssr
feature is enabled.
You can specify one, two, or three arguments to the server function:
- Required: A type name that will be used to identify and register the server function
(e.g.,
MyServerFn
). - Optional: A URL prefix at which the function will be mounted when it’s registered
(e.g.,
"/api"
). Defaults to"/"
. - Optional: either
"Cbor"
(specifying that it should use the binarycbor
format for serialization) or"Url"
(specifying that it should be use a URL-encoded form-data string). Defaults to"Url"
. If you want to use this server function to power a<form>
that will work without WebAssembly, the encoding must be"Url"
.
The server function itself can take any number of arguments, each of which should be serializable
and deserializable with serde
.
ⓘ
#[server(ReadPosts, "/api")]
pub async fn read_posts(how_many: u8, query: String) -> Result<Vec<Post>, ServerFnError> {
// do some work on the server to access the database
todo!()
}
Note the following:
- You must register the server function by calling
T::register()
somewhere in your main function. - Server functions must be
async
. Even if the work being done inside the function body can run synchronously on the server, from the client’s perspective it involves an asynchronous function call. - Server functions must return
Result<T, ServerFnError>
. Even if the work being done inside the function body can’t fail, the processes of serialization/deserialization and the network call are fallible. - Return types must implement Serialize. This should be fairly obvious: we have to serialize arguments to send them to the server, and we need to deserialize the result to return it to the client.
- Arguments must be implement
Serialize
andDeserializeOwned
. They are serialized as anapplication/x-www-form-urlencoded
form data usingserde_urlencoded
or asapplication/cbor
usingcbor
.