Enabling the Form Feature Flag in Axum
Learn how to enable Axum's optional form feature flag so you can extract HTML form data with the Form extractor, including common setup mistakes and troubleshooting.
The Form extractor lets you pull data from HTML forms into your handler. There is a small setup detail worth knowing: the Form extractor lives behind a feature flag called form, but that flag is enabled by default, so a plain axum = "0.8" dependency already includes it. You only need to think about the flag if you disabled Axum's default features. This page explains why that flag exists, exactly how to enable it, what happens if you forget, and how to verify everything works.
What Is a Feature Flag in Rust?
In Rust, a feature flag is a named option that can be turned on or off when you add a crate as a dependency. Crate authors use flags to make optional parts of their library available only when the user asks for them. This keeps the compiled binary smaller for people who don't need those parts. Axum uses many feature flags, and form is one of them.
Think of a feature flag like a light switch in a house. The house is already built, but some rooms have no light unless you flip the switch. The Form extractor is in one of those rooms, except its switch starts in the on position: with default features, the light is already on. You can use the rest of the framework without ever touching that switch, but if you turned the defaults off and then try to walk into the dark room, you'll bump into something.
The Form extractor lives behind the form feature because not every web application handles classic HTML form submissions. Axum still enables that feature by default, so most projects get Form without doing anything. You only need to opt back in if you turned the default features off to keep your binary small.
The Compile Error You Will See Without the Feature
Let's see what actually happens when you try to use Form without enabling the feature. Create a new Axum project and write a handler that uses Form:
use axum::{routing::post, Router, Form};
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginForm {
username: String,
password: String,
}
async fn login(Form(input): Form<LoginForm>) -> String {
format!("Login attempt for {}", input.username)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/login", post(login));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
If you run cargo build with default features turned off and without re-enabling form, you will get an error that looks like this:
error[E0432]: unresolved import `axum::Form`
--> src/main.rs:1:35
|
1 | use axum::{routing::post, Router, Form};
| ^^^^ no `Form` in the root
|
note: found an item that was configured out
--> axum-0.8.9/src/lib.rs:520:21
|
519 | #[cfg(feature = "form")]
| ---------------- the item is gated behind the `form` feature
520 | pub use self::form::Form;
| ^^^^
(The exact file paths and line numbers may change between versions, but the meaning is the same.)
Feature Flag Missing:
This compile error is the number one sign that the form feature is off, which happens when your Cargo.toml uses default-features = false without listing form. With default features on, you will not see this error at all. Do not try to "fix" the code. The code is correct. The problem is in your Cargo.toml.
The compiler is actually being very helpful: it tells you exactly which feature to enable. But if you are new to Rust, you might not realize that adding a feature requires a change in a separate file, not in your source code.
How to Enable the form Feature
If you use Axum's default features, form is already on and you can skip this section. The methods below are for projects that disabled default features and need to add form back. Choose the one you are most comfortable with. All of them produce the same result.
Method 1: Using Cargo's Command Line
The simplest way, if you already have axum in your Cargo.toml, is to run this command from your project directory:
cargo add axum --features form
This tells Cargo to add the axum dependency (if not already present) and include the form feature. If you already have axum, this command updates the existing entry. After running it, your Cargo.toml will contain something like:
[dependencies]
axum = { version = "0.8", features = ["form"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
Notice that serde with the derive feature is also present. The Form extractor requires serde::Deserialize on your data type, so you need serde as a dependency and the derive feature to use #[derive(Deserialize)]. The form feature of Axum brings in the necessary internal crates for parsing URL-encoded data, but it does not add serde for your own types. serde_json is there because the complete example later on this page builds a JSON response with the json! macro.
Method 2: Editing Cargo.toml Directly
Open your Cargo.toml file and modify the axum dependency line. If your axum line currently looks like this:
[dependencies]
axum = "0.8"
Change it to:
[dependencies]
axum = { version = "0.8", features = ["form"] }
You also need to add serde with derive if it's not already there. A complete minimal Cargo.toml for this page's examples would be:
[package]
name = "axum-form-feature"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["form"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
After editing, run cargo build again. This time, the Form import should resolve, and you will be able to compile the handler.
Compilation Now Succeeds:
If your project builds without errors after enabling the feature, you have set everything up correctly. You can now start the server and test the form endpoint.
Method 3: Using a Feature Flag on the Command Line
If you are in a hurry and don't want to edit Cargo.toml manually, you can temporarily build with the feature enabled:
cargo run --features axum/form
However, this is not persistent. The feature is enabled only for that one command. For a real project, you should add the feature to Cargo.toml permanently so that every developer on the team gets it automatically.
A Complete Working Example
Now that the feature flag is enabled, let's look at a slightly more realistic example. This handler extracts a login form and returns a JSON response. The code below assumes you have the Cargo.toml shown in Method 2.
use axum::{
extract::Form,
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
Json, Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct SignupForm {
username: String,
email: String,
age: Option<u8>,
}
async fn signup(Form(form): Form<SignupForm>) -> Response {
// In a real app, you would save this data to a database.
let message = format!(
"Signup successful for {} ({})",
form.username,
form.email
);
(StatusCode::CREATED, Json(serde_json::json!({
"message": message,
"age": form.age,
})))
.into_response()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/signup", post(signup));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
To test this endpoint, you need to send an HTML form with Content-Type: application/x-www-form-urlencoded. You can use curl in another terminal:
curl -X POST http://localhost:3000/signup \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=alice&email=alice%40example.com&age=25"
You should see a response like this:
{"message":"Signup successful for alice (alice@example.com)","age":25}
The Form extractor automatically decoded the URL-encoded body and turned it into a SignupForm struct. All of that works because the form feature is enabled. If you turned off default features and removed form from Cargo.toml, this code would not compile.
What Exactly Does the form Feature Enable?
When you add features = ["form"] to the axum dependency, Cargo tells the Axum crate to compile the code that implements the Form extractor and its related machinery. This code includes:
- The
Form<T>type itself. - The implementation of
FromRequestforForm<T>, which reads the request body or query string, decodes URL-encoded data, and usesserde_urlencodedinternally to convert that data into your struct. - The necessary dependencies for URL decoding:
form_urlencodedandserde_urlencodedfor parsing the encoded pairs, plusserde_path_to_errorfor the error messages.
Without this feature, those parts of Axum are simply not compiled into your binary. That's why the Form type does not exist at all - it's not just hidden or disabled at runtime, it's completely absent from the compiled code. Remember, though: with default features on, the feature is already enabled, so this only happens when you opted out of the defaults.
Feature Flags Are Compile-Time Choices:
Feature flags do not change runtime behavior dynamically. They decide what code gets compiled. When you enable form, the Form extractor becomes available for the entire crate. There is no way to turn it on only for one handler.
Common Mistakes and Misconceptions
Beginners often hit the same few walls with feature flags. Here are the specific ones to watch out for.
Mistake 1: Forgetting the serde Dependency
Enabling the form feature is necessary but not sufficient. Your own data types must implement serde::Deserialize, which requires the serde crate with the derive feature. Many people enable form, then write #[derive(Deserialize)] without adding serde to Cargo.toml, and get a compile error saying Deserialize is not found.
Missing serde Dependency:
If you see an error like cannot find derive macro Deserialize in this scope, the problem is not the Axum feature flag. You need to add serde = { version = "1", features = ["derive"] } to your Cargo.toml.
Mistake 2: Misspelling the Feature Name
The feature name is form, not forms, form-data, or urlencoded. It is exactly form, lowercase singular. If you type the wrong name, Cargo will print a warning that the feature does not exist, and your code will still fail to compile.
Mistake 3: Not Rebuilding After Changing Features
When you change Cargo.toml, you must run cargo build or cargo run again for the changes to take effect. If your editor shows errors before the rebuild finishes, those errors may be stale. Always rebuild after modifying features.
Mistake 4: Using Form with the Wrong HTTP Method
The Form extractor has special behavior depending on the HTTP method. For GET and HEAD requests, it reads from the query string, just like the Query extractor. For other methods like POST, it reads from the request body and expects the Content-Type: application/x-www-form-urlencoded header. If you send a JSON body or the wrong content type, the extractor will reject the request with an error.
This page focuses only on the feature flag, so we won't go deeper into content types here. Just remember that the feature flag and the content type are separate concerns.
Mistake 5: Using Form Without a Handler That Accepts It
Even after enabling the feature, you must actually use Form in a handler parameter. The feature flag makes the type available, but your application still needs to reference it. If you never write a handler that uses Form, the feature flag doesn't do anything visible.
How to Check Which Features Are Enabled
If you are working on a larger project and you are not sure whether form is enabled, you can check the Cargo.toml file directly. Look for the axum dependency line and see if form is listed under features. Alternatively, you can run:
cargo tree -e features -i axum
This command shows the feature graph for the axum crate. You will see a line like axum feature "form" if it is enabled.
In most cases, simply looking at Cargo.toml is enough. The feature list is right there next to the version number.
Why Axum Splits Functionality Into Feature Flags
Axum follows a philosophy common in the Rust ecosystem: keep the core small and let users opt in to what they need. This has several benefits:
- Smaller binary sizes: If you never use forms, the code for parsing form data is not compiled into your final executable. For simple services, this can make a noticeable difference.
- Faster compilation: Less code to compile means faster build times.
- Clearer dependencies: The
formfeature pulls in crates likeserde_urlencoded. If you don't need that, you don't pay for it.
The downside is that you need to remember to enable features when you start using a new extractor. It's a small one-time setup cost for long-term efficiency.
A Note on Other Axum Features
Axum has many other feature flags, each controlling different extractors or middleware. For example, query enables the Query extractor, json enables Json, and multipart enables file uploads. query, json, and form are all enabled by default; multipart is not, so it is a genuine opt-in. When you see a compile error about a missing type, always check whether the corresponding feature flag is enabled. The compiler error usually tells you the exact feature name.
Feature Flag Naming Conventions:
In Axum, the feature flag name typically matches the extractor name in lowercase. Json → json, Query → query, Form → form, Multipart → multipart. This pattern makes it easy to guess the right feature name.
Troubleshooting: A Quick Checklist
If your code using Form fails to compile, walk through this checklist in order:
- Is the
axumdependency inCargo.tomlusing theformfeature? - Did you run
cargo buildafter changingCargo.toml? - Do you have
serdewithderiveinCargo.toml? - Is the feature name spelled correctly (
form, notforms)? - Did you import
Formwithuse axum::Form;oruse axum::extract::Form;? - Does your data type derive
Deserialize?
If all of these are correct, the code should compile. If it still doesn't, read the full compiler error carefully - it often points to the exact problem.
Summary
The form feature flag in Axum is a simple switch, and it is on by default. Without it, the Form extractor does not exist in your binary, and you cannot compile any handler that tries to use it, but that only happens if you disabled default features. In that case, enabling the feature is a one-line change in Cargo.toml: add features = ["form"] to your axum dependency. You also need serde with the derive feature for your own data types. Once both are present, Form works like any other extractor, reading URL-encoded form data from requests.
If you run into a compile error about Form not existing, the first place to look is your Cargo.toml. Feature flags are the most common reason for that specific error message. Once the flag is on, you can focus on the actual logic of your form-handling code.