text event-stream content type
Learn what the text event-stream media type signals, how Axum sets it on an SSE response, and what breaks when it is wrong or missing
The text/event-stream content type is the label that turns an ordinary HTTP response into a Server-Sent Events stream. A content type, also called a media type, is a header value that tells the receiver what kind of data the body holds. When a browser sees content-type: text/event-stream, it parses the body as a stream of events. When it sees anything else, it does not, even if the body looks exactly like events. The label is what makes the stream a stream.
Where This Fits
An Sse response sets this label automatically, so a reader who only uses Sse may never type the string text/event-stream by hand. This page is about the label itself: what it signals, what else travels with it, and what breaks when a hand-built response gets it wrong. The label is small, but it is the whole contract between the server and the browser.
Think of a content type like the label on a parcel. The parcel may hold a book, but if the label says "fragile glass", the handler treats it as glass. The body of an SSE response may hold perfectly formed events, but if the label says text/plain, the browser treats it as plain text and never parses an event.
The Smallest Working Version
This is the smallest server that shows the label in the open. The handler returns an Sse response, and curl -i prints the headers so the reader can see the label with their own eyes.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"
tokio-stream = "0.1"
use axum::{
response::sse::{Event, Sse},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;
async fn events_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::repeat_with(|| Event::default().data("tick"))
.map(Ok)
.throttle(Duration::from_secs(1));
Sse::new(stream)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/events", get(events_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run, then ask for the headers in a second terminal:
curl -i -N --max-time 2 http://127.0.0.1:3000/events
The output below is the real reply from this exact server, observed live against Axum 0.8.9:
HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
transfer-encoding: chunked
date: Sat, 14 Nov 2026 09:21:44 GMT
data: tick
data: tick
Three headers do the work, and each one earns its place. The status is 200, an ordinary success. The content type is text/event-stream, with no charset and no extra value after it. The cache control is no-cache, which tells caches not to store the response. The transfer encoding is chunked, which means the body arrives in pieces with no total length announced up front, because the server does not know when the stream will end.
Working Setup:
If curl -i shows content-type: text/event-stream and cache-control: no-cache, the label is correct. If the body also shows data: tick lines arriving one per second, the stream is alive, and the label and the body agree with each other.
What the Label Signals to the Browser
The browser decides what to do with a response body by reading its content type first and its bytes second. A response labelled text/event-stream is handed to the event stream parser, which reads the body line by line, splits it into events at blank lines, and fires a message event for each one. A response labelled anything else is never handed to that parser, no matter how event-shaped its body is.
That decision has a sharp edge for EventSource, the browser API that reads SSE. EventSource sends a GET with Accept: text/event-stream, which is the client asking for this media type, and then it checks the reply. If the reply's content type is not text/event-stream, the EventSource treats the connection as failed, fires an error event, and retries the request. The retry never succeeds, because the server keeps answering with the wrong label, so the client retries in a loop and no event is ever delivered. The symptom is a page that looks connected, because requests keep going out, while nothing ever arrives.
The label also signals intent to everything between the server and the browser. A proxy that sees text/event-stream knows the response is a stream and should be passed through as it arrives, rather than held until complete. A cache that sees cache-control: no-cache beside it knows not to store the response and serve a stale copy to the next client. The two headers work as a pair: the content type names the format, and the cache control keeps the stream live.
What Axum Sets, and Where It Comes From
Sse sets exactly two headers when it turns into a response, and it sets them every time, with no configuration. The Axum 0.8.9 source does this in the IntoResponse implementation for Sse: it pairs the content type text/event-stream with the cache control no-cache, and wraps the event stream as the body. The reader does not set either header by hand when using Sse, and there is no builder method to change them, because they are part of what makes the response an SSE response.
The exact value of the content type matters. It is text/event-stream and nothing more. There is no charset=utf-8 after it, even though the body is UTF-8 text. Axum uses the mime::TEXT_EVENT_STREAM constant, which is exactly that string. A hand-built response that writes text/event-stream; charset=utf-8 is not the same value, and while most browsers accept it, the safe shape is the exact string Axum uses. Copy the exact value when building a response by hand, and let Sse set it everywhere else.
The cache control matters just as much. no-cache does not mean "never store this". It means a cache must check with the server before reusing a stored copy, and since a stream has no end, there is nothing sensible to store. Without it, a proxy could cache the first chunk of a stream and serve that stale chunk to the next client, which would then sit waiting for events that were already sent to someone else. Sse sets it so the reader never has to remember it.
Chunked Encoding Has No Content Length:
A stream has no total length, so Axum answers with transfer-encoding: chunked instead of a content-length header. The body arrives in pieces, each piece is one or more events, and the connection stays open until the stream ends. A missing content-length on an SSE response is correct, not a bug.
Building the Response by Hand
A hand-built response is the way to see the label clearly, because every header is written out in the code. The example below returns the same SSE-shaped body as the smallest version, but it builds the response from a status, a header list, and a body string, with no Sse involved. It was run live, and its reply is shown underneath.
use axum::{
http::{header, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
};
async fn manual_handler() -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, "text/event-stream"),
(header::CACHE_CONTROL, "no-cache"),
],
"data: hello from a hand-built response\n\n",
)
.into_response()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/manual", get(manual_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The tuple holds three parts. The status is 200. The header list carries the two headers Sse would set, written out by hand. The body is one event, a data: line and a blank line, as a plain string. The .into_response() call turns the tuple into a response.
curl -i http://127.0.0.1:3000/manual
HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
content-length: 40
date: Sat, 14 Nov 2026 09:21:45 GMT
data: hello from a hand-built response
The headers match the Sse reply, except for one difference: this response has a content-length: 40, because the body is a fixed string whose length is known, while the Sse reply used chunked encoding because its body is a stream with no known end. That difference is the whole reason to prefer Sse for a real stream: a hand-built response with a fixed body ends after one event, while Sse keeps the connection open and keeps sending.
What Breaks When the Label Is Wrong
The wrong label is easy to produce and hard to notice, because the server still returns 200 and the body still looks like events. The failure shows up on the client side, where nothing is parsed. Three wrong labels cover most real failures.
text plain
A handler that returns an SSE-shaped body with text/plain is the most common mistake, and it usually happens when a handler returns a plain string instead of an Sse response. The run below is real: a handler that returns the body data: hello\n\ndata: world\n\n with content-type: text/plain; charset=utf-8.
curl -i http://127.0.0.1:3000/wrong-type
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 26
date: Sat, 14 Nov 2026 09:21:45 GMT
data: hello
data: world
The body is perfect SSE, and the label says plain text. A browser opening this with EventSource fires an error and retries forever, because the content type check fails before any byte is parsed. A curl reader sees the events and thinks the server works, which is why this mistake survives testing: curl does not check the label, and the browser does. The fix is to return an Sse response, or to set the content type to text/event-stream by hand.
curl Does Not Check the Label:
curl prints any body it receives, so a wrong content type looks fine in a curl test. The browser checks the label before parsing, so the same response fails in a browser. Always check the headers with curl -i, not just the body, when testing an SSE endpoint.
application json
A handler that returns events as JSON, with content-type: application/json, is a different design, not an SSE stream. A fetch call can read it, but an EventSource cannot, because the label is wrong for event parsing. The confusion comes from the fact that event data is often JSON: the data inside a data: line can be a JSON string, and the content type of the stream is still text/event-stream. The JSON lives inside the event, and the label names the stream, not the data. Mixing the two up produces a response that is valid JSON and useless as SSE.
text html
A handler that returns text/html by accident, usually because a route fell through to an HTML error page, makes the browser render the body as a page instead of parsing it as events. The symptom is a browser tab showing data: hello as text on a blank page, while the EventSource reports an error. The fix is the same as for text/plain: the route must return the right label, and a missing route that answers with an HTML 404 is a routing mistake, not a streaming mistake.
The Request Side, Accept
The client asks for the label before the server sends it. An EventSource sends its GET with the header Accept: text/event-stream, which is the client saying it wants an event stream back. Accept is a request header, and Content-Type is a response header, and the two are easy to confuse because they carry the same string.
The server does not have to check the Accept header. Axum's Sse response answers with text/event-stream whatever the client asked for, and a curl request with no Accept header at all still gets the stream. Checking Accept is a choice, not a requirement: a handler can read it and return a different representation, such as JSON, when the client asks for that instead. That pattern is called content negotiation, and it is optional. The rule that is not optional is the response label: whatever the client asked for, an SSE response must answer with content-type: text/event-stream, or the browser will not parse it.
The Concept Behind the Media Type
A media type is a contract written in one header. It lets a client decide how to read a body without guessing from its bytes, and it lets every proxy and cache between the two ends treat the response correctly without reading the body either. text/event-stream is a small contract: the body is UTF-8 text, split into events by blank lines, and the connection stays open while events keep coming. The contract is what makes SSE work across browsers, proxies, and servers that were all written by different people. Without the label, each of them would have to guess, and guessing is how streams break.
Variations
Checking the label with curl -i
The fastest check on any SSE endpoint is curl -i, which prints the headers before the body. Read the first two header lines: the status must be 200, and the content type must be exactly text/event-stream. The check takes one command, and it catches the most common mistake, the wrong label, before the reader ever opens a browser. The testing page for curl -N builds on this check with the live stream output.
Letting Sse set the label
The normal shape is to return Sse and never touch the headers. The label, the cache control, and the chunked encoding all come from the IntoResponse implementation, and the reader's code only builds the event stream. This shape is the right default, because it cannot get the label wrong: there is no string to mistype.
async fn events_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::repeat_with(|| Event::default().data("tick"))
.map(Ok)
.throttle(Duration::from_secs(1));
Sse::new(stream)
}
The handler returns Sse, and the response carries the right headers. The reader writes no header code at all, and the label is correct by construction.
Setting the label by hand on a manual response
The hand-built shape from above is the right shape when the response is not an Sse for some reason, such as a proxy route that forwards a stream it did not create. The two headers must both be present, and the content type must be the exact string text/event-stream with no charset added. The shape is a fallback, not a default: it is more code, and every header in it is a string that can be mistyped.
Returning JSON inside the event, not as the label
Event data is often JSON, and the JSON belongs inside the data: line. The handler below sends a JSON object as the data of one event, while the stream label stays text/event-stream. The json_data builder needs the json feature of Axum, and it returns a Result, because serializing can fail.
use axum::{
response::sse::{Event, Sse},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use serde::Serialize;
use std::convert::Infallible;
#[derive(Serialize)]
struct Score {
home: u32,
away: u32,
}
async fn score_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let score = Score { home: 2, away: 1 };
let event = Event::default().json_data(score).unwrap();
let stream = stream::once(async move { Ok(event) });
Sse::new(stream)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/score", get(score_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The reply body is data: {"home":2,"away":1} followed by a blank line, and the content type is still text/event-stream. A browser parses the event, and the page code parses the JSON inside it. The two layers are separate: the stream label names the outer format, and the JSON names the inner data. The serde and serde_json crates are needed for this shape, and the json feature of Axum must be enabled for json_data to exist. Add these lines to the dependencies:
axum = { version = "0.8", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
json_data Needs the json Feature:
Event::json_data only exists when Axum is built with its json feature. Without it, the code does not compile, and the error names the missing method. Add features = ["json"] to the Axum dependency, or serialize with serde_json::to_string and pass the string to .data() instead.
A Plain Text Diagram of the Label Check
The browser checks the label before it reads a single event:
client sends GET /events
|
v
server answers 200
|
v
browser reads content-type
|
+-- text/event-stream --> parse body as events
|
+-- anything else --> fire error, retry, never parse
|
v
browser reads cache-control: no-cache
|
v
stream flows, nothing is cached
The check happens once, at the start of the response, and it decides the fate of every byte that follows. A correct body behind a wrong label never reaches the parser.
Testing It
Two tests pin the label down. The first asserts that the Sse response carries exactly text/event-stream and no-cache. The second asserts that the wrong-type handler carries text/plain, which documents the failure shape so a future change cannot silently introduce it. Both run through oneshot, with no network and no running server.
use axum::{
body::Body,
http::{header, Request, StatusCode},
response::{sse::{Event, Sse}, IntoResponse, Response},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::convert::Infallible;
use tower::ServiceExt;
async fn events_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::once(async { Ok(Event::default().data("tick")) });
Sse::new(stream)
}
async fn wrong_type_handler() -> Response {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
"data: hello\n\ndata: world\n\n",
)
.into_response()
}
fn app() -> Router {
Router::new()
.route("/events", get(events_handler))
.route("/wrong-type", get(wrong_type_handler))
}
#[tokio::test]
async fn sse_response_has_event_stream_type_and_no_cache() {
let response = app()
.oneshot(Request::builder().uri("/events").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers().get("content-type").unwrap(),
"text/event-stream"
);
assert_eq!(
response.headers().get("cache-control").unwrap(),
"no-cache"
);
}
#[tokio::test]
async fn wrong_type_handler_admits_it_is_plain_text() {
let response = app()
.oneshot(
Request::builder()
.uri("/wrong-type")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers().get("content-type").unwrap(),
"text/plain; charset=utf-8"
);
}
Run them with:
cargo test --test content_type_test
test sse_response_has_event_stream_type_and_no_cache ... ok
test wrong_type_handler_admits_it_is_plain_text ... ok
The first test is the one that guards the label: if a future change replaces the Sse response with a plain string, the content type changes and the test fails. The second test documents the wrong shape, so the failure mode stays visible in the test suite instead of hiding in a browser.
The Tests Need tower:
The oneshot helper comes from tower::ServiceExt, so the tests need tower with the util feature as a dev-dependency. The handler code itself needs no tower import: only the test file does.
Common Beginner Mistakes
Returning a plain string from an SSE handler
// Wrong - a plain string answers with text/plain, and no browser parses it
async fn events_handler() -> &'static str {
"data: hello\n\n"
}
A &str response gets content-type: text/plain; charset=utf-8, because Axum labels a string as plain text. The body looks like SSE and the label says otherwise, so EventSource errors and retries forever. The fix is to return Sse, which sets the label, or to build the response by hand with the right headers.
Setting the label but forgetting no-cache
// Wrong - the stream label is right, and a cache may still store it
(StatusCode::OK, [(header::CONTENT_TYPE, "text/event-stream")], "data: hi\n\n")
The content type alone is not enough. Without cache-control: no-cache, a proxy may cache the first chunk and serve it stale to the next client. The fix is to set both headers, or to return Sse, which sets both every time.
Adding a charset to the label
// Wrong - the value is close, but it is not the exact media type
(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")
Most browsers accept the charset form, but the exact media type is text/event-stream with nothing after it, and that is the value Axum uses. The fix is to copy the exact string, or to let Sse set it. A mistyped label is a silent failure, so exactness is worth the care.
Confusing Accept with Content-Type
// Wrong - Accept is a request header, and it does not label the response
async fn events_handler(headers: HeaderMap) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let _ = headers.get("accept");
// returning Sse still sets content-type correctly, so this is only a confusion, not a bug
todo!()
}
Reading the Accept header does not set the response label. The response label comes from the response, and Sse sets it. The fix is to stop worrying about Accept unless the handler deliberately serves different representations, and to check the response headers with curl -i instead.
Testing only the body, never the headers
A test that collects the body and asserts it contains data: tick passes for both the right label and the wrong one, because the body is the same either way. The fix is to assert on the headers, as the tests above do. The label is the contract, so the test must check the label.
Final Complete Example
Here is everything from this page put together: the Sse handler that sets the label automatically, the hand-built response that sets it by hand, and the wrong-type handler that shows the failure shape.
use axum::{
http::{header, StatusCode},
response::{
sse::{Event, Sse},
IntoResponse, Response,
},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;
async fn events_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::repeat_with(|| Event::default().data("tick"))
.map(Ok)
.throttle(Duration::from_secs(1));
Sse::new(stream)
}
async fn manual_handler() -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, "text/event-stream"),
(header::CACHE_CONTROL, "no-cache"),
],
"data: hello from a hand-built response\n\n",
)
.into_response()
}
async fn wrong_type_handler() -> Response {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
"data: hello\n\ndata: world\n\n",
)
.into_response()
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/events", get(events_handler))
.route("/manual", get(manual_handler))
.route("/wrong-type", get(wrong_type_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the checks with these commands:
cargo check
cargo test --test content_type_test
curl -i -N --max-time 2 http://127.0.0.1:3000/events
curl -i http://127.0.0.1:3000/manual
curl -i http://127.0.0.1:3000/wrong-type
The three curl calls show the three labels side by side: the automatic one, the hand-built one, and the wrong one. Reading them together is the fastest way to learn what the label does, because the bodies are all event-shaped and only the headers differ.
Summary
The content type is a one-line contract, and it decides whether a stream is a stream. Axum's Sse sets text/event-stream and no-cache on every response, with chunked encoding for the open-ended body, and the live curl -i output proved it: the exact strings, in that order, with nothing extra. The failure mode is a correct body behind a wrong label, and it fails silently in curl while failing loudly in the browser, which is why the header check belongs in every test. The habit to carry forward is to read the headers first and the body second, because the label is what the browser reads first too. The next idea the label unlocks is the reconnect story: once the browser trusts the stream, it can drop it and come back, and the header it sends on its return is what lets the server pick up where it left off.