Skip to main content

Crate dioxus_server

Crate dioxus_server 

Source
Available on crate feature server only.
Expand description

§Dioxus Fullstack

Crates.io MIT licensed Build Status Discord chat

Website | Guides | API Docs | Chat

Fullstack utilities for the Dioxus framework.

§Features

  • Integrates with the Axum server framework with utilities for serving and rendering Dioxus applications.
  • Server functions allow you to call code on the server from the client as if it were a normal function.
  • Instant RSX Hot reloading with dioxus-hot-reload.
  • Passing root props from the server to the client.

§Example

Quickly build fullstack Rust apps with axum and dioxus.

use dioxus::prelude::*;

fn main() {
    dioxus::launch(|| {
        let mut meaning = use_action(|| get_meaning("life the universe and everything".into()));

        rsx! {
            h1 { "Meaning of life: {meaning:?}" }
            button { onclick: move |_| meaning.call(), "Run a server function" }
        }
    });
}

#[get("/meaning/?of")]
async fn get_meaning(of: String) -> Result<Option<u32>> {
    Ok(of.contains("life").then(|| 42))
}

§Axum Integration

If you have an existing Axum router or you need more control over the server, you can use the DioxusRouterExt trait to integrate with your existing Axum router.

First, make sure your axum dependency is optional and enabled by the server feature flag. Axum cannot be compiled to wasm, so if it is enabled by default, it will cause a compile error:

[dependencies]
dioxus = { version = "*", features = ["fullstack"] }
axum = { version = "0.8.0", optional = true }
tokio = { version = "1.0", features = ["full"], optional = true }
dioxus-cli-config = { version = "*", optional = true }

[features]
server = ["dioxus/server", "dep:axum", "dep:tokio", "dioxus-cli-config"]
web = ["dioxus/web"]

Then we can set up dioxus with the axum server:

#![allow(non_snake_case)]
use dioxus::prelude::*;

// The entry point for the server
#[cfg(feature = "server")]
#[tokio::main]
async fn main() {
    use dioxus_server::DioxusRouterExt;

    // Get the address the server should run on. If the CLI is running, the CLI proxies fullstack into the main address
    // and we use the generated address the CLI gives us
    let address = dioxus::cli_config::fullstack_address_or_localhost();

    // Set up the axum router
    let router = axum::Router::new()
        // You can add a dioxus application to the router with the `serve_dioxus_application` method
        // This will add a fallback route to the router that will serve your component and server functions
        .serve_dioxus_application(dioxus_server::ServeConfig::new(), App);

    // Finally, we can launch the server
    let router = router.into_make_service();
    let listener = tokio::net::TcpListener::bind(address).await.unwrap();
    axum::serve(listener, router).await.unwrap();
}

// For any other platform, we just launch the app
#[cfg(not(feature = "server"))]
fn main() {
    dioxus::launch(App);
}

#[component]
fn App() -> Element {
    let mut meaning = use_signal(|| None);

    rsx! {
        h1 { "Meaning of life: {meaning:?}" }
        button {
            onclick: move |_| async move {
                if let Ok(data) = get_meaning("life the universe and everything".into()).await {
                    meaning.set(data);
                }
            },
            "Run a server function"
        }
    }
}

#[server]
async fn get_meaning(of: String) -> ServerFnResult<Option<u32>> {
    Ok(of.contains("life").then(|| 42))
}

§Getting Started

To get started with full stack Dioxus, check out our getting started guide, or the full stack examples.

§Contributing

  • Report issues on our issue tracker.
  • Join the discord and ask questions!

§License

This project is licensed under the MIT license.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Dioxus by you shall be licensed as MIT without any additional terms or conditions.

Modules§

axum
axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.
config
Types and traits for HTTP responses. Configuration for how to serve a Dioxus application
inventory
githubcrates-iodocs-rs
isrg
Incremental file based incremental rendering
redirect
server
Implementations of the server side of the server function call.
serverfn

Structs§

Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
CachedRender
A render that was cached from a previous render.
FullstackState
State used by FullstackState::render_handler to render a dioxus component with axum
IncrementalRenderer
An incremental renderer.
IncrementalRendererConfig
A configuration for the incremental renderer.
RenderFreshness
Information about the freshness of a rendered response
ServeConfig
A ServeConfig is used to configure how to serve a Dioxus application. It contains information about how to serve static assets, and what content to render with dioxus_ssr.
ServerDocument
A Document provider that collects all contents injected into the head for SSR rendering.
ServerFunction
A function endpoint that can be called from the client.

Enums§

IncrementalRendererError
An error that can occur while rendering a route or retrieving a cached route.
ServerFnError
The error type for the server function system. This enum encompasses all possible errors that can occur during the registration, invocation, and processing of server functions.
StreamingMode
The streaming mode to use while rendering the page

Traits§

DioxusRouterExt
A extension trait with utilities for integrating Dioxus with your Axum router.

Functions§

launch
Launch a fullstack app with the given root component.
launch_cfg
Launch a fullstack app with the given root component, contexts, and config.
render_handler
SSR renderer handler for Axum with added context injection.
router
Create a router that serves the dioxus application at the appropriate base path.
serve
Serve a fullstack dioxus application with a custom axum router.

Type Aliases§

ServerFnResult
A default result type for server functions, which can either be successful or contain an error. The ServerFnResult type is a convenient alias for a Result type that uses ServerFnError as the error type.