Utf8Bytes and Bytes message payloads
Learn the axum 0.8 message payload types Utf8Bytes and Bytes, how to convert between them and String and Vec u8, and what happens with invalid UTF-8
Every WebSocket message in axum 0.8 carries its payload in one of two types. Text goes in Utf8Bytes, a wrapper around raw bytes that guarantees the contents are valid UTF-8 text. Everything else goes in Bytes, a reference-counted bundle of raw bytes with no promise about what they mean. The two types look similar, and confusing them is the most common compile error in axum 0.8 WebSocket code, because the previous version used String and Vec<u8> in the same places. This page is about the two types, the conversions between them, and what happens when bytes turn out not to be text after all.
Where This Fits
The previous page kept idle connections alive with pings. This page is about the messages that travel on a live connection: what they are made of, and how the two payload types keep text and raw data apart. Think of two kinds of envelope. One is labelled "text, guaranteed readable", and the post office promises the contents are words. The other is labelled "bytes, contents unknown", and it can hold anything at all. The label decides what the receiver is allowed to assume, and the compiler enforces the label.
The Smallest Working Version First
Here is a complete server that answers text with a character count and answers binary by checking whether the bytes are valid UTF-8. It shows both payload types in action in one handler.
# Cargo.toml
[package]
name = "ws-learn"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8.9", features = ["ws"] }
tokio = { version = "1.54.1", features = ["full"] }
bytes = "1"
// src/main.rs
use axum::{
extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use bytes::Bytes;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
match msg {
Message::Text(text) => {
let reply = format!(
"text received, {} characters: {}",
text.chars().count(),
&*text
);
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Message::Binary(bytes) => {
match Utf8Bytes::try_from(bytes.clone()) {
Ok(text) => {
let reply = format!("binary that is valid UTF-8: {}", text.as_str());
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Err(_) => {
let reply = format!(
"binary is NOT valid UTF-8, kept as raw bytes, length {}",
bytes.len()
);
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
}
Message::Close(_) => return,
_ => {}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
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();
}
Run it with cargo run. Then connect a client that sends three different messages: text with non-ASCII characters, binary that happens to be valid UTF-8, and binary that is not valid UTF-8 at all.
// src/bin/ws_client.rs
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};
#[tokio::main]
async fn main() {
let (ws, _) = connect_async("ws://127.0.0.1:3000/ws").await.unwrap();
let (mut write, mut read) = ws.split();
write
.send(Message::Text("hello, axum 🌍".into()))
.await
.unwrap();
println!("client got: {:?}", read.next().await.unwrap().unwrap());
write
.send(Message::Binary(b"plain ascii bytes".to_vec().into()))
.await
.unwrap();
println!("client got: {:?}", read.next().await.unwrap().unwrap());
write
.send(Message::Binary(vec![0xff, 0xfe, 0x41].into()))
.await
.unwrap();
println!("client got: {:?}", read.next().await.unwrap().unwrap());
write.close().await.unwrap();
}
This client needs tokio-tungstenite = "0.28" and futures-util = "0.3" in Cargo.toml. Run it with cargo run --bin ws_client while the server is running. The live run printed:
client got: Text(Utf8Bytes(b"text received, 13 characters: hello, axum 🌍"))
client got: Text(Utf8Bytes(b"binary that is valid UTF-8: plain ascii bytes"))
client got: Text(Utf8Bytes(b"binary is NOT valid UTF-8, kept as raw bytes, length 3"))
Three messages, three answers. The text hello, axum 🌍 counted 13 characters: 12 letters, spaces, and punctuation, plus one globe emoji that counts as a single character even though it takes four bytes in UTF-8. The binary plain ascii bytes turned out to be valid UTF-8, so the server could read it as text. The binary 0xff, 0xfe, 0x41 did not, so the server kept it as raw bytes and reported its length. That third case is the one this page exists for.
Three Answers, Three Kinds of Payload:
If the client prints a character count for the text, a valid UTF-8 reading for the second binary, and a raw-bytes answer for the third, both payload types are working. If the third case crashes the server or the connection, the invalid bytes were treated as text somewhere they should not have been.
The Message Enum in Axum 0.8
The Message enum is the first thing to get exactly right, because it changed between axum 0.7 and 0.8, and old code copied from tutorials will not compile. In axum 0.8.9 the enum is:
pub enum Message {
Text(Utf8Bytes),
Binary(Bytes),
Ping(Bytes),
Pong(Bytes),
Close(Option<CloseFrame>),
}
Text holds a Utf8Bytes. Binary, Ping, and Pong hold a Bytes. Close holds an optional close frame. That is the whole enum, and every message a server sends or receives is one of these five variants.
In axum 0.7 the same enum was Text(String), Binary(Vec<u8>), Ping(Vec<u8>), Pong(Vec<u8>). The 0.8 change replaced the owned String and Vec<u8> with the two byte-oriented types. The reason for the change is performance and honesty: Bytes and Utf8Bytes can share the underlying memory instead of copying it, and their types say exactly what the payload promises. A String promises valid UTF-8 and owns its memory. A Utf8Bytes promises valid UTF-8 and shares its memory. A Vec<u8> promises nothing and owns its memory. A Bytes promises nothing and shares its memory. The new types keep the promise and drop the copying.
Utf8Bytes, in Plain Words
Utf8Bytes is a wrapper around Bytes with one extra guarantee: the bytes inside are always valid UTF-8. UTF-8 is the way text is written as bytes: ordinary letters take one byte each, accented letters take two, and emoji take three or four. A sequence of bytes is valid UTF-8 when it follows those rules. A Utf8Bytes value cannot hold anything else. The type itself is the proof.
That guarantee is enforced at construction. There are two ways to build a Utf8Bytes, and they differ in how much checking they do.
The infallible ways take text that is already known to be valid, because Rust's own str and String types are always valid UTF-8. These conversions cannot fail, so they use From and into:
use axum::extract::ws::Utf8Bytes;
let from_str: Utf8Bytes = "hello".into();
let from_string: Utf8Bytes = String::from("hello").into();
let from_ref: Utf8Bytes = (&String::from("hello")).into();
let from_static = Utf8Bytes::from_static("hello");
from_static builds a Utf8Bytes from a string literal that lives for the whole program. It is the cheapest construction, because a literal needs no copying and no checking. Use it for fixed strings such as close reasons and constant replies.
The fallible way takes raw bytes and checks them. If the bytes are valid UTF-8, the conversion succeeds. If they are not, it fails with a Utf8Error, the standard error type for a UTF-8 check. This conversion uses TryFrom, because it can fail:
use axum::extract::ws::Utf8Bytes;
use bytes::Bytes;
let ok = Utf8Bytes::try_from(Bytes::from_static(b"hello"));
assert!(ok.is_ok());
let bad = Utf8Bytes::try_from(Bytes::from_static(&[0xff, 0xfe]));
assert!(bad.is_err());
The bytes 0xff and 0xfe never appear in valid UTF-8, so the second conversion fails. That failure is the correct outcome. It is the type system refusing to label non-text as text.
Reading a Utf8Bytes is easy because it behaves like a string slice. It dereferences to str, which means &*text is a &str, and every string method works on it directly. It also has as_str(), which returns the same &str without the dereference syntax, and it implements Display, so it can be printed with {} and turned into an owned String with to_string(). Its len() counts bytes, and its chars().count() counts characters, which is why the globe emoji counted as one character in the live run even though it occupies four bytes.
Converting back is one step: Bytes::from(utf8bytes) gives the raw bytes back, with the UTF-8 guarantee dropped because Bytes makes no promises.
use axum::extract::ws::Utf8Bytes;
use bytes::Bytes;
let text = Utf8Bytes::from_static("hello");
let raw: Bytes = Bytes::from(text);
assert_eq!(&raw[..], b"hello");
Bytes, in Plain Words
Bytes is the general-purpose payload type, from the bytes crate. It is a bundle of raw bytes with reference counting: several Bytes values can share the same underlying memory, and cloning a Bytes is cheap because it only copies the pointer and increments the count, not the data. That cheap cloning is the performance reason axum 0.8 moved to it. A message that passes through several hands, from the network buffer to the handler to an echo, can be shared rather than copied at each step.
Building a Bytes from owned data is straightforward:
use bytes::Bytes;
let from_vec: Bytes = Bytes::from(vec![104u8, 105u8]);
let from_slice: Bytes = Bytes::copy_from_slice(b"abc");
let from_static: Bytes = Bytes::from_static(b"abc");
let from_str: Bytes = "abc".into();
Bytes::from takes a Vec<u8> and reuses its memory without copying. copy_from_slice copies from any byte slice, which is the right call when the data lives somewhere else and must be duplicated. from_static wraps a byte string literal with no copying. The From<&str> conversion works because a string slice is already a sequence of bytes, and it copies the text into a new Bytes.
Reading a Bytes back out is just as direct:
use bytes::Bytes;
let bytes: Bytes = Bytes::from(vec![1u8, 2, 3]);
let back: Vec<u8> = bytes.to_vec();
assert_eq!(back, vec![1u8, 2, 3]);
assert_eq!(bytes.len(), 3);
assert_eq!(bytes[0], 1);
to_vec() copies the bytes into a fresh Vec<u8>. Indexing and slicing work like a byte slice. len() counts bytes. There is no text interpretation anywhere in these operations, because Bytes does not know or care whether its contents are text.
Cloning Bytes Is Cheap, Copying Is Not:
Cloning a Bytes with .clone() shares the memory and costs almost nothing. Converting it to a Vec<u8> with .to_vec() copies every byte. In a handler that forwards messages, clone the Bytes and pass it on. Reach for to_vec() only when the receiver genuinely needs an owned Vec<u8>, such as a library that takes nothing else.
Converting Between the Four Types
The conversions between Utf8Bytes, Bytes, String, and Vec<u8> form a small square, and each edge has a rule about whether it can fail.
| From | To | How | Can it fail |
|---|---|---|---|
&str, String, &String | Utf8Bytes | into() | No, text is always valid UTF-8 |
Bytes, Vec<u8> | Utf8Bytes | Utf8Bytes::try_from(...) | Yes, with Utf8Error |
Utf8Bytes | Bytes | Bytes::from(...) | No, valid text is valid bytes |
Utf8Bytes | String, &str | to_string(), as_str(), &*text | No |
Vec<u8>, &[u8], &str | Bytes | into(), copy_from_slice, from_static | No |
Bytes | Vec<u8> | to_vec() | No, copies the bytes |
Bytes | String | String::from_utf8(...) | Yes, with FromUtf8Error |
Bytes | str | std::str::from_utf8(...) | Yes, with Utf8Error |
Bytes | String, lossy | String::from_utf8_lossy(...) | Never, replaces bad bytes |
The lossy conversion deserves a warning. String::from_utf8_lossy never fails: it replaces each invalid byte with the replacement character, a diamond with a question mark inside it. That is convenient for display, and it silently destroys data. A binary payload converted lossily and then sent back out is not the payload that arrived. Use the lossy conversion for logging and error messages, never for data that must survive the round trip.
The Message type has its own converters, and they follow the same pattern. Message::text builds a text message from anything that converts into Utf8Bytes, and Message::binary builds a binary message from anything that converts into Bytes:
use axum::extract::ws::Message;
let text = Message::text("hello");
let binary = Message::binary(vec![1u8, 2, 3]);
Message::from also works directly: a String or &str becomes a Text message, and a Bytes or Vec<u8> becomes a Binary message. Going the other way, into_text tries to turn any message into a Utf8Bytes, converting binary payloads with a UTF-8 check and returning an error when the check fails. to_text does the same without consuming the message, returning a &str. into_data consumes the message and returns its raw Bytes: the text itself for a text message, the payload for a binary message, and the close reason for a close message. All three of these converters were compile-checked against axum 0.8.9, along with every conversion in the table above.
What Happens With Invalid UTF-8
There are two places invalid UTF-8 can show up, and they behave very differently.
The first place is a binary frame. A binary frame is allowed to hold any bytes at all, including 0xff and 0xfe. The server receives it as Message::Binary(Bytes) with no complaint, because nothing about a binary frame promises text. The invalid bytes only become a problem if the handler tries to read them as text, and then the check happens where the handler asks for it: Utf8Bytes::try_from returns an error, into_text returns an error, and to_text returns an error. The handler decides what to do with that error. The smallest example answers with a message explaining the bytes were kept as raw data. A real handler might log the error, reply with an error frame, or close the connection. The key point is that the decision belongs to the handler, and the connection stays open either way.
The second place is a text frame. A text frame promises valid UTF-8 by the protocol itself. A client that sends a text frame containing 0xff breaks that promise, and the underlying WebSocket library treats it as a protocol error. This was verified live: a raw client that completed the handshake and then sent a masked text frame with a single 0xff byte got no reply at all. The server closed the connection at once, with zero bytes read back. There was no error message to the client, because a protocol error ends the conversation rather than continuing it. That is the correct behaviour. A text frame that is not text is not a message with bad data. It is a broken connection.
The two cases together draw the boundary clearly. Binary frames carry anything, and the handler validates. Text frames carry text, and the protocol validates. Code that needs to accept arbitrary bytes must use binary frames. Code that uses text frames gets the validation for free, and pays for it with a closed connection when the promise is broken.
Never Force Invalid Bytes Into Text:
Converting bytes to text with an unchecked cast or an unwrap on the UTF-8 check will panic or corrupt data the first time a client sends bytes that are not text. Always handle the error from try_from, into_text, or to_text. If the handler cannot use the message as text, treat it as binary or reject it with a reply, and keep the connection open.
The Concept Behind the Two Types
The two types exist because text and binary data need different promises. Text processing assumes characters: counting, searching, printing, and parsing all need to know where one character ends and the next begins. That only works when the bytes follow the UTF-8 rules. Binary processing assumes nothing: it counts bytes, copies ranges, and hands the data to a decoder that understands the format, such as an image decoder or a serialisation library.
A single type cannot make both promises. A type that promises text must reject non-text. A type that accepts anything cannot promise text. Axum 0.8 splits the job: Utf8Bytes for the promise, Bytes for the acceptance. The Message enum then uses the right type for each frame kind, so the type of a message tells the handler what it is allowed to assume before it reads a single byte.
The sharing behaviour is the second reason for the change. Network data arrives in buffers that the library already owns. Wrapping those buffers in Bytes shares them instead of copying them into a new String or Vec<u8>. A server that echoes messages or forwards them to other clients does no copying at all on the hot path. The performance gain is not something a beginner needs to measure, but the design is worth understanding: the types were chosen so the common case, receiving a message and passing it on, is cheap.
A Richer Example With a Binary File Upload Over the Socket
The smallest example answers each message as it arrives. A richer version shows what binary messages are actually for: moving data that is not text. This server accepts binary chunks and appends them to a file, and accepts text commands to start and finish the transfer.
// src/main.rs
use axum::{
extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use bytes::Bytes;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
let mut file: Option<tokio::fs::File> = None;
let mut received: usize = 0;
while let Some(msg) = socket.recv().await {
let msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
match msg {
Message::Text(text) => {
if text.as_str() == "start" {
match OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open("upload.bin")
.await
{
Ok(f) => {
file = Some(f);
received = 0;
let _ = socket.send(Message::text("ready")).await;
}
Err(e) => {
let _ = socket
.send(Message::text(format!("cannot open file: {e}")))
.await;
}
}
} else if text.as_str() == "finish" {
if let Some(mut f) = file.take() {
let _ = f.flush().await;
}
let reply = format!("done, received {received} bytes");
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
Message::Binary(bytes) => {
if let Some(f) = file.as_mut() {
if f.write_all(&bytes).await.is_err() {
return;
}
received += bytes.len();
} else {
let _ = socket
.send(Message::text("send start before binary chunks")))
.await;
}
}
Message::Close(_) => return,
_ => {}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
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();
}
The text messages are commands: start opens the file, finish closes it and reports the total. The binary messages are the data: each chunk is written to the file exactly as it arrived, with no text interpretation. A chunk that happened to be valid UTF-8 would still be written as bytes, because the handler never asks whether it is text. That is the point of the binary variant: the data is opaque, and the handler treats it as opaque.
The received counter counts bytes, not messages, because chunks can be any size. A client that sends the file in 4,096-byte pieces and a client that sends it in one piece both end with the same total. The start command truncates the file, so a second upload from the same connection replaces the first instead of appending to it.
This pattern, text for control and binary for data, is the standard shape for WebSocket protocols that move files, images, audio, or serialised structures. The text side stays readable and debuggable. The binary side stays efficient and exact. Mixing them up, by sending file data as text or commands as binary, loses both advantages at once.
Two Variations on Reading a Message
Reading text with a fallback to binary
A handler that accepts both text and binary can normalise them into one path: try the message as text, and if the check fails, handle the raw bytes.
match msg {
Message::Text(text) => {
handle_text(text.as_str());
}
Message::Binary(bytes) => match Utf8Bytes::try_from(bytes.clone()) {
Ok(text) => {
handle_text(text.as_str());
}
Err(_) => {
handle_raw_bytes(&bytes);
}
},
_ => {}
}
The bytes.clone() is cheap, because cloning a Bytes shares the memory. The fallback keeps the handler total: every message is either text the handler can read or bytes the handler can store. Nothing is dropped silently, and nothing panics on unexpected input.
Echoing a message without looking at it
A handler that forwards messages does not need to know what they contain. The into_data converter gives the raw bytes of any message, and Message::binary wraps them again:
let data: Bytes = msg.into_data();
socket.send(Message::Binary(data)).await.unwrap();
This echoes a text message back as binary, which changes the frame type the client sees. To echo a message unchanged, send the original Message value back as it arrived, as the echo servers in this chapter do. The converter is for code that genuinely needs the bytes, such as writing them to a file or hashing them, not for echoing.
The Payload Types as a Diagram
The diagram shows the four types and the conversions that connect them, with the fallible edges marked.
&str / String
|
| into() - cannot fail
v
Utf8Bytes ---- Bytes::from() ----> Bytes
| |
| as_str(), to_string() | to_vec()
v v
&str / String Vec<u8>
^ |
| try_from() - can fail | into()
+-----------------------------------+
(Bytes or Vec<u8> checked as UTF-8)
String::from_utf8_lossy(Bytes) - never fails,
replaces bad bytes, data is lost
The safe direction is down and to the right: text into bytes always works. The checked direction is back up: bytes into text can fail, and the failure is information, not an inconvenience.
Testing the Payload Types
A test for this page needs three cases: text arrives as text, valid UTF-8 binary can be read as text, and invalid UTF-8 binary is rejected by the conversion. The test below runs the smallest example's server on a port the operating system picks and checks all three from the client side.
# Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.28"
futures-util = "0.3"
// tests/payload_test.rs
use axum::{
extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::connect_async;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
match msg {
Message::Text(text) => {
let reply = format!("text: {}", text.as_str());
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Message::Binary(bytes) => {
let reply = match Utf8Bytes::try_from(bytes) {
Ok(text) => format!("utf8: {}", text.as_str()),
Err(_) => "not utf8".to_string(),
};
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Message::Close(_) => return,
_ => {}
}
}
}
#[tokio::test]
async fn payload_types_behave_as_documented() {
// The conversion rules also hold without any network.
assert!(Utf8Bytes::try_from(bytes::Bytes::from_static(b"hello")).is_ok());
assert!(Utf8Bytes::try_from(bytes::Bytes::from_static(&[0xff])).is_err());
let app = Router::new().route("/ws", any(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let url = format!("ws://{addr}/ws");
let (ws, _) = connect_async(&url).await.unwrap();
let (mut write, mut read) = ws.split();
write
.send(tokio_tungstenite::tungstenite::Message::Text(
"hello".into(),
))
.await
.unwrap();
let reply = read.next().await.unwrap().unwrap();
assert_eq!(reply.to_text().unwrap(), "text: hello");
write
.send(tokio_tungstenite::tungstenite::Message::Binary(
b"plain ascii".to_vec().into(),
))
.await
.unwrap();
let reply = read.next().await.unwrap().unwrap();
assert_eq!(reply.to_text().unwrap(), "utf8: plain ascii");
write
.send(tokio_tungstenite::tungstenite::Message::Binary(
vec![0xff, 0xfe, 0x41].into(),
))
.await
.unwrap();
let reply = read.next().await.unwrap().unwrap();
assert_eq!(reply.to_text().unwrap(), "not utf8");
}
The test starts with two assertions that need no network at all: the try_from conversion accepts valid bytes and rejects 0xff. Those two lines pin the core rule of the page. The rest of the test proves the same rule holds across a real connection: the server reads valid binary as text and reports invalid binary as not UTF-8, while the connection stays open through all three exchanges. A test that only checked the network half would leave the conversion rule itself unproven. A test that only checked the conversion would leave the server behaviour unproven. Both halves are in the same test because they are the same rule.
Common Beginner Mistakes
Writing 0.7 code against axum 0.8
// Wrong - does not compile on axum 0.8.9
let m = Message::Text("hello".to_string());
let n = Message::Binary(vec![1u8, 2, 3]);
The compiler rejects both lines. The first reports expected Utf8Bytes, found String. The second reports expected Bytes, found Vec<u8>. The fix is the constructors that convert for you:
// Right - the constructors take what you have
let m = Message::text("hello");
let n = Message::binary(vec![1u8, 2, 3]);
Message::text accepts anything that converts into Utf8Bytes, including &str and String. Message::binary accepts anything that converts into Bytes, including Vec<u8> and &[u8]. Old tutorials and old answers show the 0.7 shapes, and they are the first thing to check when a copied example fails to compile.
Treating Utf8Bytes as a String
// Wrong - Utf8Bytes is not a String, and this does not compile
fn handle(text: Utf8Bytes) {
let owned: String = text;
}
A Utf8Bytes is not a String, and it does not convert into one by assignment. Use text.to_string() for an owned String, text.as_str() for a borrowed &str, or &*text where a &str is expected. The dereference is the idiomatic way to pass a Utf8Bytes into a function that takes &str.
Counting characters with len()
// Wrong - len counts bytes, not characters
let text = Utf8Bytes::from_static("hello 🌍");
assert_eq!(text.len(), 7);
The string hello 🌍 is 10 bytes long: 6 for hello and 4 for the globe emoji. len() returns 10. chars().count() returns 7. Confusing the two is a classic bug in any code that truncates, slices, or validates the length of user text. Count characters with chars().count() when the limit is about what the reader sees, and count bytes with len() when the limit is about the size on the wire.
Unwrapping the UTF-8 check on untrusted input
// Wrong - panics the first time a client sends non-text bytes
let text = Utf8Bytes::try_from(bytes).unwrap();
Client input is untrusted by definition. A client can send any bytes it likes in a binary frame, and the first non-text byte will panic the handler task if the check is unwrapped. Handle the error: reply with an error message, store the raw bytes, or close the connection deliberately with a close frame. Never let untrusted input decide whether the server panics.
Text Frames and Binary Frames Are Not Interchangeable:
A client that sends JSON as a binary frame and a server that reads it as text will work until the JSON contains a byte sequence that is not valid UTF-8, and then it will fail in a confusing way. Agree on the frame type with the client: text for text, binary for data. The frame type is part of the protocol between the two sides, not a detail either side can choose alone.
Final Complete Example
Here is everything from this page in one place: the server that answers text with a character count and binary with a UTF-8 check, and the client that sends all three kinds of payload.
// src/main.rs
use axum::{
extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use bytes::Bytes;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
match msg {
Message::Text(text) => {
let reply = format!(
"text received, {} characters: {}",
text.chars().count(),
&*text
);
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Message::Binary(bytes) => {
match Utf8Bytes::try_from(bytes.clone()) {
Ok(text) => {
let reply = format!("binary that is valid UTF-8: {}", text.as_str());
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
Err(_) => {
let reply = format!(
"binary is NOT valid UTF-8, kept as raw bytes, length {}",
bytes.len()
);
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
}
Message::Close(_) => return,
_ => {}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
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();
}
Run the server and the client from the first section. The three answers are the three behaviours of the two types: text counted as characters, valid binary read as text, and invalid binary kept as raw bytes. The connection stays open through all three, because the handler checked instead of assuming.
Summary
Axum 0.8 draws a line between text and bytes and makes the compiler hold it. Utf8Bytes guarantees valid UTF-8 and behaves like a string. Bytes guarantees nothing and carries anything. Text frames must be valid UTF-8, and a broken promise closes the connection. Binary frames may hold anything, and the handler decides what to do with them by trying the conversion and handling the error. The conversions between the four types, Utf8Bytes, Bytes, String, and Vec<u8>, are the working vocabulary of every WebSocket handler: the infallible ones go from text to bytes, and the fallible ones go from bytes to text.
The decision that follows is small and easy to apply. When the handler needs to read words, take the text variant and use it as a string. When the handler needs to move data, take the binary variant and keep it as bytes. When the handler is not sure which one it has, try the conversion and handle both outcomes. The last page of the chapter turns to the end of the conversation: how a side that is done says so politely, with a close frame that names the reason, instead of simply vanishing.