This is the developer documentation for Dioxus from /learn/0.7/tutorial/backend. # Adding a Backend Dioxus is a *fullstack* framework, enabling you to seamlessly build your frontend alongside your backend. We provide a number of utilities like *Server Functions*, *Server Futures*, and *Server State* for you to integrate into your apps. In this chapter, we'll cover loading and saving state to our backend with *Server Functions*. For an in-depth guide on fullstack, check out the dedicated [Fullstack Guide](../essentials/fullstack/index.md). ## Enabling Fullstack Before we can start using server functions, we need to enable the "fullstack" feature on Dioxus in our Cargo.toml. ````toml [dependencies] dioxus = { version = "0.7.0", features = ["fullstack"] } ```` We also need to add the "server" feature to our app's features in the Cargo.toml and remove the default web target. ````toml [features] default = [] # <----- remove the default web target web = ["dioxus/web"] desktop = ["dioxus/desktop"] mobile = ["dioxus/mobile"] server = ["dioxus/server"] # <----- add this additional target ```` If you selected *yes* to the "use fullstack?" prompt when creating your app, you will already have this set up! > > 📣 Unfortunately, `dx` doesn't know how to hot-reload this change, so we'll need to restart the dev server. Now instead of running `dx serve`, you need to run with a manual platform with `dx serve --web`. Give your app a moment to build again and make sure that the "fullstack" feature is enabled in the dashboard. ![Fullstack Enabled](/assets/06_docs/serve_with_fullstack.png) ## Server Functions: an inline RPC system Dioxus integrates with the [axum](https://crates.io/crates/axum) crate to provide a simple inline communication system for your apps. Server functions makes it easy to build your app's backend with just basic Rust functions. Server Functions are `async` functions annotated with the a procedural macro (like post/get). A typical server function looks like this: ````rs@guide_backend.rs #[post("/api/save_dog")] async fn save_dog(image: String) -> Result<()> { Ok(()) } ```` Every server function is an async function that takes some parameters and returns a `Result<()>`. Whenever the client calls the server function, it sends an HTTP request to a corresponding endpoint on the server. The parameters of the server function are serialized as the body of the HTTP request. As a result, each argument must be serializable. On the client, the server function expands to a `reqwest` call: ````rs@guide_backend.rs // on the client: async fn save_dog(image: String) -> Result<()> { reqwest::Client::new() .post("http://localhost:8080/api/save_dog") .json(&image) .send() .await?; Ok(()) } ```` On the server, the server function expands to an [axum](https://github.com/tokio-rs/axum) handler: ````rs@guide_backend.rs // on the server: struct SaveDogArgs { image: String, } async fn save_dog(Json(args): Json) -> Result<()> { Ok(()) } ```` When `dioxus::launch` is called, the server functions are automatically registered for you and set up as an Axum router. In some cases, the `dioxus::launch` function might be too limiting for your use-case on the server. Dioxus provides an alternative entrypoint for your app on the server with `dioxus::serve`. This lets you return an Axum router while still having hot-reload, logging, and devtools wired up automatically. ````rs@guide_backend.rs fn main() { #[cfg(not(feature = "server"))] dioxus::launch(App); #[cfg(feature = "server")] dioxus::serve(|| async move { // Create a new axum router for our Dioxus app let router = dioxus::server::router(App); // .. customize it however you want .. // And then return it Ok(router) }) } ```` ## The Client/Server split When Dioxus builds your fullstack apps, it actually creates two separate applications: the server and the client. To achieve this, `dx` passes different features to each build. * The client is built with `--features web` * The server is built with `--features server` ![Server Client Split](/assets/06_docs/server_split.png) When embedding server code in our apps, we need to be careful about which code gets compiled. The body of the server function is designed to only be *executed on the server* - not the client. Any code configured by the `"server"` feature will not be present in the final app. Conversely, any code not configured by the `"server"` feature *will* make it into the final app. ````rs@guide_backend.rs // ❌ this will leak your DB_PASSWORD to your client app! static DB_PASSWORD: &str = "1234"; #[post("/api/do_thing")] async fn DoThing() -> Result<()> { connect_to_db(DB_PASSWORD).await // ... } ```` Instead, we recommend placing server-only code within modules configured for the `"server"` feature. ````rs@guide_backend.rs // ✅ code in this module can only be accessed on the server #[cfg(feature = "server")] mod server_utils { pub static DB_PASSWORD: &str = "1234"; } ```` In addition to the "server" feature, Dioxus expects a client side rendering feature like "web" or "desktop". Some libraries like web-sys only work when running in the browser, so make sure to not run specific client code in your server functions or before your `launch`. You can place client only code under a config for a client target feature like "web". ````rs@guide_backend.rs fn main() { // ❌ attempting to use web_sys on the server will panic! let window = web_sys::window(); // .. dioxus::launch(App); } ```` ## Managing Dependencies Some dependencies like [Tokio](https://github.com/tokio-rs/tokio) only compile properly when targeting native platforms. Other dependencies like [jni-sys](https://github.com/jni-rs/jni-sys) only work properly when running on a specific platform. In these cases, you'll want to make sure that these dependencies are only compiled when a particular feature is enabled. To do this, we can use Rust's `optional` [flag on dependencies in our Cargo.toml](https://doc.rust-lang.org/cargo/reference/features.html#optional-dependencies). ````toml [dependencies] tokio = { version = "1", optional = true } [features] default = [] server = ["dep:tokio"] ```` Eventually, if your project becomes large enough, you might want to pull your server functions out into their own crate to be used across different apps. We'd create a `server` crate in our workspace: ````sh ├── Cargo.toml └── crates    ├── dashboard    ├── marketplace    └── server ```` And then we'd import the server functions in our app, disabling their `"server"` feature. ````toml [dependencies] server = { workspace = true, default-features = false } ```` We provide a longer guide about the details of managing dependencies across the server and the client [here](../essentials/fullstack/project_setup.md). ## Our HotDog Server Function Revisiting our HotDog app, let's create a new server function that saves our favorite dog to a file called `dogs.txt`. In production, you'd want to use a proper database as covered in [the next chapter](databases.md), but for now we'll use a simple file to test things out. ````rs@guide_backend.rs // Expose a `save_dog` endpoint on our server that takes an "image" parameter #[post("/api/save_dog")] async fn save_dog(image: String) -> Result<()> { use std::io::Write; // Open the `dogs.txt` file in append-only mode, creating it if it doesn't exist; let mut file = std::fs::OpenOptions::new() .write(true) .append(true) .create(true) .open("dogs.txt") .unwrap(); // And then write a newline to it with the image url file.write_fmt(format_args!("{image}\n")); Ok(()) } ```` ### Calling the server function Now, in our client code, we can actually call the server function. ````rs@guide_backend.rs fn DogView() -> Element { let mut img_src = use_resource(snipped!()); // ... rsx! { // ... div { id: "buttons", // ... button { id: "save", onclick: move |_| async move { let current = img_src.cloned().unwrap(); img_src.restart(); _ = save_dog(current).await; }, "save!" } } } } } ```` Wow, our app is really coming together! ![Working Server Functions](/assets/06_docs/dog-save-serverfn.mp4) Server functions are extremely capable and can even be used during server-side-rendering. Check out the complete [fullstack guide](../essentials/fullstack/index.md) for more information. # Adding a Backend Dioxus is a *fullstack* framework, enabling you to seamlessly build your frontend alongside your backend. We provide a number of utilities like *Server Functions*, *Server Futures*, and *Server State* for you to integrate into your apps. In this chapter, we'll cover loading and saving state to our backend with *Server Functions*. For an in-depth guide on fullstack, check out the dedicated [Fullstack Guide](../essentials/fullstack/index.md). ## Enabling Fullstack Before we can start using server functions, we need to enable the "fullstack" feature on Dioxus in our Cargo.toml. ````toml [dependencies] dioxus = { version = "0.7.0", features = ["fullstack"] } ```` We also need to add the "server" feature to our app's features in the Cargo.toml and remove the default web target. ````toml [features] default = [] # <----- remove the default web target web = ["dioxus/web"] desktop = ["dioxus/desktop"] mobile = ["dioxus/mobile"] server = ["dioxus/server"] # <----- add this additional target ```` If you selected *yes* to the "use fullstack?" prompt when creating your app, you will already have this set up! > > 📣 Unfortunately, `dx` doesn't know how to hot-reload this change, so we'll need to restart the dev server. Now instead of running `dx serve`, you need to run with a manual platform with `dx serve --web`. Give your app a moment to build again and make sure that the "fullstack" feature is enabled in the dashboard. ![Fullstack Enabled](/assets/06_docs/serve_with_fullstack.png) ## Server Functions: an inline RPC system Dioxus integrates with the [axum](https://crates.io/crates/axum) crate to provide a simple inline communication system for your apps. Server functions makes it easy to build your app's backend with just basic Rust functions. Server Functions are `async` functions annotated with the a procedural macro (like post/get). A typical server function looks like this: ````rs@guide_backend.rs #[post("/api/save_dog")] async fn save_dog(image: String) -> Result<()> { Ok(()) } ```` Every server function is an async function that takes some parameters and returns a `Result<()>`. Whenever the client calls the server function, it sends an HTTP request to a corresponding endpoint on the server. The parameters of the server function are serialized as the body of the HTTP request. As a result, each argument must be serializable. On the client, the server function expands to a `reqwest` call: ````rs@guide_backend.rs // on the client: async fn save_dog(image: String) -> Result<()> { reqwest::Client::new() .post("http://localhost:8080/api/save_dog") .json(&image) .send() .await?; Ok(()) } ```` On the server, the server function expands to an [axum](https://github.com/tokio-rs/axum) handler: ````rs@guide_backend.rs // on the server: struct SaveDogArgs { image: String, } async fn save_dog(Json(args): Json) -> Result<()> { Ok(()) } ```` When `dioxus::launch` is called, the server functions are automatically registered for you and set up as an Axum router. In some cases, the `dioxus::launch` function might be too limiting for your use-case on the server. Dioxus provides an alternative entrypoint for your app on the server with `dioxus::serve`. This lets you return an Axum router while still having hot-reload, logging, and devtools wired up automatically. ````rs@guide_backend.rs fn main() { #[cfg(not(feature = "server"))] dioxus::launch(App); #[cfg(feature = "server")] dioxus::serve(|| async move { // Create a new axum router for our Dioxus app let router = dioxus::server::router(App); // .. customize it however you want .. // And then return it Ok(router) }) } ```` ## The Client/Server split When Dioxus builds your fullstack apps, it actually creates two separate applications: the server and the client. To achieve this, `dx` passes different features to each build. * The client is built with `--features web` * The server is built with `--features server` ![Server Client Split](/assets/06_docs/server_split.png) When embedding server code in our apps, we need to be careful about which code gets compiled. The body of the server function is designed to only be *executed on the server* - not the client. Any code configured by the `"server"` feature will not be present in the final app. Conversely, any code not configured by the `"server"` feature *will* make it into the final app. ````rs@guide_backend.rs // ❌ this will leak your DB_PASSWORD to your client app! static DB_PASSWORD: &str = "1234"; #[post("/api/do_thing")] async fn DoThing() -> Result<()> { connect_to_db(DB_PASSWORD).await // ... } ```` Instead, we recommend placing server-only code within modules configured for the `"server"` feature. ````rs@guide_backend.rs // ✅ code in this module can only be accessed on the server #[cfg(feature = "server")] mod server_utils { pub static DB_PASSWORD: &str = "1234"; } ```` In addition to the "server" feature, Dioxus expects a client side rendering feature like "web" or "desktop". Some libraries like web-sys only work when running in the browser, so make sure to not run specific client code in your server functions or before your `launch`. You can place client only code under a config for a client target feature like "web". ````rs@guide_backend.rs fn main() { // ❌ attempting to use web_sys on the server will panic! let window = web_sys::window(); // .. dioxus::launch(App); } ```` ## Managing Dependencies Some dependencies like [Tokio](https://github.com/tokio-rs/tokio) only compile properly when targeting native platforms. Other dependencies like [jni-sys](https://github.com/jni-rs/jni-sys) only work properly when running on a specific platform. In these cases, you'll want to make sure that these dependencies are only compiled when a particular feature is enabled. To do this, we can use Rust's `optional` [flag on dependencies in our Cargo.toml](https://doc.rust-lang.org/cargo/reference/features.html#optional-dependencies). ````toml [dependencies] tokio = { version = "1", optional = true } [features] default = [] server = ["dep:tokio"] ```` Eventually, if your project becomes large enough, you might want to pull your server functions out into their own crate to be used across different apps. We'd create a `server` crate in our workspace: ````sh ├── Cargo.toml └── crates    ├── dashboard    ├── marketplace    └── server ```` And then we'd import the server functions in our app, disabling their `"server"` feature. ````toml [dependencies] server = { workspace = true, default-features = false } ```` We provide a longer guide about the details of managing dependencies across the server and the client [here](../essentials/fullstack/project_setup.md). ## Our HotDog Server Function Revisiting our HotDog app, let's create a new server function that saves our favorite dog to a file called `dogs.txt`. In production, you'd want to use a proper database as covered in [the next chapter](databases.md), but for now we'll use a simple file to test things out. ````rs@guide_backend.rs // Expose a `save_dog` endpoint on our server that takes an "image" parameter #[post("/api/save_dog")] async fn save_dog(image: String) -> Result<()> { use std::io::Write; // Open the `dogs.txt` file in append-only mode, creating it if it doesn't exist; let mut file = std::fs::OpenOptions::new() .write(true) .append(true) .create(true) .open("dogs.txt") .unwrap(); // And then write a newline to it with the image url file.write_fmt(format_args!("{image}\n")); Ok(()) } ```` ### Calling the server function Now, in our client code, we can actually call the server function. ````rs@guide_backend.rs fn DogView() -> Element { let mut img_src = use_resource(snipped!()); // ... rsx! { // ... div { id: "buttons", // ... button { id: "save", onclick: move |_| async move { let current = img_src.cloned().unwrap(); img_src.restart(); _ = save_dog(current).await; }, "save!" } } } } } ```` Wow, our app is really coming together! ![Working Server Functions](/assets/06_docs/dog-save-serverfn.mp4) Server functions are extremely capable and can even be used during server-side-rendering. Check out the complete [fullstack guide](../essentials/fullstack/index.md) for more information.