rust-embed embedded assets

Learn how the rust-embed crate packs a folder of web files into the Rust binary at compile time and how to serve those files from Axum with the right content type

A server that reads its frontend files from disk has a weak spot: the files have to be in the right place on every machine the binary runs on. Copy the binary to a new server and forget the folder, and every page returns 404 while the API keeps working. The rust-embed crate removes that weak spot by packing a whole folder of files into the compiled binary itself. After that, the program carries its own frontend inside it, and there is no folder left to forget.

Where This Fits

The idea on this page builds on serving files from disk. The files are the same, an HTML page, a script, and a stylesheet. The change is where they live at run time. Instead of sitting in a folder next to the binary, they are baked into the binary when it is compiled. The handler code looks different because it asks the embedded collection for a file instead of asking the disk, but the HTTP behaviour the browser sees is the same: a path comes in, a file with a content type comes back, and a missing file is a 404.

The Smallest Working Version

Start with the smallest project that embeds one folder and serves one file from it. The layout looks like this:

embedded-demo/
  Cargo.toml
  assets/
    index.html
    app.js
    style.css
  src/
    main.rs

The assets folder holds the files to embed. The HTML page is a small complete page, and the other two files give the server something besides HTML to send.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Demo App</title><link rel="stylesheet" href="/style.css"></head>
<body><h1>Demo App Home</h1><script src="/app.js"></script></body>
</html>
console.log("demo app loaded");
body { font-family: sans-serif; }

The Cargo.toml file adds two crates. rust-embed is the crate that packs the folder into the binary, and mime_guess works out the content type of a file from its extension, so a .js file is served as JavaScript and a .css file as CSS.

[package]
name = "embedded-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
rust-embed = "8.14.0"
mime_guess = "2.0.5"

The server code in src/main.rs defines the embedded collection and one handler that serves the home page from it.

src/main.rs
use axum::{
    http::{header, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
};
use rust_embed::Embed;

#[derive(Embed)]
#[folder = "assets/"]
struct Asset;

async fn index_handler() -> impl IntoResponse {
    match Asset::get("index.html") {
        Some(file) => Ok((
            [(header::CONTENT_TYPE, "text/html")],
            file.data.into_owned(),
        )),
        None => Err(StatusCode::NOT_FOUND),
    }
}

fn app() -> Router {
    Router::new().route("/", get(index_handler))
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3003")
        .await
        .unwrap();
    println!("embedded listening on http://127.0.0.1:3003");
    axum::serve(listener, app()).await.unwrap();
}

Run it with cargo run from the project root and check the home page with curl.

curl -i http://127.0.0.1:3003/
HTTP/1.1 200 OK
content-type: text/html
<!DOCTYPE html>
<html lang="en">

The page comes back with the HTML content type even though no file was read from disk by the handler code. In a debug build the bytes still come from the assets folder on disk, which the section on debug and release behaviour below explains in full. In a release build they come from inside the binary. Either way, the response looks the same from the outside.

Embedding Works:

If curl shows the HTML page with content-type: text/html, the derive macro found the folder, the file was embedded or read, and the handler returned its bytes. That one request proves the whole chain: folder, macro, handler, and response.

The Derive Macro and the Folder Attribute

The three lines that make the embedding happen are short, and each one has a job a beginner should understand.

#[derive(Embed)]
#[folder = "assets/"]
struct Asset;

#[derive(Embed)] is a derive macro, which is a piece of code that runs at compile time and writes more code for you. Here it writes the code that loads every file in the folder into the program. The struct it is attached to, Asset, holds no data of its own. It is an empty struct, a name to hang the generated code on, and nothing else. #[folder = "assets/"] tells the macro which folder to pack. The path is relative to the project, and it must point at a folder that exists when the project is compiled.

The macro generates two methods on the struct, and the rest of this page is built on them.

// What the macro generates, in simplified form
impl Asset {
    pub fn get(file_path: &str) -> Option<rust_embed::EmbeddedFile> {
        // ...
    }

    pub fn iter() -> impl Iterator<Item = Cow<'static, str>> {
        // ...
    }
}

Asset::get("index.html") looks up one file by its path inside the folder and returns Some(file) when it exists and None when it does not. The path is relative to the folder, with no leading slash: "index.html" works, "/index.html" does not, because the embedded names never start with a slash. The returned value is an EmbeddedFile, which has two fields: data, the file bytes, and metadata, information about the file such as a hash of its contents and its last modified time.

Asset::iter() lists every embedded file by name. It returns an iterator of strings like "app.js", "index.html", and "style.css", in no particular order. It is the method to reach for when the program needs to know what it carries, for example to build a list endpoint or to check at startup that an expected file is present.

A note on spelling, because older examples on the internet use a different one: the derive macro used to be written #[derive(RustEmbed)] with use rust_embed::RustEmbed;, and that spelling still compiles in version 8.14.0. The current documentation writes #[derive(Embed)] with use rust_embed::Embed;, and that is the spelling this page uses. If a reader finds the older spelling in a blog post, it is the same macro under its older name, not a different crate.

The Struct Carries No Data:

struct Asset; looks unfinished to a beginner, because most structs have fields. Here the empty struct is correct. The files are not stored in a value of the struct. They are stored in code the macro generates, and the struct name is just the handle the program uses to call get and iter.

Turning an Embedded File into a Response

The index_handler in the smallest example does three things, and each one is worth seeing clearly. First it asks for the file with Asset::get("index.html"). Then it handles both answers: Some(file) builds a response, and None returns a 404. Then it sets the content type header and hands over the bytes.

The return type is Result with two different tuple shapes, and Axum knows how to turn both into responses. Ok((headers, bytes)) becomes a 200 response with those headers and that body. Err(StatusCode::NOT_FOUND) becomes a 404. Writing the handler this way keeps the missing-file case visible in the code instead of hiding it behind an unwrap that would crash the server.

One line in the handler deserves a closer look, because it is where beginners hit their first compile error on this page.

let mime = mime_guess::from_path(&path).first_or_octet_stream();
let headers = [(header::CONTENT_TYPE, mime.to_string())];

mime_guess::from_path looks at the extension of a path and guesses the content type. .first_or_octet_stream() takes the first guess, or falls back to application/octet-stream when the extension is unknown. That fallback means a file with a strange extension still gets served, just as generic binary data, instead of failing. The result is a mime value, and the header needs an owned string, so the code calls .to_string() on it. Writing mime.as_ref() here instead looks natural but does not compile: the header array would borrow a value that belongs to the current function, and the response outlives the function. The compiler reports this as error E0515, "cannot return value referencing local variable mime". Turning the guess into an owned String with .to_string() is the fix, and it is the only change needed.

Borrowing the MIME Guess Does Not Compile:

[(header::CONTENT_TYPE, mime.as_ref())] fails with E0515 because the response would borrow mime, which is dropped when the handler returns. Use mime.to_string() so the header owns its value. This error is easy to hit and easy to fix once the cause is named.

The Concept Behind Embedding Files

Compiling a Rust program turns source code into a binary file, which is the executable program the operating system runs. Normally the binary holds only code. Embedding adds data to that same file: the macro reads each file in the folder at compile time and stores its bytes inside the binary, next to the compiled code.

A useful way to picture it is the difference between a printed book and a library card. A program that reads files from disk is like a book that lists where other books live: it works only while the library is still there. A program with embedded files is like a book with the extra pages bound inside it: heavier to carry, but complete on its own wherever it goes. The cost is binary size, since every embedded byte makes the executable bigger, and the gain is that deployment becomes copying one file.

Why Embed Instead of Reading from Disk

Embedding is the right choice when the files and the program must travel together. A single binary can be copied to a server, put in a container image, or handed to a colleague, and the frontend goes with it. There is no folder to forget, no path to configure, and no difference between the machine the program was built on and the machine it runs on.

Reading from disk fits files that change on their own schedule, for example pages a designer edits on a live server: disk reads pick up edits at once, while embedded files need a rebuild. A project can mix the two: embed the stable app files and read user uploads from disk.

A Richer Complete Example

The smallest example serves one fixed file. A real embedded server needs a handler that serves any file by name, with the right content type, and a 404 for names that are not embedded. That handler is the heart of this page, and it is worth reading slowly.

src/main.rs
use axum::{
    extract::Path,
    http::{header, StatusCode},
    response::IntoResponse,
    routing::get,
    Json, Router,
};
use rust_embed::Embed;

#[derive(Embed)]
#[folder = "assets/"]
struct Asset;

async fn index_handler() -> impl IntoResponse {
    match Asset::get("index.html") {
        Some(file) => Ok((
            [(header::CONTENT_TYPE, "text/html")],
            file.data.into_owned(),
        )),
        None => Err(StatusCode::NOT_FOUND),
    }
}

async fn asset_handler(Path(path): Path<String>) -> impl IntoResponse {
    let path = if path.is_empty() {
        "index.html".to_string()
    } else {
        path
    };
    match Asset::get(&path) {
        Some(file) => {
            let mime = mime_guess::from_path(&path).first_or_octet_stream();
            let headers = [(header::CONTENT_TYPE, mime.to_string())];
            Ok((headers, file.data.into_owned()))
        }
        None => Err(StatusCode::NOT_FOUND),
    }
}

async fn list_files() -> Json<Vec<String>> {
    Json(Asset::iter().map(|name| name.to_string()).collect())
}

fn app() -> Router {
    Router::new()
        .route("/", get(index_handler))
        .route("/files", get(list_files))
        .route("/{*path}", get(asset_handler))
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3003")
        .await
        .unwrap();
    println!("embedded listening on http://127.0.0.1:3003");
    axum::serve(listener, app()).await.unwrap();
}

Three routes share the work. / serves the home page through the fixed handler. /{*path} is a wildcard route, which is a route whose last segment captures the rest of the path, so /app.js gives the handler the string "app.js" and /css/main.css would give "css/main.css". Path(path) is the extractor that pulls that captured string out of the URL and hands it to the handler as a String. /files lists everything embedded, which is useful for checking what the binary carries.

The wildcard handler has one small piece of logic before the lookup. An empty path becomes "index.html", so a request for a bare folder path still lands on the home page. Then the handler asks Asset::get for the file, guesses the content type from the extension, and returns the bytes with that content type. A name that is not embedded returns a 404.

Run the server and check each route. The content types are the proof that the guessing works: JavaScript comes back as JavaScript, CSS as CSS, and a plain text file as plain text.

curl -i http://127.0.0.1:3003/
HTTP/1.1 200 OK
content-type: text/html

curl -i http://127.0.0.1:3003/app.js
HTTP/1.1 200 OK
content-type: text/javascript

curl -i http://127.0.0.1:3003/style.css
HTTP/1.1 200 OK
content-type: text/css

curl -i http://127.0.0.1:3003/version.txt
HTTP/1.1 200 OK
content-type: text/plain
EMBEDDED-VERSION-ONE

curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/nope.html
404

curl http://127.0.0.1:3003/files
["app.js","index.html","style.css","version.txt"]

The version.txt file holds the text EMBEDDED-VERSION-ONE. It exists only so the rebuild test below has something visible to change. The /files answer lists the four embedded names, which is the same list Asset::iter() produces inside the program.

Set the Content Type Yourself:

Returning bare bytes without a content type header sends them as application/octet-stream, which makes the browser download the file instead of showing it. The mime_guess call in the handler exists to stop that. Every file response on this page carries the type guessed from its extension.

Listing Every Embedded File with iter

The /files route in the richer example is small, but it shows the second generated method doing its job. Asset::iter() walks the embedded names, .map(|name| name.to_string()) turns each borrowed name into an owned String, and .collect() gathers them into a Vec<String>, which Json turns into a JSON array.

async fn list_files() -> Json<Vec<String>> {
    Json(Asset::iter().map(|name| name.to_string()).collect())
}

This route is handy beyond debugging: a startup check can call Asset::iter() and fail loudly when an expected file is missing from the build, instead of serving 404s to the first visitors. The key point is that iter reads the same embedded list get searches, so the two methods can never disagree about what the binary holds.

Debug Builds Read from Disk, Release Builds Embed

The most surprising fact about rust-embed is that embedding only happens in release builds by default. In a debug build, which is what cargo run produces, the files are read from the folder on disk each time they are requested. In a release build, which is what cargo run --release produces, the files are baked into the binary at compile time. The documentation for the crate states the rule plainly: in debug mode, and without the debug-embed feature, the folder path is resolved relative to the folder the binary is run from, while in release mode it is resolved relative to the folder holding Cargo.toml.

That difference is easy to prove. Build the release binary, move the assets folder away entirely, and run the binary from a different folder.

cargo build --release --bin embedded
mv assets assets_moved_away
cd /tmp
/home/hatch/workspace/axum-ch17-scratch-b/target/release/embedded
curl -i http://127.0.0.1:3003/
HTTP/1.1 200 OK
content-type: text/html
curl http://127.0.0.1:3003/version.txt
EMBEDDED-VERSION-ONE
curl http://127.0.0.1:3003/files
["app.js","index.html","style.css","version.txt"]

The release binary serves every file with the folder gone and the working folder changed. That is the proof the files are inside the binary: there is no other place they could have come from. Now run the debug binary in the same conditions.

cd /tmp
/home/hatch/workspace/axum-ch17-scratch-b/target/debug/embedded
curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/
404
curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/app.js
404
curl http://127.0.0.1:3003/files
[]

The debug binary returns 404 for both files and an empty list from /files. It looked for the folder next to where it was run, found nothing, and reported the embedded collection as empty. The program did not crash and did not print an error. It simply behaved as if the folder held no files.

Debug and Release Behave Differently Here:

A debug binary that works fine when run from the project root can return 404 for every file when run from another folder, while the release binary works everywhere. When embedded files vanish after a move, check two things before anything else: which build is running, and which folder it was started from.

Embedding in Debug Builds with debug-embed

When the debug behaviour gets in the way, the debug-embed feature switches it off. Enabling the feature makes even debug builds bake the files into the binary, so development and release behave the same way.

rust-embed = { version = "8.14.0", features = ["debug-embed"] }

With that feature turned on, the debug binary serves the files after the folder is moved away, exactly like the release binary did.

curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/
200
curl -i http://127.0.0.1:3003/app.js
HTTP/1.1 200 OK
content-type: text/javascript
curl http://127.0.0.1:3003/version.txt
EMBEDDED-VERSION-ONE

The trade-off is compile time: every rebuild re-reads and re-packs the folder, so a large folder makes debug builds slower. For a small frontend folder the cost is small, and the matching behaviour is worth it when the team keeps tripping over the debug difference. Without the feature, the faster debug cycle is the default, and the release build is the one that proves the embedding works.

Changing a File Needs a Rebuild

Because the files are copied at compile time, editing a file in the folder changes nothing until the project is compiled again. The test below makes that visible using the version.txt file. Change its contents, rebuild the release binary, and check again.

1

Step 1: Edit the file

Change the contents of assets/version.txt from EMBEDDED-VERSION-ONE to EMBEDDED-VERSION-TWO. Do not touch any Rust code.

printf 'EMBEDDED-VERSION-TWO' > assets/version.txt
2

Step 2: Rebuild the binary

Compile the project again so the macro re-reads the folder and packs the new bytes in.

cargo build --release --bin embedded
3

Step 3: Run the new binary and check

Start the freshly built binary and request the file.

curl http://127.0.0.1:3003/version.txt
EMBEDDED-VERSION-TWO

Before the rebuild, the running binary keeps serving EMBEDDED-VERSION-ONE, because the old bytes are still inside it. After the rebuild, the same request returns EMBEDDED-VERSION-TWO. Nothing else changed: no code was edited, no route was added, and no configuration was touched. The rebuild alone moved the new file contents into the binary.

This is the mistake to watch for during development. Editing an HTML file and refreshing the browser shows the old page, and the natural conclusion is that the handler is broken or the browser cached the page. The handler is fine. The binary simply still holds the old bytes. Rebuild, restart, and the new page appears.

The Prefix Attribute

Sometimes the embedded names need a prefix in front of them, for example when two folders are embedded into one program and their file names would collide, or when the lookup code wants names that match the URL paths they are served under. The prefix attribute adds that prefix to every name.

#[derive(Embed)]
#[folder = "assets/"]
#[prefix = "static/"]
struct Prefixed;

With this attribute, the file is fetched as Prefixed::get("static/app.js"), and Prefixed::iter() returns names like "static/app.js", "static/index.html", and "static/style.css". The plain name no longer works: Prefixed::get("app.js") returns None, because the stored name now starts with the prefix. The prefix is part of the name everywhere, in get and in iter, with no exceptions. A beginner who adds a prefix to the struct and forgets to add it to the get calls will see every lookup return None, which looks like the folder went missing when really only the names changed.

Paths That Escape the Folder Are Not Found

Asset::get only knows the names the macro recorded. A path that tries to climb out of the folder, like "../Cargo.toml", is not one of those names, so get returns None and the handler answers 404. That was checked directly: Asset::get("../Cargo.toml") is None, and requesting /..%2FCargo.toml over HTTP returns 404. The handler never touches the disk in a release build, so there is no file path for an attacker to escape through. The lookup is a match against a fixed list of names, and anything not on the list misses, which is why the None branch in the handler matters for mistyped paths too.

A Plain Text Diagram of the Two Timelines

Embedding splits the work across two moments: compile time, when the files are packed in, and request time, when they are served. The diagram shows both.

Compile time (cargo build)
  macro reads the assets/ folder
        |
        v
  file bytes are stored inside the binary
        |
        v
  binary is complete and carries its own files

Request time (server running)
  GET /app.js arrives
        |
        v
  handler calls Asset::get("app.js")
        |
        v
  found? yes -> guess content type, return bytes
  found? no  -> return 404

Nothing on the request path touches the disk in a release build. The only disk access happens at compile time, which is why a rebuilt binary is the only way to change what is served.

Testing the Embedded Server

Two kinds of tests fit this page. The first kind tests the embedded collection directly, with no HTTP involved: a known file is found, a missing file is None, and the listing contains the expected names. The second kind sends fake HTTP requests through the Router with tower::ServiceExt and checks the status and the content type header. Add tower with the util feature as a dev dependency.

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
src/main.rs
#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;

    #[test]
    fn known_file_is_found() {
        let file = Asset::get("app.js");
        assert!(file.is_some());
    }

    #[test]
    fn missing_file_is_none() {
        assert!(Asset::get("nope.html").is_none());
    }

    #[test]
    fn iter_lists_every_file() {
        let names: Vec<String> = Asset::iter().map(|name| name.to_string()).collect();
        assert!(names.contains(&"index.html".to_string()));
        assert!(names.contains(&"app.js".to_string()));
    }

    #[tokio::test]
    async fn embedded_file_served_with_js_content_type() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/app.js")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()["content-type"], "text/javascript");
    }

    #[tokio::test]
    async fn missing_embedded_file_returns_404() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/nope.html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}

Run them with cargo test. All five pass. The content type assertion in the fourth test catches a handler that returns bytes without a header, and the fifth test guards the 404 branch. These tests run against the debug build, so they read the files from the assets folder on disk, and cargo test runs with the project root as its working folder, so the folder is found.

Common Beginner Mistakes

Asking for a file with a leading slash

// Wrong - returns None, and the handler answers 404
Asset::get("/app.js")

Embedded names never start with a slash, so the lookup misses. The fix is to drop the slash: Asset::get("app.js"). The same applies to paths built from URL segments. A wildcard route hands the handler "app.js" without a slash, which is exactly the form get wants, so the common case already works. The mistake appears when code adds a slash of its own while joining path pieces together.

Forgetting to rebuild after editing a file

Editing assets/index.html and refreshing the browser shows the old page. The handler is not broken and the browser is not caching anything. The binary still holds the old bytes, and only cargo build packs the new ones in. Rebuild, restart the server, and the new page appears. During heavy frontend editing, the debug-embed feature does not help here either: it changes where debug builds read from, not when the bytes are packed in.

Adding the folder path relative to the wrong place

The #[folder = "assets/"] path is resolved relative to the folder holding Cargo.toml in release builds, but in debug builds without debug-embed it is resolved relative to the folder the binary is run from. A project that works with cargo run from the project root and breaks when the binary is run from elsewhere is showing this difference, not a bug in the handler. The fix is to run from the project root during development, or to enable the debug-embed feature so debug builds behave like release builds.

Returning bytes with no content type

// Wrong - the browser downloads the file instead of showing it
Ok(file.data.into_owned())

Returning the bytes alone sends them as application/octet-stream. The browser then treats the response as a download rather than a page, a script, or a stylesheet. The fix is the header tuple from the richer example: guess the type with mime_guess::from_path and return it alongside the bytes.

Expecting get to read the disk at run time

In a release build, Asset::get never opens a file. If a file is added to the assets folder after the build, get returns None for it until the next compile. Files that must appear without a rebuild, such as user uploads, do not belong in the embedded folder. They belong on disk, served by a disk-reading service, while the embedded folder holds the stable app files that only change when the program itself is rebuilt.

Two Kinds of Files, Two Kinds of Serving:

Embedded files are frozen at compile time, and uploaded files appear at run time. Mixing the two up causes real bugs: an upload written into the embedded folder is invisible to get, and a frontend file edited on disk is invisible to a release binary. Keep the stable app files embedded and the changing user files on disk.

Final Complete Example

Here is the whole project put together: the dependencies, the embedded folder, the server with its three routes, and the tests.

# Cargo.toml
[package]
name = "embedded-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
rust-embed = "8.14.0"
mime_guess = "2.0.5"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
src/main.rs
use axum::{
    extract::Path,
    http::{header, StatusCode},
    response::IntoResponse,
    routing::get,
    Json, Router,
};
use rust_embed::Embed;

#[derive(Embed)]
#[folder = "assets/"]
struct Asset;

async fn index_handler() -> impl IntoResponse {
    match Asset::get("index.html") {
        Some(file) => Ok((
            [(header::CONTENT_TYPE, "text/html")],
            file.data.into_owned(),
        )),
        None => Err(StatusCode::NOT_FOUND),
    }
}

async fn asset_handler(Path(path): Path<String>) -> impl IntoResponse {
    let path = if path.is_empty() {
        "index.html".to_string()
    } else {
        path
    };
    match Asset::get(&path) {
        Some(file) => {
            let mime = mime_guess::from_path(&path).first_or_octet_stream();
            let headers = [(header::CONTENT_TYPE, mime.to_string())];
            Ok((headers, file.data.into_owned()))
        }
        None => Err(StatusCode::NOT_FOUND),
    }
}

async fn list_files() -> Json<Vec<String>> {
    Json(Asset::iter().map(|name| name.to_string()).collect())
}

fn app() -> Router {
    Router::new()
        .route("/", get(index_handler))
        .route("/files", get(list_files))
        .route("/{*path}", get(asset_handler))
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3003")
        .await
        .unwrap();
    println!("embedded listening on http://127.0.0.1:3003");
    axum::serve(listener, app()).await.unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;

    #[test]
    fn known_file_is_found() {
        let file = Asset::get("app.js");
        assert!(file.is_some());
    }

    #[test]
    fn missing_file_is_none() {
        assert!(Asset::get("nope.html").is_none());
    }

    #[test]
    fn iter_lists_every_file() {
        let names: Vec<String> = Asset::iter().map(|name| name.to_string()).collect();
        assert!(names.contains(&"index.html".to_string()));
        assert!(names.contains(&"app.js".to_string()));
    }

    #[tokio::test]
    async fn embedded_file_served_with_js_content_type() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/app.js")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()["content-type"], "text/javascript");
    }

    #[tokio::test]
    async fn missing_embedded_file_returns_404() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/nope.html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}

The assets folder holds index.html, app.js, style.css, and version.txt. Run cargo test to confirm the five tests pass, then cargo run and check with curl: / returns the page, /app.js returns JavaScript, /style.css returns CSS, /files lists the four names, and /nope.html returns 404. Build with cargo build --release and run the binary from another folder to see the embedding prove itself: every file still answers, with no assets folder in sight. A separate helper crate named axum-embed also exists for serving embedded files, but it is a different crate from rust-embed, and this page teaches the direct rust-embed handler so the mechanism stays visible.

Summary

The decision that matters most with embedded assets is not which handler to write. It is which files deserve to be frozen at compile time. Stable app files, the HTML page, the scripts, the stylesheets, are good candidates: they change when the program changes, they travel with the binary, and they can never be forgotten on a server. Changing user content is a bad candidate: it appears at run time, after the build, and embedding cannot see it.

Use that split as the rule. If a file changes only when the code changes, embed it with rust-embed and serve it with a small handler built on get, iter, and mime_guess. If a file changes on its own schedule, keep it on disk and serve it from there. And keep the debug and release difference in mind while developing: debug reads the folder, release carries it, and the release binary run far from the project folder is the test that proves the embedding is real.