Hyper compatibility
Understand how Axum works with the Hyper HTTP library, why the two are tightly connected, and how you can use Hyper types and services inside an Axum application.
Hyper compatibility
Most web frameworks try to hide the low-level details of HTTP from you. That is often a good thing. But it can also create a wall: the moment you need something the framework does not expose, you are stuck. Axum takes a different path. It is built directly on a library called Hyper, and it keeps that connection visible and usable. This page explains what that means, why it matters, and how you can work with Hyper types inside an Axum application without fighting the framework.
What Hyper is in plain terms
Hyper is a Rust library that speaks HTTP. It understands incoming requests, outgoing responses, headers, status codes, body streams, and the other raw pieces that make up the web. Axum does not reimplement any of that. Instead, Axum sits on top of Hyper and adds the parts that make application code pleasant to write: routing, extractors, typed responses, and state sharing.
A useful mental model is a restaurant. Hyper is the kitchen infrastructure: stoves, fridges, raw ingredients, plumbing. Axum is the menu and the service flow that lets diners order without thinking about gas valves and drain pipes. You normally interact with the menu, but the kitchen is right there, and a chef can walk in and use the same equipment at any time.
This relationship is not accidental. Axum and Hyper are maintained by overlapping groups of people within the Tokio project. They are designed to fit together from the start, not as an afterthought.
Why Hyper compatibility is useful
Axum lets you stay at a high level for most of your code. A handler that returns a string or a JSON value never needs to know that Hyper exists. But real applications sometimes need to step closer to the protocol. A few situations where that happens:
- You want to read or set very specific HTTP headers that Axum does not wrap in a convenient extractor.
- You are integrating with an existing codebase that already uses Hyper types.
- You want to run an Axum router inside a custom Hyper server setup.
- You need to handle raw HTTP semantics that are rare or unusual.
In all these cases, the fact that Axum and Hyper share the same underlying http crate types - method, path, headers, status code - means you can move between the two layers without converting data back and forth for those types. Bodies are the exception: Axum has its own body type, and Hyper's server-side body is a different type.
The connection between Axum and Hyper
At the center of the connection is a type called Body. In plain Rust terms, a body is the stream of bytes that follows the headers in an HTTP message. axum::body::Body is Axum's own body type - "the body type used in axum requests and responses" - not a Hyper type. Hyper's server-side body is a different type, hyper::body::Incoming, and Axum converts between the two internally when a request arrives and a response leaves.
This also means Axum inherits Hyper's behavior around reading bodies, streaming bodies, connection handling, and HTTP versions. When Axum documentation says it works over HTTP/1.1 or HTTP/2, that capability comes from Hyper underneath. Axum focuses on routing and application logic; Hyper focuses on the wire.
A minimal Axum application to see the surface
Before doing anything Hyper-specific, start with the smallest Axum server possible. This gives a baseline that every later example modifies.
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Run this with cargo run, then open http://localhost:3000 in a browser. You should see the text Hello, World!. Underneath, the axum::serve function created a Hyper server, passed the Axum router to it, and started accepting TCP connections. You did not need to name Hyper anywhere, but it was doing the heavy lifting.
Axum's own Body type
The most visible piece of Hyper inside Axum is axum::body::Body. In older versions of Hyper, every request and response carried a concrete body type. Newer Hyper versions make the body type generic, which lets different parts of the stack choose different body representations. Axum defines its own Body type for its requests and responses; it is not a thin alias over a Hyper body - Hyper's server-side body is hyper::body::Incoming, and Axum converts between the two internally.
You rarely need to name Body directly. Handlers return strings, JSON values, status codes, and tuples, and Axum converts those into a response with a Hyper-compatible body automatically. But knowing that Body exists helps when reading compiler errors. If an error mentions Body, the compiler is usually telling you that some function returned a type that could not be converted into a valid HTTP response.
Using Hyper types in a handler
A common first step into Hyper compatibility is using the axum::http module. This module re-exports the shared http crate's types - request, response, header names, header values, method, status code, and version - the same crate Hyper builds on. Axum and Hyper do not re-export each other's types; they both build on http. You can import these in any handler.
Here is a handler that reads a custom header and returns its value:
use axum::{
http::{HeaderMap, StatusCode},
response::IntoResponse,
routing::get,
Router,
};
async fn show_custom_header(headers: HeaderMap) -> impl IntoResponse {
match headers.get("x-demo-header") {
Some(value) => value.to_str().unwrap_or("invalid").to_string(),
None => "no x-demo-header found".to_string(),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(show_custom_header));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The HeaderMap type here comes from the shared http crate (re-exported as axum::http::HeaderMap), not from Hyper. Axum can extract it directly from the request because Axum's request type is the http crate's request type carrying Axum's Body. Test it with curl:
curl -H "x-demo-header: hello" http://localhost:3000
You should see hello. Without the header, you should see no x-demo-header found.
HeaderMap is useful when you need access to many headers at once. For a single header, the TypedHeader extractor does the job - but it lives in axum-extra, not in axum itself (use axum_extra::{headers::UserAgent, TypedHeader}). The point here is that the http module gives you direct access to the same types Hyper uses, without a conversion step.
Reading the raw request
Sometimes a handler needs the full incoming request object, not just extracted pieces. Axum provides the Request type through axum::extract::Request. This is an http::Request carrying Axum's Body - a type from the shared http crate, not a Hyper type. You can inspect the method, path, headers, and body from it.
use axum::{
extract::Request,
http::Method,
routing::get,
Router,
};
async fn inspect_request(request: Request) -> String {
let method = request.method().clone();
let path = request.uri().path().to_string();
let header_count = request.headers().len();
format!("method={method}, path={path}, headers={header_count}")
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(inspect_request));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Send a request with curl:
curl -H "x-one: 1" -H "x-two: 2" http://localhost:3000/some/path
The response should be method=GET, path=/some/path, headers=5: the two custom headers you sent, plus the three curl sends by default - Host, User-Agent, and Accept. This handler uses the raw request, as Axum received it, to gather information that Axum's normal extractors might not expose in one place.
Returning a hand-built response
Handlers do not have to return Axum's convenient response types. You can also return a full response built by hand with the http crate's builder. This is occasionally useful when you need exact control over every header and status code.
use axum::{
body::Body,
http::{Response, StatusCode},
routing::get,
Router,
};
async fn custom_response() -> Response<Body> {
Response::builder()
.status(StatusCode::ACCEPTED)
.header("x-powered-by", "example-app")
.body(Body::from("custom body text"))
.unwrap()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(custom_response));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The return type Response<Body> uses the shared http crate's response type with Axum's body type. When a client sends a request, it receives the status 202 Accepted and the body custom body text. The Response::builder() API is part of the http crate, which both Hyper and Axum build on and which Axum re-exports as axum::http.
Body type in the return position:
Response<Body> is the most explicit return type an Axum handler can use. It gives you total control but also total responsibility. For most endpoints, returning a simpler type such as (StatusCode, &'static str) is clearer and less error-prone. Reach for Response<Body> only when you have a specific reason to set headers or status codes manually.
Using an Axum router inside a Hyper server
The previous examples all used axum::serve, which hides the Hyper server behind a friendly function. But because Axum builds on Hyper, you can also take an Axum router and hand it to a Hyper server yourself. This is useful when you already have a Hyper server with custom configuration and want Axum to handle the routing.
The key idea is that an Axum Router implements the tower::Service trait. Hyper knows how to run any type that implements that trait for requests and responses - but with one wrinkle: Hyper has its own Service trait, separate from Tower's. A Router cannot be passed to serve_connection directly. Axum's own serve-with-hyper example bridges the two with hyper::service::service_fn, which calls the router through Tower's Service::call. Here is that pattern, replacing axum::serve with a direct Hyper setup:
use axum::{extract::Request, routing::get, Router};
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
use tower::Service;
async fn hello() -> &'static str {
"Hello from Axum inside Hyper"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
loop {
let (stream, _remote_addr) = listener.accept().await.unwrap();
let io = TokioIo::new(stream);
let tower_service = app.clone();
tokio::spawn(async move {
// Hyper has its own `Service` trait and doesn't use Tower's.
// `service_fn` adapts the Tower service (the router) to it.
let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| {
tower_service.clone().call(request)
});
if let Err(err) = http1::Builder::new()
.serve_connection(io, hyper_service)
.await
{
eprintln!("connection error: {err}");
}
});
}
}
To compile this, add Hyper, the Tokio adapter utility, and Tower to Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["tokio"] }
tower = "0.5"
This example accepts TCP connections in a loop, wraps each stream in TokioIo so Hyper can use it with Tokio's async runtime, and then calls serve_connection with the adapted service. Hyper is running the HTTP protocol; Axum is matching routes and calling handlers.
The important observation is that the only adapter needed is between the two Service traits. The router accepts the Hyper request directly (its Service implementation is generic over the body type), converts the body to Axum's Body internally, and hands back a response Hyper can write. This is the practical meaning of Hyper compatibility: the boundaries are porous by design.
The Service trait as the glue
Axum's side of the boundary speaks tower::Service: a service is something that takes a request and eventually produces a response, and an Axum router is one. Hyper's side speaks its own Service trait, which looks similar but is a different trait - that is why the example above needed the service_fn adapter. What the two sides genuinely share is the http crate: method, URI, headers, status code, and the request and response shapes.
This is why Axum does not need its own middleware system. It uses tower::Service, which was originally designed for generic async services. That shared vocabulary means a compression layer, timeout layer, or tracing layer can be applied to an Axum router without knowing it is an Axum router. It just sees a service.
Everything connected:
If you have built an Axum router and can pass it to axum::serve, you have already seen Hyper compatibility working. The router is a tower::Service over the shared http crate's request and response types, carrying Axum's Body, and the service_fn adapter bridges Hyper's Service trait to Tower's. There is no hidden serialization step.
Accessing Hyper's lower-level connection details
Axum keeps connection details out of the handler by default. Your handler receives an HTTP request, not a socket or a connection object. This keeps handlers easy to test and reason about. But in some advanced situations you may need information about the connection itself. Hyper exposes this through its connection types, and the data can be attached to the request as a request extension.
This approach is more advanced than most beginners need, but knowing it exists helps when reading library code. Extensions are a key-value store attached to a request. Axum's Extension extractor can read values from that store. A custom Hyper service could insert the peer's IP address or TLS certificate into the request, and a later Axum handler could extract it.
Because the extension types flow through unchanged, you can write a custom Hyper-level service that enriches requests and still use ordinary Axum handlers downstream. This is a strong real-world sign of Hyper compatibility: the two layers can be combined instead of being forced to replace each other.
What beginners usually misunderstand
A frequent assumption is that Axum is an alternative to Hyper, like two competing frameworks. It is not. Axum depends on Hyper and runs on top of it. You never choose between "using Axum" and "using Hyper." You choose how much of Hyper you want to see. Most applications stay entirely at the Axum level and never name Hyper in their code. A few applications reach into Hyper for a specific feature.
Another misconception is that using Hyper types in an Axum handler is unsafe or unsupported. The opposite is true. The axum::http module - Axum's re-export of the shared http crate - is part of Axum's public API. Code written against it is following a supported path, not bypassing the framework.
Some beginners also expect Axum to work without an async runtime. That is not possible, because Hyper itself is async and depends on Tokio for its runtime. Axum's compatibility with Hyper also means it inherits that requirement. If you are using Axum, you are using Tokio and Hyper underneath, even when you do not mention them.
Body types can surprise you:
When you work with raw requests and responses, the compiler may mention multiple body types. Axum's Body is the one to use in handler signatures and response builders. Hyper's own body::Incoming appears on server requests. Axum converts between these internally. If a function expects Request<Body> and you pass something else, check whether you mixed Axum's request extractor with Hyper's raw connection-level request.
Comparing the two styles of building a server
You now have two ways to start a server: axum::serve and a direct Hyper loop. The table below summarizes when each is appropriate.
| Approach | How you start it | When to use it |
|---|---|---|
axum::serve | axum::serve(listener, app).await | Everyday Axum applications; no custom connection setup needed |
| Direct Hyper server | Manually accept connections and call hyper::server::conn | Existing Hyper servers, custom connection handling, or special protocol tweaks |
axum::serve is a convenience wrapper around the direct approach. It handles the connection loop for you, and it is intentionally simple - it does not support configuration beyond that. Graceful shutdown is not a default: it is opt-in via Serve::with_graceful_shutdown, which takes a future that completes when the server should stop:
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
}
The direct approach gives more control but requires more code and more knowledge of Hyper's API. Most Axum users never need the direct approach, but it is available because of the compatibility described on this page.
Handling a Hyper-focused use case with a shared body
A concrete scenario where Hyper compatibility becomes visible is when a library accepts or returns Hyper types. Imagine a helper function that already exists in your codebase and returns hyper::Response<hyper::body::Incoming>. You cannot return that directly from an Axum handler because the body type is different. You have to collect the incoming body into bytes first, then wrap those bytes in Axum's Body:
use axum::{body::Body, http::Response};
use http_body_util::BodyExt;
use hyper::body::Incoming;
async fn convert_hyper_response(resp: Response<Incoming>) -> Response<Body> {
let (parts, incoming) = resp.into_parts();
let bytes = incoming.collect().await.unwrap().to_bytes();
Response::from_parts(parts, Body::from(bytes))
}
The status code and headers survive untouched - only the body changes shape. This needs http-body-util = "0.1" in Cargo.toml for the collect() helper.
Often no conversion is needed at all, because the helper builds its response with the shared http types and Axum's Body from the start. Here is that case: the helper uses Hyper's builder style, but the body is already Axum's Body, so the response can be returned unchanged.
use axum::{
body::Body,
http::{Response, StatusCode},
routing::get,
Router,
};
fn existing_hyper_response() -> Response<Body> {
Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain")
.body(Body::from("from a Hyper-style helper"))
.unwrap()
}
async fn handler() -> Response<Body> {
existing_hyper_response()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The helper function uses the same http types that Axum re-exports. Because the body is already Axum's Body, the response can be returned unchanged. This pattern makes it easy to keep a library of response-building functions that works across different parts of a Rust codebase, even if some parts use Axum and others use Hyper more directly.
When Hyper compatibility is not the right focus
Hyper compatibility does not mean you should always work at the Hyper level. Most handlers should stay simple: return a string, a status code, a JSON value, or a tuple. Those simple returns are easier to read, easier to test, and less likely to hide mistakes. The reason to reach for Hyper types is when the application genuinely needs something outside Axum's friendly surface.
If you find yourself using raw HeaderMap and Response<Body> in every handler, step back and ask whether that extra control is really necessary. Often a standard Axum extractor or response type does the same job with less code.
Summary
Axum's Hyper compatibility is not a feature you enable. It is a structural fact: Axum and Hyper both build on the shared http crate's types, Axum runs inside Hyper's server, and Axum exposes those shared types through its own public modules. This means you can start with an ordinary Axum application and later reach into Hyper when a specific need appears, without rewriting the application around a different type system.
The most important takeaway is that the boundaries between Axum, Hyper, and the Tower service layer are intentionally thin. A router is a service. A request is an http::Request carrying Axum's Body (Hyper hands the server side an http::Request carrying hyper::body::Incoming, and Axum converts it). A response is an http::Response carrying Axum's Body. This shared vocabulary is what lets one middleware ecosystem serve HTTP servers, RPC servers, and Axum routers at the same time. Once you are comfortable with the idea that Axum is a layer above Hyper rather than a replacement for it, the rest of the framework's design becomes much easier to understand.