Returning &'static str Responses in Axum

Learn how to return static string literals from Axum handlers using the &'static str type, why it works, common pitfalls, and complete examples for beginners.

When you build a web server with Axum, every handler must produce a response. Axum provides many built-in types that can be returned directly. This page focuses on one of the simplest: &'static str. It is the type of a string literal in Rust, like "Hello, world!". Because string literals are embedded in your program and live forever, they are safe to return as a response without any copying or ownership concerns. By the end of this page you will know exactly what &'static str means, why Axum accepts it as a response, how to use it in many realistic handlers, and what mistakes to avoid.

Understanding &'static str in Plain Words

Before we talk about web responses, make sure you are comfortable with what &'static str is. In Rust, the type str represents a sequence of UTF‑8 characters. You almost never use str directly as a value because its size is not known at compile time. Instead you use a reference to it, written as &str. This reference points to the string data and also knows how many bytes it occupies.

The word 'static is a lifetime. Lifetimes tell the Rust compiler how long a reference is allowed to live. A 'static lifetime means the reference is valid for the entire duration of the program. In practice, string literals like "Hello" are stored in a special read‑only part of your compiled binary. They are never deallocated, so a reference to them is always safe. That is why the type of "Hello" is &'static str.

You can also create a &'static str by using a const or static item. A const is a compile‑time constant that gets inlined wherever it is used. A static is a fixed memory location that also lives for the whole program. Both can be used to produce a &'static str value.

Lifetime vs. ownership:

If you are new to Rust lifetimes, remember that 'static does not mean the value is stored in a special "static memory" that you must manage. It simply promises that the reference will never become invalid. String literals satisfy this automatically.

Why Axum Accepts &'static str as a Response

The IntoResponse trait is how Axum turns a handler's return value into an HTTP response. The trait has one method, into_response(), which turns the value into a response. Axum provides an implementation of IntoResponse for &'static str (and also for String, which behaves the same way for text you build at runtime). That means when you return a &'static str from a handler, Axum calls into_response() on it and sends the resulting response to the client.

What exactly does that implementation do? It creates a response with:

  • status code 200 OK
  • Content-Type header set to text/plain; charset=utf-8
  • the response body containing the string content

So the client receives the exact text you returned, and the browser (or curl) will display it as plain text. There is no HTML rendering, no JSON parsing - just raw text. This makes &'static str perfect for simple messages, health checks, or any endpoint that only needs to return a fixed string.

Zero allocation:

Returning a &'static str does not allocate memory on the heap. The string already exists in your binary, so Axum can simply copy a pointer and a length into the response. This is very efficient for frequently used static responses.

Your First Handler Returning &'static str

Let's build the smallest possible Axum application with a single route that returns a static string. Create a new project with cargo new static-str-example, add Axum and Tokio to Cargo.toml, and replace src/main.rs with the following:

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
    "Welcome to my Axum server!"
}

Let's break this down. The home function is an async handler with no parameters. Its return type is explicitly &'static str, and the body returns a string literal "Welcome to my Axum server!". Because the return type matches the value exactly, Axum knows it can call into_response() on it. When you run the program and open http://127.0.0.1:3000 in a browser or send a curl request, you will see:

Welcome to my Axum server!

The response status is 200 OK, and the Content-Type header is text/plain; charset=utf-8. You can verify this with curl -i:

$ curl -i http://127.0.0.1:3000
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 26
date: Mon, 31 Aug 2026 12:00:00 GMT
Welcome to my Axum server!

The exact date and server header may differ, but the important parts are the status, the content type, and the body.

Using Multiple Static String Routes

You often need several routes that each return a different static message. The pattern is exactly the same: define a separate handler for each route, and each handler returns a &'static str.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/about", get(about))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
    "Home page"
}
async fn about() -> &'static str {
    "About us"
}
async fn health() -> &'static str {
    "OK"
}

Now curl http://127.0.0.1:3000/ returns Home page, /about returns About us, and /health returns OK. Each handler is independent, and Axum routes the request to the correct one based on the path.

You can also write a single handler that returns different static strings depending on some condition, as long as the return type is always &'static str. This is often used for simple A/B testing or fallback messages.

async fn status_message(flag: bool) -> &'static str {
    if flag {
        "Feature is enabled"
    } else {
        "Feature is disabled"
    }
}

Because both "Feature is enabled" and "Feature is disabled" are string literals, the function compiles. You would then call this function inside an Axum handler (though the example above is not itself a handler because it takes a bool parameter; you would call it from a handler that gets the flag from somewhere, like query parameters - but that is an extractor topic, so we keep it simple).

Returning &'static str from a Function That Returns the Same Type

A handler can call another function that returns &'static str and then return that value directly. This is useful for organizing code - you might have a helper that chooses the right message.

fn get_greeting(language: &str) -> &'static str {
    match language {
        "en" => "Hello",
        "es" => "Hola",
        "fr" => "Bonjour",
        _ => "Hello",
    }
}
async fn greeting_handler() -> &'static str {
    let lang = "en"; // in real code this would come from an extractor
    get_greeting(lang)
}

Here get_greeting returns &'static str because every branch returns a string literal. The handler calls it and returns the result. This works because the lifetime 'static is compatible with the handler's return type.

Returning a local String reference will fail:

You cannot return a reference to a String that is created inside the handler. For example, this will not compile:

async fn broken_handler() -> &'static str {
    let s = String::from("Hello");
    &s // ERROR: `s` does not live long enough
}

The reference &s would become invalid as soon as the function returns, so it cannot have a 'static lifetime. For dynamic strings, you must return String instead, which owns its text and has no such lifetime requirement.

Using Constants and Statics for Shared Messages

If you have the same message used in multiple places, you can define it once as a const or a static item. Both can be referenced as &'static str because they live for the whole program.

const WELCOME_MESSAGE: &str = "Welcome to the service";
static ERROR_MESSAGE: &str = "Something went wrong";
async fn welcome() -> &'static str {
    WELCOME_MESSAGE
}
async fn error() -> &'static str {
    ERROR_MESSAGE
}

Both const and static work. The difference is subtle: a const is inlined at each use site (so the string may appear multiple times in the binary), while a static is a single memory location that is shared. For string literals the difference rarely matters; choose whichever feels clearer. const is generally preferred for fixed values, static for values that need a stable address (which strings usually don't).

What Happens Under the Hood When You Return &'static str

When a handler returns a &'static str, Axum converts it into an HTTP response object. This is done by the implementation of IntoResponse for &'static str, which delegates to the implementation for Cow<'static, str>. That implementation builds the body from the string and then inserts the Content-Type header itself. The content type is not set by Body and it is not guessed from the bytes: the trait implementation sets it explicitly.

If you are curious, the code in Axum looks conceptually like this:

impl IntoResponse for Cow<'static, str> {
    fn into_response(self) -> Response {
        let mut res = Body::from(self).into_response();
        res.headers_mut().insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("text/plain; charset=utf-8"),
        );
        res
    }
}

The response built from the body starts with the default status 200 OK, and the implementation above adds the text/plain; charset=utf-8 header. The Body type knows how to store static strings efficiently. Note that self here is a Cow<'static, str>, a standard-library wrapper that can hold either a borrowed string slice or an owned String; because the borrowed form is 'static, Axum can keep the reference for the lifetime of the response without worrying about dangling pointers.

Common Mistakes and How to Fix Them

Beginners often run into two problems when trying to return &'static str.

Trying to Return a Non‑static String Slice

A handler that returns &str without the 'static lifetime will not compile, because Axum only implements IntoResponse for &'static str (and for String, but that is a separate type). If you have a function that returns a &str that is tied to some input, you cannot directly return it as a response.

// This will not compile
async fn echo(input: &str) -> &str {
    input
}

Axum expects the return type to be something that implements IntoResponse. &str with an arbitrary lifetime does not, because the response body must be owned or be 'static. The fix is either to use String (if you can own the data) or to ensure the lifetime is 'static. For data that is not static, you should use String - the owned string type handles that case.

Forgetting That a String Literal Is &'static str

Some newcomers think they need to write &'static str explicitly in the return type for every handler that returns a literal. You can use impl IntoResponse as the return type instead, and the compiler will infer the concrete type from the body:

use axum::response::IntoResponse;
// Explicit
async fn explicit() -> &'static str {
    "Hello"
}
// The concrete type is still &'static str, but the signature hides it
async fn implicit() -> impl IntoResponse {
    "Hello"
}

You cannot omit the return type altogether: an async fn with no declared return type returns (), so writing async fn implicit() { "Hello" } fails to compile with a mismatched types error. The impl IntoResponse version is useful when you want to hide a long return type, but it still stands for exactly one concrete type. You cannot return a &str in one branch and a StatusCode in another; impl Trait never lets you return different types from different branches. For learning, explicit is fine.

Returning a String Literal with Escape Sequences

String literals can contain escape sequences like \n for a newline or \t for a tab. These are still &'static str. The response body will include the actual characters, so "Line1\nLine2" will appear as two lines in the client.

async fn multiline() -> &'static str {
    "First line\nSecond line\t(with tab)"
}

The Content-Length header will reflect the exact byte count after escapes are processed.

UTF‑8 only:

A &str must always be valid UTF‑8. If you need to send arbitrary bytes that are not valid UTF‑8, &'static str is not the right type. For binary data you would use Vec<u8> or bytes::Bytes instead.

Comparing &'static str and String in One Sentence

You already know &'static str works for fixed strings. If you need to build a response dynamically - for example, using format!() or reading from a file - you must use String, because it owns its data. String also implements IntoResponse and behaves similarly. But the focus of this page is the static case, and for any endpoint that always returns the same text, &'static str is the most direct choice.

A Complete Example with Several Routes and Constants

Here is a small but realistic Axum application that serves static text for different endpoints, using both literals and constants.

use axum::{routing::get, Router};
const APP_NAME: &str = "My Static Server";
const VERSION: &str = "1.0.0";
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/about", get(about))
        .route("/version", get(version))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("{} v{} running on http://127.0.0.1:3000", APP_NAME, VERSION);
    axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
    "Welcome! Try /about, /version, or /health."
}
async fn about() -> &'static str {
    "This server only returns static text responses."
}
async fn version() -> &'static str {
    VERSION
}
async fn health() -> &'static str {
    "OK"
}

Run this program and test each route. Every response will have status 200 OK and text/plain. This pattern is often used for microservices that expose simple health and info endpoints without needing a database or dynamic logic.

Summary

The &'static str response type in Axum lets you return string literals (or constants) directly from handlers. It is the simplest possible response that carries a text body. Because the string lives for the entire program, Axum can safely include it in the response without copying. This type sets the status to 200 OK and the content type to text/plain; charset=utf-8, making it perfect for fixed messages, health checks, and placeholder endpoints.

When you move beyond fixed strings and need to build responses dynamically, you will reach for String - a type that also implements IntoResponse and will be covered next. For now, remember that any handler returning a string literal is returning &'static str, and that is perfectly valid in Axum. Use it whenever your response text never changes.