Zero-argument handlers in Axum

Learn what zero-argument handlers are, why they are useful, how to write them with many examples, and common mistakes to avoid when building Axum applications.

A handler in Axum is an async function that processes an incoming HTTP request and produces a response. Some handlers need to look at the request - maybe they read a query parameter, a JSON body, or a path segment. Others do not need any information from the request at all. These are called zero‑argument handlers, because the function signature has no parameters between the parentheses.

You already saw handlers that take extractors like Path or State. Those are extremely useful, but sometimes a route needs the same response no matter what the client sends. A health check, a version endpoint, or a simple "Hello, World!" page are perfect examples. For these routes, a zero‑argument handler is the simplest, clearest way to write the code.

What a zero‑argument handler looks like

The absolute minimum handler you can write in Axum is an async fn that takes no arguments and returns a type that can become an HTTP response. Axum's Handler trait is automatically implemented for any async function with zero parameters - as long as the return type implements IntoResponse.

Here is the smallest possible complete Axum application with one zero‑argument handler:

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(hello));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
    "Hello, World!"
}

When you run this program and visit http://localhost:3000/ in a browser, you will see the text Hello, World!. The handler hello takes no arguments, so it is a zero‑argument handler. Its return type &'static str is a string slice that lives for the entire program, which Axum knows how to turn into an HTTP response with status 200 OK and the string as the body.

Everything is working:

If you see Hello, World! in your browser, your zero‑argument handler is functioning correctly. The server is receiving requests, running the handler, and sending the response back.

Why use zero‑argument handlers?

Zero‑argument handlers are the simplest possible building block for an Axum server. They express the idea "this route always returns the same thing (or something that does not depend on the request)". Using them has several benefits:

  • Clarity - The function signature tells you immediately that this route ignores the request. There is no need to scroll through unused extractor parameters.
  • Less boilerplate - No State, Path, or Query to import or destructure. You just write the body.
  • Good for fixed endpoints - Health checks (/health), version information (/version), home pages, and static messages are natural fits.
  • Easy to test - Since there are no inputs, you can call the handler directly in a unit test without building a fake request.

Zero arguments ≠ zero information:

A zero‑argument handler cannot receive request data through extractor arguments. However, it can still access data that is available globally or captured from the surrounding scope, as you will see later in this page.

Returning different types from zero‑argument handlers

Axum is very flexible about what a handler can return. Any type that implements IntoResponse works. For a zero‑argument handler, this flexibility is especially handy because you can change the response type without adding any parameters.

Returning nothing: ()

Sometimes you just need to confirm that the server is alive. A handler can return the unit type (), which Axum converts into an empty 200 OK response.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/ping", get(ping));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn ping() {
    // nothing to do, just return an empty 200 response
}

When you request /ping, the server responds with status code 200 and an empty body. This is a common pattern for simple health checks where the only important signal is "the service is up".

Returning a String

A String is also an IntoResponse. Unlike &'static str, a String can be built at runtime, which gives you more control over the response body.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(greeting));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn greeting() -> String {
    let name = "friend";
    format!("Hello, {}!", name)
}

Even though the handler does not take any arguments, it can still compute the response body using local variables, function calls, or even data from a database (as long as that data is accessed through some global connection or captured closure). The key point is that the handler itself has zero extractor arguments.

Returning a custom type that implements IntoResponse

For more complex responses, you can create your own type and implement IntoResponse for it. This lets you bundle status codes, headers, and bodies into one reusable object. A zero‑argument handler can return such a type just as easily.

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(api_info));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
struct ApiInfo {
    version: &'static str,
    status: &'static str,
}
impl IntoResponse for ApiInfo {
    fn into_response(self) -> Response {
        (
            StatusCode::OK,
            format!("version: {}, status: {}", self.version, self.status),
        )
            .into_response()
    }
}
async fn api_info() -> ApiInfo {
    ApiInfo {
        version: "1.0.0",
        status: "operational",
    }
}

This example returns an ApiInfo struct. Because ApiInfo implements IntoResponse, Axum can convert it into a full HTTP response. The handler has no parameters, but the response depends on data that is hard‑coded inside the handler body. In a real application, you might read that data from a global variable or a shared resource, which we will cover shortly.

Accessing shared state without extractor arguments

A zero‑argument handler cannot use the State extractor because that requires adding a function parameter. However, you can still access shared application state by capturing it in a closure. A closure is an anonymous function that can capture variables from its surrounding environment. Axum accepts closures as handlers, and a closure with no parameters is effectively a zero‑argument handler.

Imagine you have some configuration that should be available to a health‑check endpoint. You can move that configuration into the closure when you set up the route:

use axum::{routing::get, Router};
use std::sync::Arc;
#[derive(Debug)]
struct AppConfig {
    app_name: String,
}
#[tokio::main]
async fn main() {
    let config = Arc::new(AppConfig {
        app_name: "My Axum App".to_string(),
    });
    let app = Router::new().route(
        "/health",
        get({
            let config = Arc::clone(&config);
            move || async move {
                format!("{} is healthy", config.app_name)
            }
        }),
    );
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here the closure move || async move { ... } takes no arguments, so it is a zero‑argument handler from Axum's perspective. Inside, it has access to the captured config variable. This pattern is useful when you want to keep the handler function free of extractor arguments but still need to read some state that was set up before the router was built.

Closures must be cloneable and static:

When you use a closure as a handler, Axum requires the closure to implement Clone + Send + Sync and be 'static. The closure in the example above satisfies these requirements because it only captures an Arc<AppConfig>, which is cloneable and sendable. If you capture a non‑cloneable or non‑sendable type, you will get a compile error.

Multiple routes sharing one zero‑argument handler

You can use the same zero‑argument handler for several different routes. Because the handler does not read any request data, it will behave identically no matter which path triggers it.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/index", get(home))
        .route("/start", get(home));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
    "Welcome to the site"
}

Visiting /, /index, or /start all produce the same response. This is a quick way to serve a single landing page under multiple URLs. In practice you might prefer to use a redirect instead, but this shows that zero‑argument handlers are reusable across routes without any modification.

Returning results and errors

So far all the examples always succeed. A real handler often needs to signal an error. Since a zero‑argument handler can return a Result, you can still handle errors internally without needing any extractors. The error type must implement IntoResponse, and Axum will convert Ok and Err into responses automatically.

Here is a handler that checks a global flag and returns an error if the service is not ready:

use axum::{
    http::StatusCode,
    routing::get,
    Router,
};
use std::sync::atomic::{AtomicBool, Ordering};
static READY: AtomicBool = AtomicBool::new(true);
#[tokio::main]
async fn main() {
    let app = Router::new().route("/ready", get(readiness));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn readiness() -> Result<&'static str, StatusCode> {
    if READY.load(Ordering::Relaxed) {
        Ok("ready")
    } else {
        Err(StatusCode::SERVICE_UNAVAILABLE)
    }
}

When the global READY flag is true, the handler returns Ok("ready") and Axum sends a 200 OK with body ready. When the flag is false, it returns Err(StatusCode::SERVICE_UNAVAILABLE) and Axum sends a 503 Service Unavailable response with an empty body. The handler still has no arguments; all the state it needs is global.

Do not use extractors inside a zero‑argument handler:

It is tempting to think you can add a State or Path parameter "sometimes" and still call it zero‑argument. But once you add any parameter, it is no longer a zero‑argument handler - it is a handler with extractor arguments. That is perfectly fine in many cases, but it is a different topic. For this page, keep the function signature completely empty if you want the benefits of zero‑argument handlers.

Combining zero‑argument handlers with other handlers in the same router

A single Axum Router can mix zero‑argument handlers with handlers that take extractors. The router does not care about the number of arguments; each route's handler is independent. This is useful when you have a small set of routes that need no request data and others that do.

use axum::{
    extract::Path,
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
    "Home page"
}
async fn get_user(Path(id): Path<u32>) -> String {
    format!("User ID: {}", id)
}

The home handler is zero‑argument, while get_user extracts a path segment. Axum handles each route according to its own handler's signature. This is the normal way to build a real application: simple routes stay simple, and complex routes get the extractors they need.

Common mistakes with zero‑argument handlers

Because zero‑argument handlers are so basic, mistakes tend to be small but can cause confusing compile errors. Here are the ones beginners encounter most often.

Forgetting async

A handler must be an async fn. If you forget the async keyword, the function returns a normal value, not a future, and Axum cannot treat it as a handler. On its own, a plain fn is valid Rust - it only fails when you register it as a handler:

use axum::{routing::get, Router};
fn hello() -> &'static str {
    "Hello"
}
#[tokio::main]
async fn main() {
    // This line will NOT compile: hello is not async, so it does not implement Handler
    let app = Router::new().route("/", get(hello));
    // ...
}

The error message you get might mention that the function does not implement the Handler trait. That is Axum's way of saying "I expected an async function, but I got a sync one."

Returning a type that does not implement IntoResponse

Every handler must return something Axum can turn into a response. If you return a type like u32 or a plain struct without implementing IntoResponse, the compiler will reject it - again, only when the function is registered as a handler:

use axum::{routing::get, Router};
// This will NOT compile when registered: u32 does not implement IntoResponse
async fn number() -> u32 {
    42
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/number", get(number));
    // ...
}

You must wrap the value in a type that does implement IntoResponse. For example, (StatusCode::OK, "42") works, or you can implement IntoResponse for your own struct.

Trying to access request data without an extractor

A zero‑argument handler cannot look at the incoming request directly. If you need to read a header, query parameter, or body, you must add an extractor argument. Trying to do so inside a zero‑argument handler will not work because there is no handle to the request.

// This is impossible with zero arguments:
async fn handler() {
    // You cannot access the request here.
    // To get request data, add an extractor parameter like `headers: HeaderMap`.
}

This is not a bug - it is by design. When you need request data, you move to a handler with one or more extractor arguments. That is the next step after mastering zero‑argument handlers.

When to use a zero‑argument handler

Use a zero‑argument handler when:

  • The response does not depend on the request method, path, query, headers, or body.
  • You need a health check, liveness probe, or version endpoint.
  • You want to return a fixed message or static HTML.
  • You are prototyping and want the absolute simplest route.
  • You have a resource that is global or captured via closure, and you do not need request context.

When any of these conditions change - for example, you need to return a different response depending on the user ID - switch to a handler with extractor arguments. That is a natural progression and keeps your code clear about what each route actually depends on.

Summary

Zero‑argument handlers are the starting point of any Axum application. They are simple async functions with no parameters that return a response‑convertible type. Their simplicity makes them perfect for static endpoints, health checks, and situations where the request details are irrelevant. You can return many different types, handle errors with Result, and even access shared state through closure captures - all while keeping the handler signature empty.

The most important insight from this page is that a zero‑argument handler communicates intent: this route does not care about the incoming request. When you see an empty parameter list, you immediately know that the response is independent of the client's data. As soon as that stops being true, you add an extractor and move to a handler that takes arguments - which is exactly the next step in building more dynamic Axum applications.