Sse response type

Learn what Server-Sent Events are and how the Axum Sse response type streams events to a browser over plain HTTP

Most HTTP responses work the same way. The browser asks for something, the server sends one body, and the connection closes. That shape fits a web page or a JSON answer, but it does not fit a live feed. A stock ticker, a build log, or a progress bar needs new data to arrive over time, without the browser asking again and again.

Server-Sent Events, usually shortened to SSE, solve that with plain HTTP. The server answers the first request and then keeps the connection open, sending one small message after another. Each message is called an event. The browser reads them as they arrive and updates the page. Axum has a response type built for exactly this shape. It is called Sse, and it lives in axum::response::sse.

Where This Fits

Before this page, a handler returned one value and Axum turned it into one finished response. The response had a body with a fixed end, and the browser knew the exchange was over when the body ended. An SSE handler looks similar on the outside - it is still a function that returns a value - but the value it returns is a stream instead of a finished body.

Think of the difference like a letter and a phone call. A normal response is a letter: written once, sealed, delivered. An SSE response is a phone call: the line stays open and either side can keep talking. The server does the talking here, one event at a time, and the browser listens until the server hangs up or the browser closes the tab.

The Smallest Working SSE Server

Here is the smallest complete example. It sends the word hi! once every second, forever, to any browser that connects.

src/main.rs
use axum::{
    response::sse::{Event, KeepAlive, Sse},
    routing::get,
    Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/sse", get(sse_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000/sse");
    axum::serve(listener, app).await.unwrap();
}

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // A stream that repeats an event every second
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));

    Sse::new(stream).keep_alive(KeepAlive::default())
}

The Cargo.toml file needs these dependencies:

Cargo.toml
[package]
name = "sse-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
futures-util = "0.3"

Run it with cargo run, then open a second terminal and run:

curl -N http://127.0.0.1:3000/sse

The -N flag tells curl to show each chunk the moment it arrives instead of waiting for the whole response. Without it, curl waits for the response to finish, and an endless stream never finishes, so you would see nothing. You will see this output, one line appearing each second:

HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
transfer-encoding: chunked

data: hi!

data: hi!

data: hi!

Press Ctrl+C to stop curl. The server keeps running. Each data: hi! block is one event, and the blank line after it marks the end of that event. That blank line is part of the format, not decoration. The browser waits for it before treating the event as complete.

Working Setup:

If curl prints content-type: text/event-stream and then a new data: hi! block every second, the SSE endpoint works. The headers prove Axum set the response up as an event stream, and the repeating lines prove the stream keeps flowing.

Understanding the Handler Line by Line

The handler is the new part of this page, so it deserves a close look. Everything around it - the Router, the listener, axum::serve - works the way it does in any Axum server.

The return type

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {

The handler returns Sse<...>, and the angle brackets hold the type of the stream inside it. Read the stream part from the inside out. Stream means a source that produces values over time instead of all at once. Item = Result<Event, Infallible> means each value the stream produces is a Result holding either an Event or an error. Event is one SSE message. Infallible is a Rust type that means "this stream never produces an error", which is the honest choice for a stream built from fixed values. The impl keyword means the handler does not name the exact stream type - it only promises that whatever it returns behaves like that stream. The exact type of a chained stream is long and ugly, so impl keeps the signature readable.

Building the stream

let stream = stream::repeat_with(|| Event::default().data("hi!"))
    .map(Ok)
    .throttle(Duration::from_secs(1));

This builds the stream in three steps. stream::repeat_with calls the closure again and again, producing the same event each time. Event::default().data("hi!") builds one event whose payload is the text hi!. The .map(Ok) step wraps each event in Ok, because Sse expects the stream to yield Result values, not bare events. Without it, the types do not line up and the code does not compile. .throttle(Duration::from_secs(1)) slows the stream down so it yields at most one event per second. Without the throttle, repeat_with would produce events as fast as the machine allows, flooding the connection with thousands of identical messages per second.

Wrapping the stream in Sse

Sse::new(stream).keep_alive(KeepAlive::default())

Sse::new takes the stream and turns it into a response value. The handler returns that value, and Axum sends it as the HTTP response. Sse::new sets two headers on the response by itself: content-type: text/event-stream and cache-control: no-cache. You never set those by hand. The .keep_alive(KeepAlive::default()) call adds a safety net that sends a small comment line whenever the stream goes quiet for 15 seconds. That net matters because proxies and browsers drop connections that sit idle, and it is covered in full on the keep-alive page. For now, know that it is optional and that leaving it off still gives you a working stream.

Throttle Comes from tokio-stream:

The .throttle method comes from tokio_stream::StreamExt, not from futures_util::StreamExt. Both traits offer methods named map, then, and take, so importing both at once makes the compiler complain about ambiguity. Import tokio_stream::StreamExt as _ and leave the futures trait out when you need throttle. This mix-up is easy to make because many tutorials show the wrong import.

The Concept Behind Sse

A normal Axum response is a finished value: a string, some JSON, a status code. Sse is different because its body is not finished when the handler returns. Its body is a stream, and Axum writes each item from that stream to the connection the moment the stream produces it. The HTTP response starts right away - headers first, then the first event - and the connection stays open while the stream keeps producing.

That is why the handler returns so fast even though the stream never ends. The handler does not wait for the stream to finish. It hands the stream to Axum and returns. Axum then sits in a loop: wait for the next item, write it to the socket, repeat. When the stream ends, Axum closes the response. When the browser disconnects, Axum drops the stream and the handler's work stops.

A useful mental model is a conveyor belt. The stream is the belt, each event is a box on the belt, and Axum is the worker standing at the end of the belt, taking each box and loading it onto the truck - the network connection - as it arrives. The handler only builds the belt. It never touches the truck.

Why Sse Exists Instead of a Hand-Built Response

You could build an SSE response by hand: return a body made from a stream, set the content type yourself, and remember the cache header. Axum gives you Sse so you do not have to remember any of that, and so a mistake in one of those details cannot silently break the stream. Sse sets the two headers that make browsers treat the response as an event stream, and it refuses at compile time to accept a stream whose items are not events wrapped in Result. That compile-time check catches the most common beginner error - handing over a stream of plain strings - before the server ever runs.

Sse also owns the keep-alive behaviour. Wrapping a stream in Sse and then calling .keep_alive is one line, and it works the same way for every endpoint. Doing it by hand would mean writing a timer and merging two streams yourself in every handler.

A Richer Example - a Clock That Ticks Every Two Seconds

The hi! example proves the plumbing works, but it sends the same text forever. A clock is only slightly bigger and shows the stream carrying fresh data each time.

src/main.rs
use axum::{
    response::sse::{Event, KeepAlive, Sse},
    routing::get,
    Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/sse", get(sse_handler))
        .route("/clock", get(clock_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();
}

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));
    Sse::new(stream).keep_alive(KeepAlive::default())
}

async fn clock_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| {
        let now = chrono::Local::now().format("%H:%M:%S").to_string();
        Event::default().data(now)
    })
    .map(Ok)
    .throttle(Duration::from_secs(2));
    Sse::new(stream).keep_alive(KeepAlive::default())
}

This adds the chrono crate for the time formatting:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
futures-util = "0.3"
chrono = "0.4"

Running curl -N http://127.0.0.1:3000/clock prints a new time every two seconds:

data: 14:32:10

data: 14:32:12

data: 14:32:14

Each event is built fresh inside the closure, so the payload changes every time. The shape of the code is identical to the hi! example - only the closure body changed. That is the point: once the stream plumbing is in place, the event content is just a value you compute per tick.

A browser can read this stream with the built-in EventSource object, no library needed:

static/app.js
const source = new EventSource("http://127.0.0.1:3000/clock");
source.onmessage = (event) => {
    console.log("tick:", event.data);
};

EventSource opens the connection, reads each data: line as it arrives, and calls onmessage with the event. Open the browser console and you will see tick: 14:32:10, then a new line every two seconds. If the connection drops, EventSource reconnects on its own.

SSE Is One-Way Only:

Events flow from the server to the browser and never the other way. If the browser needs to send data back, it makes a normal request to a separate route. That one-way shape is a feature, not a limitation: it keeps the protocol simple, and it is exactly what live feeds, logs, and progress updates need.

A Finite Stream That Ends on Its Own

Not every stream runs forever. A stream built from a fixed list ends after the last item, and Axum then closes the response cleanly. This is the shape for a short feed, such as sending the last three log lines when a page loads.

src/main.rs
async fn recent_logs() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::iter(vec![
        "server started",
        "database connected",
        "listening on port 3000",
    ])
    .map(|line| Ok(Event::default().data(line)));
    Sse::new(stream)
}

stream::iter turns the list into a stream that yields one item per entry, in order, and then ends. Running curl -N http://127.0.0.1:3000/logs prints all three events at once and then curl exits by itself, because the response finished:

data: server started

data: database connected

data: listening on port 3000

The handler code is the same shape as before. The only change is how the stream is built: a list instead of a repeating closure. Whether the stream ends after three items or never ends, Sse::new treats it the same way.

Sending Numbers and Other Values

Event data is always text on the wire, so a number has to become a string before it goes into .data. The format! macro does that inline.

src/main.rs
async fn counter() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::iter(1..=5)
        .map(|n| Ok(Event::default().data(format!("count {n}"))));
    Sse::new(stream)
}

Curl prints data: count 1 through data: count 5 and then the response ends. The same trick works for any value that can be formatted: floats, booleans, or a struct turned into text with format!("{:?}", value). When the payload is structured data with named fields, serializing it to JSON is the cleaner choice, and that is covered on the event builder page.

Sse Without Keep-Alive

Keep-alive is optional. Leaving it off gives a shorter handler and a stream that behaves identically while events are flowing. The difference only shows up during long silences, when a proxy may close the connection without it.

src/main.rs
async fn bare() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));
    Sse::new(stream)
}

Use this shape while learning, and add .keep_alive when the stream will sit idle for seconds at a time in real use. There is no compile-time difference between the two: Sse::new returns an Sse, and .keep_alive returns a different Sse wrapping the same stream with a timer. Both are valid handler return values.

Keep-Alive Needs the Tokio Feature:

Sse::keep_alive only exists when Axum is built with its tokio feature. That feature is on by default, so a plain axum = "0.8" dependency already has it. If you ever turn off default features and pick them by hand, add "tokio" back or the .keep_alive call will fail to compile. Sse::new itself needs no feature flag.

What Happens When a Request Arrives

Here is the full sequence from the moment a browser connects to the moment the first event lands:

Browser requests GET /sse
        |
        v
Router matches the route and calls sse_handler
        |
        v
Handler builds the stream and returns Sse
        |
        v
Axum writes the headers
content-type: text/event-stream
cache-control: no-cache
        |
        v
Axum waits for the first stream item
        |
        v
Stream yields Event, Axum writes "data: hi!" plus a blank line
        |
        v
Browser parses the event and fires onmessage
        |
        v
Axum waits for the next item, and the loop repeats

The handler runs once per connection and returns immediately. The loop after it runs for as long as the stream lives. That split is what makes one handler serve many browsers at once: each connection gets its own stream and its own loop, and they do not block each other.

Testing the SSE Response

An SSE endpoint can be tested without a network connection, using the same oneshot helper used for normal routes. The trick is to use a finite stream, because the test has to read the whole body, and an endless stream never finishes. The test below checks the status code, the content type header, and the exact bytes of the body.

tests/sse_test.rs
use axum::{
    body::{to_bytes, Body},
    http::{Request, StatusCode},
    response::sse::{Event, Sse},
    routing::get,
    Router,
};
use futures_util::stream::{self, Stream, StreamExt};
use std::convert::Infallible;
use tower::ServiceExt;

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::iter(vec!["one", "two"]).map(|w| Ok(Event::default().data(w)));
    Sse::new(stream)
}

#[tokio::test]
async fn sse_returns_event_stream() {
    let app = Router::new().route("/sse", get(sse_handler));
    let response = app
        .oneshot(Request::builder().uri("/sse").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["content-type"], "text/event-stream");
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(&body[..], b"data: one\n\ndata: two\n\n");
}

The tower crate is needed as a dev dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the test with cargo test. It passes because the body bytes are exactly what the format requires: each event is data: plus the payload plus two newlines. to_bytes collects the whole body, which is why the handler in the test uses a two-item stream. Testing an endless stream this way would hang forever, so keep test streams finite.

Common Beginner Mistakes

Returning a plain string and expecting a stream

// Wrong - sends one finished body, not a stream
async fn wrong() -> &'static str {
    "hi!"
}

This compiles and runs, but the browser gets one response and the connection closes. A &str return is a single finished body. Only Sse keeps the connection open and streams events. If curl prints your text once and exits, you returned the wrong type.

Forgetting to wrap events in Ok

// Wrong - does not compile
async fn wrong() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("hi!"));
    Sse::new(stream)
}

Sse::new requires the stream to yield Result<Event, E>, not bare Event. The compiler error points at the Sse::new call and mentions a type mismatch. The fix is one method call: add .map(Ok) after building the stream. The Ok wrapper exists so a stream that can fail - a database cursor, a file reader - can report its error through the same channel instead of needing a separate one.

Throttling with the wrong StreamExt import

// Wrong - does not compile, throttle is not on this trait
use futures_util::stream::StreamExt as _;

futures_util::StreamExt has map, then, and take, but it has no throttle. The method lives on tokio_stream::StreamExt. Importing both traits at once also fails, because the compiler cannot tell which map you mean. Pick one import per file: tokio_stream::StreamExt as _ covers map, then, take, and throttle together.

Expecting the handler to wait for the stream

A beginner sometimes writes a handler that loops over the stream itself, awaiting each item before returning. That defeats the design: the handler would never return, Axum would never send the headers, and the browser would wait forever for the first byte. Build the stream, hand it to Sse::new, and return. Axum does the waiting.

An Endless Stream Never Closes the Response:

A stream built with repeat_with has no end, so the HTTP response never finishes and curl without -N shows nothing. That is correct behaviour, not a bug. When you want the response to end, build the stream from a fixed list or use .take(n) to stop after a set number of events.

Final Complete Example

Here is everything from this page put together: two routes, one endless and one finite, a shared keep-alive, and the test that proves the finite one works.

src/main.rs
use axum::{
    response::sse::{Event, KeepAlive, Sse},
    routing::get,
    Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/sse", get(sse_handler))
        .route("/logs", get(recent_logs));
    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();
}

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));
    Sse::new(stream).keep_alive(KeepAlive::default())
}

async fn recent_logs() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::iter(vec![
        "server started",
        "database connected",
        "listening on port 3000",
    ])
    .map(|line| Ok(Event::default().data(line)));
    Sse::new(stream)
}
Cargo.toml
[package]
name = "sse-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
futures-util = "0.3"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the server with cargo run. curl -N http://127.0.0.1:3000/sse shows a new data: hi! block every second, and curl -N http://127.0.0.1:3000/logs prints the three log lines and exits. The two routes share nothing but the pattern: build a stream of Result<Event, _> values, wrap it in Sse::new, return it.

Summary

The single most useful way to think about Sse is as a change of return type. A normal handler returns a finished value, and Axum sends it once. An SSE handler returns a stream, and Axum sends each item as it arrives. Everything else - the headers, the keep-alive timer, the blank line after each event - is Sse doing the protocol work so the handler only thinks about what to send next.

That split decides when to reach for this type. If the browser needs the current value once, return a normal response. If it needs a value that keeps changing - a clock, a log, a progress bar - return Sse and let the stream carry the changes. The same handler shape serves both cases; only the stream changes. What this page did not cover is how a single event is shaped in detail - its name, its id, its retry delay - and that is where the event builder comes in.