#[server]Expand description
§Usage
ⓘ
#[server]
async fn blog_posts(category: String) -> Result<Vec<BlogPost>> {
let posts = load_posts(&category).await?;
// maybe do some other work
Ok(posts)
}§Named Arguments
You can use any combination of the following named arguments:
endpoint: a prefix at which the server function handler will be mounted (defaults to/api). Example:endpoint = "/my_api/my_serverfn".input: the encoding for the arguments, defaults toJson<T>- You may customize the encoding of the arguments by specifying a different type for
input. - Any axum
IntoRequestextractor can be used here, and dioxus providesJson<T>: The default axumJsonextractor that decodes JSON-encoded request bodies.Cbor<T>: A custom axumCborextractor that decodes CBOR-encoded request bodies.MessagePack<T>: A custom axumMessagePackextractor that decodes MessagePack-encoded request bodies.
- You may customize the encoding of the arguments by specifying a different type for
output: the encoding for the response (defaults toJson).- The
outputargument specifies how the server should encode the response data. - Acceptable values include:
Json: A response encoded as JSON (default). This is ideal for most web applications.Cbor: A response encoded in the CBOR format for efficient, binary-encoded data.
- The
client: a customClientimplementation that will be used for this server function. This allows customization of the client-side behavior if needed.
§Advanced Usage of input and output Fields
The input and output fields allow you to customize how arguments and responses are encoded and decoded.
These fields impose specific trait bounds on the types you use. Here are detailed examples for different scenarios:
§Adding layers to server functions
Layers allow you to transform the request and response of a server function. You can use layers to add authentication, logging, or other functionality to your server functions. Server functions integrate with the tower ecosystem, so you can use any layer that is compatible with tower.
Common layers include:
tower_http::trace::TraceLayerfor tracing requests and responsestower_http::compression::CompressionLayerfor compressing large responsestower_http::cors::CorsLayerfor adding CORS headers to responsestower_http::timeout::TimeoutLayerfor adding timeouts to requeststower_sessions::service::SessionManagerLayerfor adding session management to requests
You can add a tower Layer to your server function with the middleware attribute:
ⓘ
#[server]
// The TraceLayer will log all requests to the console
#[middleware(tower_http::timeout::TimeoutLayer::new(std::time::Duration::from_secs(5)))]
pub async fn my_wacky_server_fn(input: Vec<String>) -> ServerFnResult<usize> {
unimplemented!()
}