Crate dioxus_fullstack

Source
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

Full stack Dioxus in under 30 lines of code

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

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))
}

§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::*;
use dioxus_fullstack::ServeConfig;

// The entry point for the server
#[cfg(feature = "server")]
#[tokio::main]
async fn main() {
    // 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(ServeConfig::new().unwrap(), 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.

Re-exports§

pub use server_fn::ServerFn as _;

Modules§

client
Implementations of the client side of the server function call.
codec
Encodings for arguments and results. The serialization/deserialization process for server functions consists of a series of steps, each of which is represented by a different trait:
history
A history provider for fullstack apps that is compatible with hydration.
server
Implementations of the server side of the server function call.
server_fn
Server Functions

Structs§

BoxedStream
A boxed stream type that can be used with the websocket protocol.
FullstackHistory
A history provider for fullstack apps that is compatible with hydration.
FullstackWebDocument
A document provider for fullstack web clients
StreamingContext
The context dioxus fullstack provides for the status of streaming responses on the server
Websocket
The websocket protocol that encodes the input and output streams using a websocket connection.

Enums§

Format
Encode format type
ServerFnError
An error type for server functions. This may either be an error that occurred while running the server function logic, or an error that occurred while communicating with the server inside the server function crate.
StreamingStatus
The status of the streaming response

Traits§

ContentType
A trait for types with an associated content type.
Decodes
A trait for types that can be decoded from a bytes for a response body.
Encodes
A trait for types that can be encoded into a bytes for a request body.
FormatType
Data format representation
ServerFn
Defines a function that runs only on the server, but can be called from the server or the client.

Functions§

commit_initial_chunk
Commit the initial chunk of the response. This will be called automatically if you are using the dioxus router when the suspense boundary above the router is resolved. Otherwise, you will need to call this manually to start the streaming part of the response.
current_status
Get the current status of the streaming response. This method is reactive and will cause the current reactive context to rerun when the status changes.
get_server_url
Returns the root server URL for all server functions.
set_server_url
Set the root server URL that all server function paths are relative to for the client.
use_server_cached
This allows you to send data from the server to the client. The data is serialized into the HTML on the server and hydrated on the client.
use_server_future
Runs a future with a manual list of dependencies and returns a resource with the result if the future is finished or a suspended error if it is still running.

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.

Attribute Macros§

server
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 on this crate.