Enabling the axum ws feature for WebSocket support
Learn what the ws feature flag in the axum crate does, how to enable it in Cargo.toml, and how to verify WebSocket support works with a minimal echo endpoint.
The ws feature in axum controls whether your project can use WebSockets. WebSockets are a way for a browser and a server to keep a two-way connection open and exchange messages in real time, instead of the usual request-response pattern where the browser asks for something and gets one answer back. By default, axum does not include WebSocket support. You have to turn it on explicitly.
Why WebSockets are hidden behind a feature flag
Axum is built as a collection of optional pieces. When you add axum to your Cargo.toml, you get the core routing and handler machinery. But extractors that parse special request types - JSON bodies, query strings, forms, multipart uploads, and WebSocket upgrades - are not all compiled in by default. Each one sits behind a separate feature flag.
The reason is practical. A command-line tool that uses axum only for a health-check endpoint does not need WebSocket code compiled into its binary. A real-time chat server does. If axum always included every extractor, every project would carry code it never uses, increasing compile times and binary size for no benefit. Feature flags let you opt in to exactly the pieces your application needs.
This is the same pattern as serde and its derive feature: the crate is small by default, and you grow it deliberately.
Feature flags are additive:
Enabling the ws feature does not remove anything from axum. It only adds new types, functions, and trait implementations on top of what you already have. Your existing routes and handlers continue to work unchanged.
What the ws feature unlocks
Turning on ws makes three public types available to you:
WebSocketUpgrade- an extractor that captures the incoming HTTP request and checks whether the client wants to switch from HTTP to the WebSocket protocol.WebSocket- a handle to the upgraded connection. You use it to send and receive messages.Message- an enum that represents the different kinds of data a WebSocket can carry: text, binary, ping, pong, and close.
You import all three from the same module path:
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
Without the ws feature, this module does not exist. The import line will fail to compile, and the compiler will tell you the module is not found. That error message is your signal that the feature flag is missing.
Module path matters:
The import path is axum::extract::ws, not axum::ws or axum::websocket. Beginners often try the shorter paths and get confused when the compiler says they do not exist. The module lives inside extract because WebSocketUpgrade is an extractor like Path or Json.
Enabling the ws feature with cargo add
The fastest way to enable the feature is through cargo add. If you have been following this chapter from the start, axum is already in your Cargo.toml. The cargo add command can update an existing dependency to include a new feature without removing what is already there.
Run this command from your project directory:
cargo add axum --features ws
If axum was already present, this adds ws to its existing feature list. If axum was not present, the command adds the entire dependency with the ws feature enabled.
After either method, run cargo check to confirm the dependency resolves correctly:
cargo check
If you see no errors, the feature is active and the WebSocket types are ready to use.
A minimal WebSocket echo endpoint
The smallest useful program that proves the ws feature is working has three parts: a regular HTTP route, a WebSocket route, and the handler logic that echoes messages back.
Here is the complete src/main.rs:
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::IntoResponse,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.route("/ws", get(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();
}
async fn ws_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(|socket| handle_socket(socket))
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(Ok(message)) = socket.recv().await {
match message {
Message::Text(text) => {
if socket.send(Message::Text(text)).await.is_err() {
break;
}
}
Message::Close(_) => break,
_ => {}
}
}
}
There are several things happening here that deserve a closer look. The ws_handler function takes a WebSocketUpgrade extractor as its parameter. This tells axum to check the incoming HTTP request for the special headers that signal a WebSocket handshake. If those headers are present, axum returns a response that tells the client the protocol switch is accepted. If they are not present, axum rejects the request with an error.
The on_upgrade method takes a closure. That closure runs after the handshake completes. It receives a WebSocket value, which is the upgraded connection. The handle_socket function owns that connection and runs for as long as the client keeps it open.
Inside handle_socket, the while let loop calls socket.recv().await repeatedly. This method waits for the next incoming message. When a Message::Text arrives, the code sends the same text back to the client. When a Message::Close arrives, the loop exits and the connection ends. Other message types - binary, ping, pong - are ignored in this simple example.
Missing ws feature causes a compile error:
If you write this code without enabling the ws feature, the compiler will fail at the use axum::extract::ws::... line. The error will say the module ws does not exist in axum::extract. This is not a syntax problem or a logic bug. It is purely the missing feature flag. Add features = ["ws"] to your axum dependency and the error disappears.
Verifying the feature works end to end
Compiling successfully is the first checkpoint. But you should also confirm that a real WebSocket client can connect and exchange messages. This proves the feature is not just present at compile time but actually functional at runtime.
Step 1: Add the ws feature and write the code
Make sure your Cargo.toml includes features = ["ws"] for axum, and that src/main.rs contains the echo example from the previous section.
Step 2: Start the server
Run the project:
cargo run
You should see the message Listening on http://127.0.0.1:3000 in your terminal.
Step 3: Connect a WebSocket client
Open a browser tab and load the regular HTTP route first to confirm the server is up:
http://127.0.0.1:3000/
You should see Hello, World!. Then open your browser's developer console (F12 on most browsers) and paste this JavaScript:
const socket = new WebSocket("ws://127.0.0.1:3000/ws");
socket.onopen = () => {
console.log("Connected");
socket.send("Hello from the browser!");
};
socket.onmessage = (event) => {
console.log("Server says:", event.data);
};
socket.onclose = () => {
console.log("Disconnected");
};
When you run it, the console should print Connected, then Server says: Hello from the browser!.
Step 4: Confirm the echo works
If you see the echoed message in the console, the ws feature is fully working. The handshake succeeded, the connection stayed open, and messages flowed in both directions. To end the test, run socket.close() in the console or just close the browser tab.
Correct setup confirmation:
When the browser console prints Server says: Hello from the browser!, that is your proof that the ws feature is enabled correctly. If the feature were missing, the server would not even compile. If the handler were wrong, the connection would open but no echo would come back.
What happens if you use the WebSocket types without the feature
A common beginner mistake is to copy a WebSocket example from the internet and paste it into a project that does not have the ws feature enabled. The resulting compile error can look confusing because it does not mention feature flags directly. Instead, it says something like:
error[E0433]: failed to resolve: could not find `ws` in `extract`
or:
error[E0432]: unresolved import `axum::extract::ws`
The word ws appears in the error, which is the clue. The module exists in the axum source code, but it is not compiled into your project because the feature flag is off. This is different from a typo in the module name. If you had typed axum::extract::wss by accident, the error would look nearly identical, which is why beginners sometimes spend time checking their spelling before realizing the feature is missing.
The fix is always the same: add ws to the features list for axum in Cargo.toml, then run cargo check again.
What the ws feature does internally
When you enable ws, cargo compiles additional code inside axum that handles the WebSocket handshake. The handshake is the process where an HTTP request becomes a WebSocket connection. It requires computing a special response header that proves the server understood the client's upgrade request.
The feature also pulls in any internal dependencies axum needs for this work. You do not have to add those dependencies yourself. For example, WebSocket connections in axum are built on top of the hyper upgrade mechanism. The ws feature enables that plumbing automatically. Your Cargo.toml only needs to list axum with the ws feature. Cargo resolves the rest.
This is worth understanding because it explains why you cannot skip the feature flag and just import the types anyway. The types are not present in the compiled code at all until the feature is on. There is nothing to import.
The ws feature compared to the other extractor features
The ws feature belongs to the same family as the json, query, form, and multipart features. Each one enables a specific extractor module. The difference is that WebSocket support is more complex than the others. A JSON extractor parses a request body and returns a value. A WebSocket extractor transforms the entire connection into a persistent, bidirectional channel.
Because of this, the ws feature pulls in more internal machinery than, say, the query feature. The compile-time cost is slightly higher. But for any project that needs real-time communication - chat apps, live dashboards, multiplayer game state, browser notifications - the cost is unavoidable and worth paying.
You can combine features freely:
A project that serves JSON APIs and also supports WebSockets would list both features:
[dependencies]
axum = { version = "0.8", features = ["json", "ws"] }
There is no conflict between them. Each feature adds its own extractor module.
Common mistakes to avoid
Several errors come up repeatedly when people first enable the ws feature. Knowing them in advance saves time.
The first mistake is enabling the feature but forgetting to import the types from the correct module path. The path is axum::extract::ws, not axum::ws. The ws in the feature name is the same word, but the module is nested under extract.
The second mistake is assuming that enabling ws automatically gives you WebSocket support in other crates. It does not. For example, if you also want to use tower-http middleware that handles WebSockets, that is a separate crate with its own features. The axum ws feature only affects axum itself.
The third mistake is running the server and then trying to connect with a regular HTTP request. A WebSocket connection starts with an HTTP request, but it includes specific upgrade headers. If you open http://127.0.0.1:3000/ws in a browser address bar, you will get an error response because the browser is not sending the WebSocket handshake headers. You need a WebSocket client - JavaScript in the browser console, a tool like websocat, or a small Rust client - to complete the handshake.
Browser address bar does not do WebSockets:
Typing http://127.0.0.1:3000/ws into the address bar sends a plain HTTP request. The WebSocketUpgrade extractor will reject it because the upgrade headers are missing. Use the JavaScript new WebSocket("ws://...") approach shown above, or any dedicated WebSocket client, to test the endpoint properly.
When you do not need the ws feature
If your project is purely a REST API - handlers that receive JSON and return JSON, with no real-time component - you do not need ws. Adding it would only increase compile time and binary size without providing any benefit. Feature flags are optional for a reason. You enable the ones your application actually uses.
A health-check endpoint, a form handler, a static file server, a database-backed CRUD app - none of these need WebSockets unless you decide to add live updates. If you later add a chat feature or a notification stream, you can turn on ws at that point without touching any existing code.
Summary
The ws feature is a compile-time switch in axum that unlocks the WebSocket extractor and connection types. It is off by default to keep projects small. You turn it on by adding ws to axum's feature list in Cargo.toml, either with cargo add axum --features ws or by editing the file directly. Once enabled, you can import WebSocketUpgrade, WebSocket, and Message from axum::extract::ws and build real-time endpoints.
The echo example on this page is the smallest possible proof that the feature works. When the browser console prints the echoed message, every part of the pipeline - the feature flag, the extractor, the handshake, and the message loop - is confirmed working. From here, real WebSocket applications build on this foundation with more sophisticated message handling, application state, and client logic.