No Content response

Learn how to return a 204 No Content response in Axum using the NoContent type or StatusCode, why 204 is useful, and common mistakes to avoid.

When a client sends a request to your server, the server always answers with an HTTP response. Most responses include a body - some text, HTML, JSON, or another payload. But sometimes the request succeeds and there is simply nothing to send back. A delete operation, a successful save, an acknowledgment of a received message - these often need only a confirmation, not data. HTTP has a dedicated status code for exactly that situation: 204 No Content. In Axum, you can express this cleanly with the built-in NoContent response type.

What 204 No Content Means

The 204 No Content status code tells the client that the server successfully processed the request but has no body to return. It is part of the HTTP specification and is widely used in REST APIs. Unlike a 200 OK response with an empty body, a 204 response explicitly signals that there is no content, and user agents (like browsers) must not navigate away from the current page or refresh content. That distinction matters in practice.

In Axum, any type that implements the IntoResponse trait can be returned from a handler. The NoContent struct is one such type. When you return NoContent from a handler, Axum automatically builds a response with the status code 204 and an empty body.

Returning NoContent from a Handler

The simplest way to send a 204 response is to make your handler return the NoContent type. It is a unit struct - meaning you write NoContent without any parentheses or fields.

Here is a complete, runnable Axum application with a single route that returns NoContent:

src/main.rs
use axum::{routing::delete, Router, response::NoContent};
#[tokio::main]
async fn main() {
    // Build the router with one route.
    let app = Router::new()
        .route("/delete", delete(delete_item));
    // Start the server on localhost:3000.
    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();
}
// Handler that returns NoContent.
async fn delete_item() -> NoContent {
    // In a real app, you would delete something from a database here.
    // For now, just return the 204 response.
    NoContent
}

When you run this program and send a DELETE request to http://127.0.0.1:3000/delete (using curl or another HTTP client), you will receive a response with status 204 No Content and an empty body. For example, using curl in a terminal:

curl -i -X DELETE http://127.0.0.1:3000/delete

The output will show something like:

HTTP/1.1 204 No Content
date: ...

Notice that there is no content-length header at all. Hyper omits it for 204 responses, because the HTTP standard forbids a body with 204 and there is nothing to measure. If you were to inspect this response in a browser's developer tools, you would see the status code 204 and no response data.

Why Use NoContent Instead of an Empty 200?

You might wonder: why not just return () (the unit type) or an empty String and get a 200 OK with an empty body? The difference is semantic and affects how clients behave.

A 200 OK response means "the request succeeded, and here is the result." Even if the result is empty, the client may still treat it as a normal content response - browsers might re-render the page, JavaScript code might expect data, or caching layers may store it. A 204 No Content tells the client: "the request succeeded, but do not change the current view or expect any data." For example, when you delete a resource via a REST API, a 204 response tells the frontend "the deletion succeeded, nothing else to show." The frontend can update its local state without trying to parse an empty response.

If you return () from a handler, Axum produces a 200 OK with an empty body. That is a valid response, but it does not carry the same "no content" meaning. The NoContent type exists specifically so you can be explicit.

Semantic clarity:

Using NoContent makes your API contract clearer. It tells other developers reading your code that this endpoint intentionally returns nothing, and it makes the client's job easier because it can rely on the 204 status to skip body parsing.

Alternative: Returning StatusCode::NO_CONTENT

Because StatusCode itself implements IntoResponse, you can also return StatusCode::NO_CONTENT directly from a handler. This produces the same 204 No Content response with an empty body. Axum knows that when you return a StatusCode, it should build a response with that status and no body.

Here is the same handler rewritten to use StatusCode::NO_CONTENT:

src/main.rs
use axum::{routing::delete, Router, http::StatusCode};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/delete", delete(delete_item));
    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 delete_item() -> StatusCode {
    StatusCode::NO_CONTENT
}

Both approaches are functionally identical for this simple case. So which one should you use? The NoContent type is more self-documenting - its name literally says "no content." StatusCode::NO_CONTENT is a bit more general; you might use it if you are returning a variety of status codes from different branches of a handler. If your handler always returns 204, NoContent is the clearer choice.

Either approach works:

If you run either version and curl the route with curl -i -X DELETE http://127.0.0.1:3000/delete, you will see HTTP/1.1 204 No Content. That confirms your setup is correct.

Adding Headers to a NoContent Response

Sometimes you want to send a 204 response but also include custom headers, for example a Location header after a successful delete, or a rate-limit header. Axum supports combining multiple response parts using tuples. The last element of a tuple must implement IntoResponse (the body/status part), and the earlier elements must implement IntoResponseParts (which includes types like HeaderMap and arrays of header pairs). A leading StatusCode is also allowed, because Axum provides dedicated tuple implementations with the status code first.

To add a custom header while still returning no content, you can return a tuple containing a HeaderMap (or an array of header pairs) followed by NoContent.

Here is an example that sets a custom header X-Deleted-Id before returning 204:

src/main.rs
use axum::{
    routing::delete,
    Router,
    response::NoContent,
    http::{HeaderMap, header},
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/delete/42", delete(delete_item));
    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 delete_item() -> (HeaderMap, NoContent) {
    let mut headers = HeaderMap::new();
    headers.insert(
        "X-Deleted-Id",
        "42".parse().unwrap(),
    );
    (headers, NoContent)
}

If you run this and send a DELETE request to /delete/42:

curl -i -X DELETE http://127.0.0.1:3000/delete/42

the response will contain:

HTTP/1.1 204 No Content
x-deleted-id: 42
date: ...

The header is included, but the body remains empty and the status stays 204. As with the plain NoContent response, there is no content-length header. This pattern is useful when you want to communicate additional metadata without attaching a response body.

Using NoContent in a Tuple with StatusCode

You can also include a StatusCode in the tuple, but the leading StatusCode always wins over the status set by the last element. Axum builds the response from the last element first, then applies the leading status code on top. So (StatusCode::CREATED, NoContent) produces a 201 Created response with an empty body, not a 204: the NoContent supplies the empty body, and the CREATED status overrides its 204.

This can lead to confusion. The general rule: when you return a tuple, the leading StatusCode determines the status and the last element determines the body. If you want a different status (like 201 Created) with no body, return StatusCode::CREATED directly, or use an empty body with a status in a tuple. For a true 204, stick with NoContent alone or as the final element without a conflicting leading status.

Do not mix status codes unexpectedly:

If you write (StatusCode::CREATED, NoContent), the resulting status will be 201, not 204, because the leading status code is applied last and overrides the 204 from NoContent. Always make NoContent the last element and do not include a conflicting StatusCode before it unless you intend for that status to win.

Common Mistakes and Misunderstandings

Assuming () Returns 204

The empty tuple () is the most basic return type for a handler. It represents "nothing" and causes Axum to send a 200 OK response with an empty body. Many beginners confuse () with "no content," but they are not the same. () is the absence of a value, not the explicit "no content" status. If you need a 204, you must use NoContent or StatusCode::NO_CONTENT.

Here is a quick comparison:

src/main.rs
use axum::{response::NoContent, http::StatusCode};
async fn handler_unit() {
    // Returns 200 OK with empty body
}
async fn handler_no_content() -> NoContent {
    // Returns 204 No Content with empty body
    NoContent
}
async fn handler_status() -> StatusCode {
    // Returns 204 No Content with empty body
    StatusCode::NO_CONTENT
}

Wrong status code in API clients:

If your frontend JavaScript expects a 204 response to know that a delete succeeded, but your handler returns (), it will receive a 200 instead. That can break client-side logic that relies on the status code to decide whether to refresh the page or show a message. Always return the explicit 204 type when that is your contract.

Including a Body with 204

The HTTP specification says a 204 response must not include a message body. In Axum, if you return a tuple like (StatusCode::NO_CONTENT, "some text"), the status will be 204 and the headers will still advertise the text as the body, but Hyper will not send any body bytes on the wire, so the client receives a body of zero bytes after headers that claim a length. Some clients may ignore the mismatch, while others may raise errors or behave unexpectedly. Always ensure that when you want a 204, you do not attach a body.

For example, the following is not recommended:

async fn bad_handler() -> (StatusCode, &'static str) {
    (StatusCode::NO_CONTENT, "should not be here")
}

If you absolutely need to send a body with a successful response, use a 200 status instead. Reserve 204 for responses that are truly empty.

Using 204 for Endpoints That Return Data

A 204 response means "no content." If your endpoint is supposed to return data - like a JSON representation of a resource - you should never return 204. A client expecting data will receive an empty body and likely fail to parse it. That is a common API design mistake. Use 204 only for operations where the client does not need any information back beyond success or failure.

Practical Uses of 204 in Real Applications

In production systems, 204 No Content appears frequently in RESTful APIs. Here are a few typical scenarios:

  • DELETE endpoints - After successfully deleting a resource, the server often returns 204. The client knows the resource is gone and can remove it from its local list.
  • PUT/PATCH updates that do not return the updated resource - If an update succeeds and the client does not need the new version, 204 is a clean response.
  • Webhook acknowledgments - When your server receives a webhook from another service and processes it, you might return 204 to indicate "received and processed, no further action needed."
  • Analytics or tracking endpoints - Ingesting events and returning 204 keeps the response lightweight.

Understanding when to use 204 is part of designing clear, predictable APIs. In Axum, the NoContent type makes that choice explicit in your code.

Summary

The NoContent response type in Axum is the idiomatic way to return an HTTP 204 status with an empty body. It signals to the client that the request succeeded but there is no content to show. You can also use StatusCode::NO_CONTENT for the same effect, but NoContent is more descriptive. You can combine it with headers using tuples, but remember that NoContent must be the last element, that a body attached to a 204 is dropped on the wire even though the headers advertise its length, and that a leading status code in a tuple wins over the 204.

The key takeaway: if you need an empty successful response that is not the default 200, reach for NoContent. When you later need to return actual data - like JSON - you will use other Axum response types such as Json or custom IntoResponse implementations. Those build on the same principles you have seen here.