Crate tower_http

source ·
Expand description

async fn(HttpRequest) -> Result<HttpResponse, Error>


tower-http is a library that provides HTTP-specific middleware and utilities built on top of tower.

All middleware uses the http and http-body crates as the HTTP abstractions. That means they’re compatible with any library or framework that also uses those crates, such as hyper, tonic, and warp.

Example server

This example shows how to apply middleware from tower-http to a Service and then run that service using hyper.

use tower_http::{
use tower::{ServiceBuilder, service_fn, make::Shared};
use http::{Request, Response, header::{HeaderName, CONTENT_TYPE, AUTHORIZATION}};
use hyper::{Body, Error, server::Server, service::make_service_fn};
use std::{sync::Arc, net::SocketAddr, convert::Infallible, iter::once};

// Our request handler. This is where we would implement the application logic
// for responding to HTTP requests...
async fn handler(request: Request<Body>) -> Result<Response<Body>, Error> {
    // ...

// Shared state across all request handlers --- in this case, a pool of database connections.
struct State {
    pool: DatabaseConnectionPool,

async fn main() {
    // Construct the shared state.
    let state = State {
        pool: DatabaseConnectionPool::new(),

    // Use tower's `ServiceBuilder` API to build a stack of tower middleware
    // wrapping our request handler.
    let service = ServiceBuilder::new()
        // Mark the `Authorization` request header as sensitive so it doesn't show in logs
        // High level logging of requests and responses
        // Share an `Arc<State>` with all requests
        // Compress responses
        // Propagate `X-Request-Id`s from requests to responses
        // If the response has a known size set the `Content-Length` header
        .layer(SetResponseHeaderLayer::overriding(CONTENT_TYPE, content_length_from_response))
        // Authorize requests using a token
        // Accept only application/json, application/* and */* in a request's ACCEPT header
        // Wrap a `Service` in our middleware stack

    // And run our service using `hyper`
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
        .expect("server error");

Keep in mind that while this example uses hyper, tower-http supports any HTTP client/server implementation that uses the http and http-body crates.

Example client

tower-http middleware can also be applied to HTTP clients:

use tower_http::{
use tower::{ServiceBuilder, Service, ServiceExt};
use hyper::Body;
use http::{Request, HeaderValue, header::USER_AGENT};

async fn main() {
    let mut client = ServiceBuilder::new()
        // Add tracing and consider server errors and client
        // errors as failures.
        // Set a `User-Agent` header on all requests.
            HeaderValue::from_static("tower-http demo")
        // Decompress response bodies
        // Wrap a `hyper::Client` in our middleware stack.
        // This is possible because `hyper::Client` implements
        // `tower::Service`.

    // Make a request
    let request = Request::builder()

    let response = client

Feature Flags

All middleware are disabled by default and can be enabled using cargo features.

For example, to enable the Trace middleware, add the “trace” feature flag in your Cargo.toml:

tower-http = { version = "0.1", features = ["trace"] }

You can use "full" to enable everything:

tower-http = { version = "0.1", features = ["full"] }

Getting Help

If you’re new to tower its guides might help. In the tower-http repo we also have a number of examples showing how to put everything together. You’re also welcome to ask in the #tower Discord channel or open an issue with your question.


  • add_extensionadd-extension
    Middleware that clones a value into each request’s extensions.
  • authauth
    Authorization related middleware.
  • catch_paniccatch-panic
    Convert panics into responses.
  • Tools for classifying responses as either success or failure.
  • compressioncompression-br or compression-deflate or compression-gzip or compression-zstd
    Middleware that compresses response bodies.
  • corscors
    Middleware which adds headers for CORS.
  • decompressiondecompression-br or decompression-deflate or decompression-gzip or decompression-zstd
    Middleware that decompresses request and response bodies.
  • follow_redirectfollow-redirect
    Middleware for following redirections.
  • limitlimit
    Middleware for limiting request bodies.
  • map_request_bodymap-request-body
    Apply a transformation to the request body.
  • map_response_bodymap-response-body
    Apply a transformation to the response body.
  • metricsmetrics
    Middlewares for adding metrics to services.
  • normalize_pathnormalize-path
    Middleware that normalizes paths.
  • propagate_headerpropagate-header
    Propagate a header from the request to the response.
  • request_idrequest-id
    Set and propagate request ids.
  • sensitive_headerssensitive-headers
    Middlewares that mark headers as sensitive.
  • Services that return responses without wrapping other Services.
  • set_headerset-header
    Middleware for setting headers on requests and responses.
  • set_statusset-status
    Middleware to override status codes.
  • timeouttimeout
    Middleware that applies a timeout to requests.
  • tracetrace
    Middleware that adds high level tracing to a Service.
  • validate_requestvalidate-request
    Middleware that validates requests.


  • CompressionLevelcompression-br or compression-deflate or compression-gzip or compression-zstd or decompression-br or decompression-deflate or decompression-gzip or decompression-zstd
    Level of compression data should be compressed with.
  • The latency unit used to report latencies by middleware.


Type Aliases

  • Alias for a type-erased error type.