SSE stream mapping
Learn how to turn a stream of plain values into a stream of SSE Events with map and other stream helpers
Every SSE example so far built its events by hand inside the stream: the closure called Event::default().data(...) for each item. That works when the stream itself is written for SSE, but real data rarely arrives that way. A sensor produces numbers. A channel delivers chat lines. A timer ticks with no value at all. None of those are events, and Sse::new only accepts a stream of events.
Stream mapping bridges that gap. Mapping means taking a stream of one kind of value and turning each value into another kind, one item at a time, without collecting anything into a list. The values flow through, each one is transformed as it passes, and what comes out the other end is a stream of Event values ready for Sse::new. This page covers the mapping helpers you will actually use: map for plain values, then for async work, filter_map for skipping values, and channel wrappers for values that arrive from other tasks.
Where This Fits
The earlier pages treated the stream as a given: repeat_with made events directly, and the handler wrapped them. This page opens up the step before that. The stream is no longer assumed to speak SSE. It speaks whatever the data source speaks - numbers, strings, database rows - and a mapping step translates it. The handler stays the same shape: build a source stream, map it into events, wrap it in Sse::new.
Think of a factory line. Raw parts roll in on one belt, a worker at a station fits each part into a box, and boxed parts roll out on the next belt. The mapping step is the worker. The parts are your numbers or messages, the boxes are Event values, and the belt after the station is what Sse::new accepts.
The Smallest Mapping
The smallest mapping turns a stream of numbers into a stream of events with one .map call:
use axum::{
response::sse::{Event, Sse},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::convert::Infallible;
use tokio_stream::StreamExt as _;
#[tokio::main]
async fn main() {
let app = Router::new().route("/count", get(count_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000/count");
axum::serve(listener, app).await.unwrap();
}
async fn count_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::iter(1..=3).map(|n| Ok(Event::default().data(format!("count {n}"))));
Sse::new(stream)
}
stream::iter(1..=3) yields the numbers 1, 2, and 3. The .map closure runs once per number and returns an Event holding that number as text, wrapped in Ok. Curl prints the mapped output:
data: count 1
data: count 2
data: count 3
The handler never sees the numbers as a list. It sees a stream, maps it, and hands the mapped stream to Sse::new. The mapping is lazy: the closure runs only when Axum asks the stream for its next item, which happens when the browser is ready for the next event. Nothing is computed ahead of time, and nothing is stored.
Working Setup:
If curl prints data: count 1 through data: count 3 in order and then exits, the mapping works. The numbers went in, the events came out, and the stream ended cleanly after the last item.
The Map Closure and the Ok Wrapper
The closure passed to .map does two jobs at once, and it helps to see them separately. First it converts the value into an event: Event::default().data(format!("count {n}")). Then it wraps that event in Ok, because Sse requires the stream to yield Result<Event, E> values. The two jobs are written as one expression, but they are separate concerns. The conversion is about your data. The Ok wrapper is about the type Sse demands.
That split matters when the mapping can fail. A mapping that reads a file or queries a database can return Err instead of Ok, and Sse passes the error through as a stream failure, which ends the response. The Infallible in the return type says this particular stream never fails; a stream that can fail would name its real error type there instead.
Mapping with Async Work
.map runs a plain function: it gets a value and returns an event immediately. Sometimes the conversion itself needs to wait - a sleep between events, a database lookup per item, a call to another service. The .then helper is the async version of .map: its closure returns a future, and the stream awaits that future before yielding the mapped item.
use std::time::Duration;
async fn slow_count() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::iter(vec!["one", "two", "three"]).then(|word| async move {
tokio::time::sleep(Duration::from_millis(300)).await;
Ok(Event::default().data(word))
});
Sse::new(stream)
}
This needs Duration imported from std::time. Curl shows one event arriving every 300 milliseconds, with the browser receiving each the moment its sleep finishes:
data: one
data: two
data: three
The difference between .map and .then is only about waiting. Use .map when the conversion is immediate - formatting a number, building a string, wrapping a value. Use .then when the conversion waits for something - a timer, a network call, a lock. Picking the wrong one is a compile error rather than a silent bug: an async closure passed to .map returns a future instead of an event, and the types do not line up.
The Concept Behind Mapping
A stream is a sequence of values over time, and every stream helper is a way to describe what happens to each value as it passes. .map transforms, .then transforms while waiting, .filter_map transforms and sometimes drops, .take stops after a count. The helpers chain: the output of one is the input of the next, and the whole chain is still just a stream.
That chaining is what makes mapping powerful for SSE. The source stream can be anything - a list, a timer, a channel, a file reader - and the chain between it and Sse::new is where the SSE framing gets applied. The source knows nothing about events, and the handler knows nothing about the source. The mapping is the only place the two meet, which keeps both sides simple.
Helpers Chain in Any Order:
Mapping helpers can be combined freely: .map then .take(10), .filter_map then .throttle, .then then .map. Each helper takes a stream and returns a stream, so the chain can be as long as the transformation needs. The only rule is that the final stream must yield Result<Event, E> items, or Sse::new will not accept it.
Filtering While Mapping
Sometimes not every value deserves an event. A sensor that reports every second might only be interesting when the reading changes, or a number feed might only want even values. .filter_map combines mapping and filtering: the closure returns Some(event) for values to keep and None for values to drop.
async fn evens() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::iter(1..=6).filter_map(|n| {
if n % 2 == 0 {
Some(Ok(Event::default().data(format!("even {n}"))))
} else {
None
}
});
Sse::new(stream)
}
Curl prints only the even numbers:
data: even 2
data: even 4
data: even 6
Two details matter here. First, the closure passed to .filter_map on tokio_stream::StreamExt is a plain function, not an async one - it returns Option directly, so there is no async move in the closure. Second, dropped values simply vanish: the stream yields nothing for them, and the browser never knows they existed. Filtering is the right tool when the source is chatty and the client only cares about a subset.
Map and Filter_map Closures Differ:
On tokio_stream::StreamExt, .map takes a plain closure and .filter_map also takes a plain closure that returns Option. Writing async move inside the .filter_map closure is a compile error, because the helper expects an Option back, not a future. If the filtering decision needs to wait, use .then first to do the async work, then .filter_map on the result.
Mapping a Channel into Events
The most common real source is a channel: one task produces values and sends them through, and the handler receives them. Tokio's mpsc channel is the usual choice for a single producer, and tokio_stream::wrappers::ReceiverStream turns its receiving end into a stream. Mapping that stream into events is then the same .map call as before.
use tokio_stream::wrappers::ReceiverStream;
async fn channel_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let (tx, rx) = tokio::sync::mpsc::channel::<u32>(8);
tokio::spawn(async move {
for n in 1..=3u32 {
tokio::time::sleep(Duration::from_millis(200)).await;
if tx.send(n).await.is_err() {
break;
}
}
});
let stream = ReceiverStream::new(rx).map(|n| Ok(Event::default().data(format!("got {n}"))));
Sse::new(stream)
}
The spawned task sends 1, 2, and 3 with a 200 millisecond pause between them, then drops the sender, which ends the stream. Curl shows one event arriving every 200 milliseconds:
data: got 1
data: got 2
data: got 3
The channel capacity of 8 means up to 8 values can wait unread before the sender blocks. When the sender is dropped, ReceiverStream ends, and Axum closes the response. The mapping step does not care where the values came from. A list, a timer, or a channel all look the same after .map.
This example needs the sync feature of tokio-stream, because the channel wrappers live behind it:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1", features = ["sync"] }
futures-util = "0.3"
Without the feature, ReceiverStream does not exist and the import fails to compile. The same feature gates the broadcast wrapper used for chat, so it is worth turning on once and leaving on.
Channel Wrappers Need the sync Feature:
ReceiverStream and BroadcastStream are only available with tokio-stream built with its sync feature. A plain tokio-stream = "0.1" dependency compiles the timer and throttle helpers but not the channel wrappers, and the error - "no ReceiverStream in wrappers" - does not say which feature is missing. Add features = ["sync"] whenever a channel feeds a stream.
Mapping a Timer into Events
A stream can also come from a timer. tokio::time::interval ticks on a schedule, and IntervalStream turns it into a stream whose items are the ticks themselves. Mapping each tick into an event gives a heartbeat feed with no manual sleep loop.
use tokio_stream::wrappers::IntervalStream;
async fn heartbeat() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream =
IntervalStream::new(tokio::time::interval(Duration::from_secs(1)))
.map(|_| Ok(Event::default().data("tick")));
Sse::new(stream)
}
The closure ignores the tick value with |_| and builds the same event each time. This shape is equivalent to the repeat_with plus throttle pattern from the first page, and the choice between them is style: the interval version says "tick on a schedule" directly, while the throttle version says "repeat as fast as possible, then slow down". For a feed that must tick on a schedule, the interval version reads more honestly.
Mapping into Named and JSON Events
Mapping is not limited to plain data. The closure can call any Event builder method, so the same pattern produces named events and JSON events from a stream of structs. Serializing with .json_data(...).unwrap() inside the closure works here, since serializing a simple struct cannot fail:
use serde::Serialize;
#[derive(Serialize)]
struct Reading {
sensor: &'static str,
celsius: f64,
}
async fn readings_simple() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let values = vec![
Reading { sensor: "boiler", celsius: 91.5 },
Reading { sensor: "boiler", celsius: 92.0 },
];
let stream = stream::iter(values).map(|reading| {
Ok(Event::default()
.event("reading")
.json_data(reading)
.unwrap())
});
Sse::new(stream)
}
Curl prints:
event: reading
data: {"sensor":"boiler","celsius":91.5}
event: reading
data: {"sensor":"boiler","celsius":92.0}
The mapping closure is where the event shape is decided, so changing the feed from plain text to JSON is a change to one closure, not to the handler structure. That is the payoff of keeping the mapping step separate from the source and from the response.
What Happens When a Value Flows Through
Here is the path of one number through the mapping chain:
Source yields 2
|
v
.map closure receives 2
|
v
Closure builds Event with data "count 2"
|
v
Closure wraps it in Ok
|
v
Mapped stream yields Ok(Event)
|
v
Sse writes "data: count 2" plus a blank line
|
v
Browser fires onmessage with "count 2"
Each stage handles one concern and passes the result on. The source produces values, the closure translates them, Sse frames them, and the browser reads them. A bug in any stage shows up in only that stage: wrong values mean the source is wrong, wrong text means the closure is wrong, and missing blank lines would mean the framing is wrong - which Axum handles, so that last case does not happen in practice.
Testing a Mapped Stream
The test below maps the numbers 1 to 3 into events, sends them through a real router, and asserts the exact bytes. It verifies the whole chain at once: source, mapping, framing, and response.
use axum::{
body::{to_bytes, Body},
http::{Request, StatusCode},
response::sse::{Event, Sse},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::convert::Infallible;
use tokio_stream::StreamExt as _;
use tower::ServiceExt;
async fn count_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::iter(1..=3).map(|n| Ok(Event::default().data(format!("count {n}"))));
Sse::new(stream)
}
#[tokio::test]
async fn mapped_stream_produces_events() {
let app = Router::new().route("/count", get(count_handler));
let response = app
.oneshot(Request::builder().uri("/count").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(
&body[..],
b"data: count 1\n\ndata: count 2\n\ndata: count 3\n\n"
);
}
The tower crate is needed as a dev dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with cargo test. The assertion pins the mapped output exactly, so a change to the closure - a different format string, a missing Ok - fails the test instead of silently changing what browsers receive.
Common Beginner Mistakes
Mapping to a bare Event instead of a Result
// Wrong - does not compile
let stream = stream::iter(1..=3).map(|n| Event::default().data(format!("count {n}")));
Sse::new needs Result<Event, E> items. The compiler error mentions a type mismatch at the Sse::new call. Add Ok(...) around the event, or write the closure as |n| Ok(Event::default().data(...)).
Importing both StreamExt traits
// Wrong - does not compile, ambiguous method calls
use futures_util::stream::StreamExt as _;
use tokio_stream::StreamExt as _;
Both traits define map, then, take, and filter_map. Importing both makes every call to those methods ambiguous, and the compiler refuses to guess. Import only tokio_stream::StreamExt as _ in files that use throttle, filter_map, or the interval wrappers. Import only futures_util::stream::StreamExt in files that need neither. One import per file keeps the calls unambiguous.
Dropping the sender too early
// Wrong - the stream ends immediately
let (tx, rx) = tokio::sync::mpsc::channel::<u32>(8);
drop(tx);
let stream = ReceiverStream::new(rx).map(|n| Ok(Event::default().data(format!("got {n}"))));
A ReceiverStream ends when every sender is dropped. If the sender is dropped before any value is sent - because the task that owned it finished, or because it was never moved into a task - the stream yields nothing and the response closes at once. The browser connects, receives no events, and the connection ends. Keep the sender alive in a spawned task for as long as the feed should run, and let it drop only when the feed is truly finished.
Collecting the stream into a list first
// Wrong shape - waits for every value before sending any
let values: Vec<_> = source_stream.collect().await;
Collecting defeats the purpose of streaming. The handler would wait until the source is exhausted, then build events from the finished list, and the browser would receive everything at once at the end. Map the stream instead and return it directly, so each value flows to the browser the moment it is ready.
Mapping Is Lazy:
Nothing in a .map closure runs until Axum asks the stream for its next item. If the browser disconnects, the stream is dropped and the remaining closures never run. Do not put work with side effects - database writes, file deletes - inside a mapping closure and expect it to run for every item regardless of the client.
Final Complete Example
Here is everything from this page put together: a counter mapped from numbers, a channel feed mapped from messages, and the test that pins the counter output.
use axum::{
response::sse::{Event, Sse},
routing::get,
Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::{wrappers::ReceiverStream, StreamExt as _};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/count", get(count_handler))
.route("/channel", get(channel_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 count_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = stream::iter(1..=3).map(|n| Ok(Event::default().data(format!("count {n}"))));
Sse::new(stream)
}
async fn channel_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let (tx, rx) = tokio::sync::mpsc::channel::<u32>(8);
tokio::spawn(async move {
for n in 1..=3u32 {
tokio::time::sleep(Duration::from_millis(200)).await;
if tx.send(n).await.is_err() {
break;
}
}
});
let stream = ReceiverStream::new(rx).map(|n| Ok(Event::default().data(format!("got {n}"))));
Sse::new(stream)
}
[package]
name = "sse-mapping"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1", features = ["sync"] }
futures-util = "0.3"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
curl -N http://127.0.0.1:3000/count prints the three count events at once, and curl -N http://127.0.0.1:3000/channel prints one got event every 200 milliseconds. The two handlers differ only in their source stream. The mapping call and the Sse::new wrapper are identical, which is the whole point: once the mapping is written, any source can feed an SSE endpoint.
Summary
Mapping is the translation step between your data and the SSE format. The source stream speaks in numbers, strings, or channel messages, and a single .map call turns each value into an event. .then covers conversions that need to wait, .filter_map drops the values the client should never see, and channel wrappers turn tasks that produce values elsewhere into streams the handler can map.
The decision framework is a question about the source. If the values are already in hand, map a list or a range. If they arrive over time from another task, map a channel. If they arrive on a schedule, map a timer. In every case the handler keeps the same shape - source, map, Sse::new - and the only part that changes is the first step. That stability is what makes the mapping pattern worth learning once and reusing everywhere.