Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Extractors and Responses

Headers, Cookies and Uploads in Axum

Read request headers with HeaderMap and TypedHeader, manage cookies with CookieJar, set response headers, and receive multipart file uploads in Axum with limits.

HTTP metadata lives in headers: who is calling (user-agent), what they accept, which credentials they present (authorization, cookie), what you send back (content-type, set-cookie, cache-control). This lesson shows how to read and write headers in Axum, how cookies fit in, and how to accept file uploads with multipart/form-data.

Some of the tools here live in the companion crate axum-extra (typed headers, cookie jars, multipart helpers, the Query that supports repeated keys). Add it with the features you need, for example cargo add axum-extra --features typed-header,cookie.

Reading headers

HeaderMap: everything

Rust
use axum::http::HeaderMap;

async fn show(headers: HeaderMap) -> String {
    let agent = headers
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("unknown");
    format!("user-agent: {agent}")
}

HeaderMap implements FromRequestParts, so it can be used anywhere in the argument list. Header names are case-insensitive (User-Agent and user-agent are the same key). Values are bytes, not necessarily UTF-8, which is why to_str() returns a Result. A header may appear more than once: get returns the first value, get_all an iterator.

Use HeaderMap for quick inspection. For a header your handler really depends on, prefer a typed extractor.

TypedHeader: parsed, checked and named

Rust
use axum_extra::{
    headers::{authorization::Bearer, Authorization, UserAgent},
    TypedHeader,
};

async fn me(
    TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
    TypedHeader(agent): TypedHeader<UserAgent>,
) -> String {
    format!("token {} from {}", auth.token(), agent.as_str())
}

If the header is missing or malformed, the extractor rejects the request with 400 Bad Request (a clear message, handler not run). Wrap it in Option<TypedHeader<...>> when the header is optional. The headers crate defines ContentType, Authorization<Basic>, Authorization<Bearer>, Cookie, IfNoneMatch, CacheControl and many more.

Single-header shortcut

For one custom header, writing a tiny extractor (see the previous lesson) is often cleaner than HeaderMap: it names the concept (ApiKey, TenantId) and centralises parsing.

Setting response headers

Any tuple that starts with a HeaderMap, an array of (name, value) pairs, or [(HeaderName, HeaderValue)] implements IntoResponse when followed by the body:

Rust
use axum::{http::{header, StatusCode}, response::IntoResponse};

async fn download() -> impl IntoResponse {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "text/csv"),
            (header::CONTENT_DISPOSITION, "attachment; filename=\"users.csv\""),
            (header::CACHE_CONTROL, "no-store"),
        ],
        "id,name\n1,Ana\n2,Ben\n",
    )
}

Use the constants in axum::http::header (CONTENT_TYPE, LOCATION, SET_COOKIE...) so typos become compile errors. The next lesson looks at responses in full.

Cookies

A cookie is just two headers: the server sets it with Set-Cookie and the browser returns it in Cookie. Parsing and escaping them by hand is error-prone, so use axum_extra::extract::CookieJar:

Rust
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};

async fn login(jar: CookieJar) -> (CookieJar, &'static str) {
    let cookie = Cookie::build(("session", "abc123"))
        .http_only(true)
        .secure(true)
        .same_site(SameSite::Lax)
        .path("/")
        .max_age(time::Duration::hours(8))
        .build();
    (jar.add(cookie), "logged in")
}

async fn profile(jar: CookieJar) -> String {
    match jar.get("session") {
        Some(c) => format!("session {}", c.value()),
        None => "not logged in".to_string(),
    }
}

async fn logout(jar: CookieJar) -> CookieJar {
    jar.remove(Cookie::from("session"))
}

Returning the jar from a handler is what writes the Set-Cookie headers: a jar you only read changes nothing. Remember the three flags that matter for session cookies:

Flag Effect
HttpOnly JavaScript cannot read the cookie, which limits damage from XSS
Secure only sent over HTTPS
SameSite=Lax or Strict not sent on most cross-site requests, which blunts CSRF

PrivateCookieJar encrypts and authenticates the values and SignedCookieJar signs them, both with a Key stored in your state. Never put secrets in a plain cookie.

Multipart uploads

Browsers send files as multipart/form-data, a body made of parts separated by a boundary string. Axum's Multipart extractor (feature multipart) streams the parts to you:

Rust
use axum::extract::Multipart;

async fn upload(mut multipart: Multipart) -> Result<String, (StatusCode, String)> {
    let mut saved = Vec::new();
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?
    {
        let name = field.name().unwrap_or("").to_string();
        let file_name = field.file_name().map(str::to_owned);
        let bytes = field
            .bytes()
            .await
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
        saved.push(format!("{name}: {:?} ({} bytes)", file_name, bytes.len()));
    }
    Ok(saved.join("\n"))
}

Upload checklist:

  1. Raise the body limit for this route only (DefaultBodyLimit::max(...)), as in JSON and form bodies. The default 2 MB stops most photos.
  2. Never trust file_name(). It is client-controlled and may contain ../. Generate your own name (a UUID) and keep the original only as metadata.
  3. Check the real content, not only content_type(). Check size and, for images, decode a header.
  4. Stream big files to disk with field.chunk().await instead of field.bytes(), so memory stays small.

Stand-in: headers and cookies

The first model implements a case-insensitive header map, parsing of the Cookie request header and building of a Set-Cookie value, so you can see exactly what bytes the real libraries manage for you.

Rust Stand-in: header map, Cookie parsing and Set-Cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Stand-in: multipart parsing

A multipart body is plain text (or bytes) with boundaries. This parser handles the simplest case, text parts with headers, so you can see what next_field() hands you: a field name, an optional file name and the data.

Rust Stand-in: reading a multipart body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The client sent the file name ../../etc/passwd. A server that joins it to an upload directory would write outside that directory. Generating your own file name avoids the whole class of bug.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about header names in HeaderMap is true?

    HTTP header names are case-insensitive, and HeaderMap normalises them.
  2. 2. You call jar.add(cookie) inside a handler but return only a String. What happens?

    The jar writes Set-Cookie through its IntoResponse implementation, so it has to be part of the returned value.
  3. 3. Which cookie flag stops JavaScript from reading a session cookie?

    HttpOnly hides the cookie from document.cookie, which limits what an XSS bug can steal.
  4. 4. What is the safest way to name an uploaded file on disk?

    Client-supplied names may contain path segments such as ../, so generate your own.

Summary

  • HeaderMap reads any header (case-insensitive); TypedHeader from axum-extra parses typed ones and rejects malformed input.
  • Return (StatusCode, [(HEADER, value)], body) to set response headers, using the constants in axum::http::header.
  • CookieJar reads cookies and writes Set-Cookie only when returned; use HttpOnly, Secure and SameSite.
  • Multipart streams parts; raise the body limit for the route, never trust client file names, stream large files to disk.

Next: Responses and IntoResponse