Html wrapper

Learn how to return HTML responses in Axum using the Html wrapper, set the correct Content-Type header, and avoid common pitfalls such as XSS and incorrect content types.

When you build a web server, one of the most common things you want to send back to a browser is HTML. Axum provides a small helper type called Html that makes this straightforward and correct. In this guide, you will learn what Html is, why it exists, how it works under the hood, and how to use it in your own handlers. We will start from the absolute basics, assume no prior knowledge of HTML or HTTP headers, and build up to practical examples you can run and modify.

What Is the Html Wrapper?

Html is a thin wrapper around any type that can already be turned into an HTTP response. Its only job is to set the Content-Type header of that response to text/html; charset=utf-8. The wrapper itself does not change the body content, escape characters, or do any kind of validation. It simply tells the client (usually a web browser) that the bytes in the response body should be interpreted as HTML.

In Axum, Html lives in axum::response and looks like this:

pub struct Html<T>(pub T);

Because it is a tuple struct, you create an instance by writing Html(some_value). The inner value T must implement the IntoResponse trait, which means it already knows how to become a full HTTP response. The wrapper then modifies that response by inserting the correct Content-Type header.

You will most often use Html with a String or a &str because those are the types you will naturally use to hold chunks of HTML. However, any type that implements IntoResponse can be wrapped, even though some combinations make little sense. For example, wrapping a Json value inside Html would set the content type to HTML but leave the body as JSON text, which is almost certainly not what you want.

Wrapper Means No Magic:

The Html wrapper does not escape or sanitize the content you pass to it. It also does not validate that the content is valid HTML. It only changes one HTTP header.

Why the Content-Type Header Matters

Every HTTP response includes a set of headers. One of the most important for content delivery is Content-Type. This header tells the client what kind of data is in the body. For example:

  • text/plain means the body is plain text.
  • application/json means the body is JSON data.
  • text/html means the body is an HTML document.

When you return a plain &str or String from an Axum handler, Axum automatically sets Content-Type: text/plain. That is fine for plain text messages, but it is wrong for HTML. If you return a string like "<h1>Hello</h1>" without wrapping it in Html, the browser will see text/plain and will display the literal characters <h1>Hello</h1> instead of rendering a large heading. The browser does not try to guess whether the content is HTML; it trusts the header.

The Html wrapper exists to avoid this exact mistake. By wrapping your string in Html, you ensure the header becomes text/html; charset=utf-8. The browser then parses the body as HTML and renders it properly.

Forgetting the Wrapper Breaks Rendering:

Returning "<h1>Hello</h1>" directly from a handler will not render as HTML in a browser. The default content type for &str and String is text/plain, so the browser will show the tags as text.

Basic Usage of Html

Let us start with the simplest possible example: a handler that returns a static HTML string. Create a new Axum project, or add this to your existing main.rs:

// main.rs
use axum::{routing::get, response::Html, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello_html));
    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 hello_html() -> Html<&'static str> {
    Html("<h1>Hello, world!</h1>")
}

Here is what happens when you run this server and open http://127.0.0.1:3000 in a browser:

  • The handler hello_html returns Html("<h1>Hello, world!</h1>").
  • The inner value is a string literal, which has type &'static str. That type implements IntoResponse, so the wrapper can use it.
  • The wrapper turns that string into a response with status code 200 OK, body <h1>Hello, world!</h1>, and header Content-Type: text/html; charset=utf-8.
  • The browser receives the response, sees the content type, and renders the HTML as a large heading.

You can verify the headers with curl -i:

$ curl -i http://127.0.0.1:3000
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 22
date: Mon, 31 Aug 2026 12:00:00 GMT

<h1>Hello, world!</h1>

Correct Header Set:

When you see content-type: text/html; charset=utf-8 in the response headers, the Html wrapper has done its job correctly.

Building Dynamic HTML Responses

Static HTML is useful, but most real web pages are built dynamically. You might need to insert a user's name, the current date, or the result of a database query into the HTML. To do this, you first construct a String containing the complete HTML, and then wrap that String in Html.

Here is an example that reads a name from the URL path and inserts it into an HTML heading:

// main.rs
use axum::{extract::Path, routing::get, response::Html, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/greet/{name}", get(greet));
    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 greet(Path(name): Path<String>) -> Html<String> {
    let html = format!("<h1>Hello, {name}!</h1>");
    Html(html)
}

When you visit http://127.0.0.1:3000/greet/Alice, the server builds the string <h1>Hello, Alice!</h1> and returns it with the HTML content type. The browser renders a large heading saying "Hello, Alice!".

Notice that the return type is now Html<String> instead of Html<&'static str>. The format! macro produces an owned String, which also implements IntoResponse. This is the most common pattern for dynamic HTML: build a String, then wrap it.

You can build much larger HTML pages in the same way. Here is an example that returns a small but complete HTML document with a title, heading, and a paragraph:

async fn full_page() -> Html<String> {
    let html = r#"<!DOCTYPE html>
<html>
<head>
    <title>My Axum Page</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>This page was generated by an Axum server.</p>
</body>
</html>"#;
    Html(html.to_string())
}

The raw string literal r#"..."# lets you include quotes and newlines without escaping. You then call .to_string() to get a String instead of &'static str, but you could also return Html<&'static str> if you prefer. Either works.

Using Html with Other Response Parts

Sometimes you want to send a status code other than 200 OK along with your HTML. For example, a "Not Found" page should return status 404. You can combine Html with StatusCode by returning a tuple (StatusCode, Html<String>). This is part of Axum's built-in support for response tuples: Axum has a tuple form that applies the StatusCode as the status and uses the Html value as the body.

Here is an example handler that returns a custom 404 page:

use axum::http::StatusCode;
async fn not_found() -> (StatusCode, Html<String>) {
    let html = String::from("<h1>Page not found</h1><p>Sorry, that page does not exist.</p>");
    (StatusCode::NOT_FOUND, Html(html))
}

The response will have status 404 Not Found, body containing the HTML, and the Content-Type header set by the Html wrapper. This works because Axum has a tuple form that applies the StatusCode as the status and uses the Html value as the body.

You can add custom headers the same way, by putting a HeaderMap first in the tuple:

use axum::http::{header, HeaderMap};
async fn page_with_header() -> (HeaderMap, Html<String>) {
    let mut headers = HeaderMap::new();
    headers.insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
    let html = String::from("<h1>Fresh page</h1>");
    (headers, Html(html))
}

The HeaderMap comes first and the Html value comes last, so the response keeps the text/html; charset=utf-8 content type and also carries the Cache-Control: no-store header. A page like this is useful when the content changes on every visit and must never be served from a cache. For most HTML responses, a simple Html<String> or (StatusCode, Html<String>) is all you need.

Common Mistakes and How to Avoid Them

Working with Html is easy, but there are a few mistakes that beginners frequently make. Understanding these will save you time and frustration.

Forgetting to Wrap the String

This is the most common mistake. A handler that returns "<h1>Hello</h1>" without Html will produce a response with Content-Type: text/plain. The browser will show the literal text <h1>Hello</h1> instead of rendering it as a heading. Always wrap HTML strings in Html.

Plain String vs Html:

Returning a plain string containing HTML tags will not render as HTML because the default content type is text/plain. Use Html to set the correct header.

Injecting Untrusted User Input Without Escaping

The Html wrapper does not escape or sanitize the content you give it. If you insert user-supplied data directly into an HTML string, you open your application to cross-site scripting (XSS) attacks. An attacker could submit a name containing <script>alert('XSS')</script>, and that script would run in the browser of anyone who views the page.

Consider this dangerous handler:

async fn greet(Path(name): Path<String>) -> Html<String> {
    Html(format!("<h1>Hello, {name}!</h1>"))
}

If a user visits /greet/<script>alert('XSS')</script>, the resulting HTML becomes:

<h1>Hello, <script>alert('XSS')</script>!</h1>

The browser will execute the script. This is a serious security vulnerability.

To prevent XSS, you must escape any untrusted data before inserting it into HTML. Escaping means replacing characters like <, >, and & with their safe HTML entities (&lt;, &gt;, &amp;). Axum does not provide built-in escaping in the Html wrapper, so you need to handle it yourself or use a templating engine that does it for you.

A simple manual escape function might look like this:

fn escape_html(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}
async fn safe_greet(Path(name): Path<String>) -> Html<String> {
    let safe_name = escape_html(&name);
    Html(format!("<h1>Hello, {safe_name}!</h1>"))
}

Now the script tag becomes &lt;script&gt;, and the browser displays it as text instead of executing it.

XSS Risk Is Real:

Never insert untrusted user input directly into an Html response. Always escape the data first or use a template engine that escapes automatically.

Thinking Html Validates Your HTML

The Html wrapper does not check whether your HTML is well-formed. If you forget a closing tag, the browser will still try to render it, but the result may be broken. The wrapper only sets the content type; it does not parse or validate the body. You are responsible for producing correct HTML.

Using Html with the Wrong Inner Type

Because Html can wrap any type that implements IntoResponse, it is possible to create nonsensical combinations. For example:

use axum::Json;
use serde_json::json;
async fn bad_response() -> Html<Json<serde_json::Value>> {
    Html(Json(json!({"message": "Hello"})))
}

This returns a body containing JSON with a Content-Type: text/html. The browser will try to parse the JSON as HTML, which will produce garbage or display the raw JSON text. Make sure the inner value is actually an HTML string (or a type that produces HTML, such as a templating engine's markup type).

Alternatives to Html

The Html wrapper is the idiomatic way to return HTML in Axum. However, there are other approaches that you might encounter, and it is useful to know when each one is appropriate.

Setting the Header Manually

You could construct a Response manually and insert the Content-Type header yourself. This gives you full control but is more verbose. You would typically use Response::builder and HeaderMap. For simple cases Html is much shorter and clearer.

Using a Templating Engine

For larger projects, building HTML strings with format! becomes unwieldy. Many Axum users adopt a templating engine like Maud, Askama, or Tera. These engines often have their own types that already implement IntoResponse and set the correct content type. You can still wrap them in Html if needed, but often the engine's type already does that. This is beyond the scope of this page, but it is good to know that the Html wrapper is primarily for small, ad-hoc HTML snippets or when you are not using a full templating system.

Summary

The Html wrapper is a small but essential tool for returning HTML responses from Axum handlers. It works by taking any value that implements IntoResponse and adding the Content-Type: text/html; charset=utf-8 header. The body is left exactly as you provide it, so you must ensure the content is valid HTML and, more importantly, that any user input is escaped to prevent XSS.

In practice, you will use Html<String> for dynamic HTML built with format!, Html<&'static str> for static snippets, and (StatusCode, Html<String>) when you need a non-200 status code. Always remember to wrap your HTML strings; forgetting to do so results in plain text responses that display tags instead of rendering them.

The pattern to carry forward is the wrapper idea itself: a small type that takes a value you already know how to build and adjusts exactly one part of the response, in this case the content type. Every other response type works the same way, changing one piece while leaving the rest to the pieces around it.