Signup handler

Learn how a POST signup handler checks the input, hashes the password with argon2, inserts the user, and returns 201 without the hash

A signup handler takes a name, an email, and a password, and turns them into a user account. It checks the input first, hashes the password second, inserts one row third, and answers with the new user and status 201. The password is hashed before it reaches the database, and the hash never comes back in the response. One request in, one row in the table, one complete user back out, and the password itself exists nowhere after the request ends.

Where This Fits

The table has a column for the hash, and the hashing tool produces the hash string. This page is the route that connects the two. A client sends a JSON body to POST /signup, and the handler does the work in a strict order, so a bad request fails before any hashing happens, and a good request stores a hash that the login check can verify later. The shape is the same one the user creation handler uses, with one new step in the middle: the password is hashed between validation and the INSERT.

Think of a reception desk that takes a form, checks it, stamps it, and files it. The form is the JSON body, the check is the validation, the stamp is the hash, and the filing cabinet is the table. Nothing is filed until the form is checked, and the stamp is applied before filing, never after.

The Smallest Working Version

Create a project with these files. It has one route, POST /signup, and nothing else.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }
argon2 = "0.6"

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

The sqlx line needs four features. runtime-tokio runs sqlx on the Tokio runtime, postgres adds the Postgres driver, macros turns on the query_as! macro used below, and derive turns on the FromRow derive used on the User struct. The argon2 line is the password hashing crate, version 0.6. The tower dev-dependency is only for the test near the end of this page.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    Unauthorized,
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}

AppError is one shared error type for the whole app. NotFound becomes 404 with the message "resource not found", ValidationError becomes 422 with the message inside it, InternalError becomes 500 with the fixed message "something went wrong", Unauthorized becomes 401 with the message "unauthorized", and Forbidden becomes 403 with the message "forbidden". Every error body has the same shape, {"error": "..."}, built from the status and the message in one place. The From implementation at the bottom is the bridge from database failures to this type. A missing row becomes NotFound, and every other database failure is logged with eprintln! and becomes InternalError, so the client never sees database detail. This handler uses the ValidationError and InternalError variants, and the Unauthorized variant belongs to the login check.

src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/password.rs
use argon2::{
    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
    Argon2,
};

use crate::errors::AppError;

pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|error| {
                eprintln!("password hashing failed: {error}");
                AppError::InternalError
            })
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

pub async fn verify_password(password: String, stored_hash: String) -> Result<bool, AppError> {
    tokio::task::spawn_blocking(move || {
        let parsed = match PasswordHash::new(&stored_hash) {
            Ok(parsed) => parsed,
            Err(error) => {
                eprintln!("stored password hash could not be parsed: {error}");
                return Err(AppError::InternalError);
            }
        };
        Ok(Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok())
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

The password module holds the two Argon2 calls, wrapped so they run off the async threads. Both helpers take owned String values, because the closure they hand to spawn_blocking must own everything it uses. hash_password returns the PHC string, and verify_password returns a yes or no answer. The signup handler on this page uses only the first one, and the login check uses the second. The wrapping is explained in its own section below.

src/handlers.rs
use axum::{
    Json,
    extract::State,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::{
    errors::AppError,
    password::hash_password,
};

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct SignupInput {
    pub name: String,
    pub email: String,
    pub password: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_signup_input(name: &str, email: &str, password: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    if password.chars().count() < 8 {
        return Err(AppError::ValidationError(
            "password must be at least 8 characters".to_string(),
        ));
    }
    Ok(())
}

pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_signup_input(&input.name, &input.email, &input.password)?;
    let password_hash = hash_password(input.password).await?;
    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
        input.name,
        input.email,
        password_hash
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(user)))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;
pub mod password;

use axum::{Router, routing::post};
use handlers::signup;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/signup", post(signup))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Before running the server, build the table with the two migrations from the column page, against a database of your own:

createdb ch13_password
cargo sqlx migrate run
Applied 20261114075821/migrate create users table (149.888636ms)
Applied 20261114075822/migrate add password hash column (97.278011ms)

Start the server with the connection string in the environment. DATABASE_URL is an environment variable, a named value set outside the program that the program reads at startup, and it holds the address, user, password, and database name in one string.

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo run

The terminal prints Server running at http://127.0.0.1:3000 and waits. In a second terminal, send a signup request with curl. The -i flag prints the status line and headers as well as the body, and -X POST sets the method.

curl -i -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}'

The server answers with status 201 and the new user as JSON:

HTTP/1.1 201 Created
content-type: application/json
content-length: 49

{"id":1,"name":"Asha","email":"asha@example.com"}

The id in the response is 1 because this is the first row in an empty table, and it came from the database, not from the request. The client never sent an id, and the response carries no password and no hash. Check the row landed in the table, showing only the start of the stored hash:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "SELECT id, name, email, left(password_hash, 30) AS hash_start, length(password_hash) AS hash_len FROM users;"
 id | name |      email       |           hash_start           | hash_len
----+------+------------------+--------------------------------+----------
  1 | Asha | asha@example.com | $argon2id$v=19$m=19456,t=2,p=1 |       97

The row holds the name and the email the client sent, an id and a timestamp from the database, and a 97 character hash string that starts with the Argon2id prefix. The password itself is nowhere in the table.

Working Setup:

If the curl response shows 201 and a JSON object with an id, a name, and an email, and the table row shows a hash starting with $argon2id$v=19$, the handler works end to end. The JSON body was read, the input was checked, the password was hashed, the row was inserted, and the new row came back without the hash.

Understanding the Handler Line by Line

The handler is short, and each of its pieces does one job. A beginner who understands these pieces understands every handler in this cluster, because the others are the same shape with a different SQL statement and a different step in the middle.

The two extractors

pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {

A handler in Axum is an async function, and its arguments are extractors, types that pull values out of the incoming request. State(pool) pulls the connection pool out of the router state, which is the pool main passed to app and app stored with with_state. Json(input) reads the request body and parses it as JSON into a SignupInput value. If the body is not valid JSON, or a field is missing, Axum rejects the request before the handler body runs, so the handler can trust that input.name, input.email, and input.password are present.

The return type says the handler either succeeds with a status code plus a JSON user, or fails with an AppError. Result is a Rust enum with two variants, Ok for success and Err for failure, and the ? operator used later in the body turns an Err into an early return from the handler.

The validation check

    check_signup_input(&input.name, &input.email, &input.password)?;

Validation runs before any database call and before any hashing. check_signup_input returns Result<(), AppError>, where () means the success case carries no value. The ? at the end says that if the check failed, return that error from the handler at once, and if it passed, carry on. An empty name, an email without an @ and a dot in the domain, or a password shorter than 8 characters becomes a 422 response with a plain message, and no row is written and no hash is computed.

The password rule deserves a plain sentence. Eight characters is a minimum length the app chose, not a rule Argon2 imposes. Argon2 hashes a password of any length, including an empty one. The app refuses short passwords because a short password is easy to guess no matter how slow the hash is, and the check belongs here, in plain Rust, where the error message can name the rule. The check counts characters with password.chars().count(), not bytes, so a password written in a script where one character takes several bytes is measured fairly.

Checking before hashing also saves real work. Hashing costs about a fifth of a second, and a request with a bad password would waste that time before failing anyway. Validation in memory costs nothing by comparison, so the expensive step only runs for input that already passed.

The hashing step

    let password_hash = hash_password(input.password).await?;

This line is the new step in the pipeline, and it is the only line that touches the password. hash_password takes the password by value, as an owned String, because the string is moved into the blocking thread that runs the hash, and the handler gives up ownership of it at this point. The await waits for the hash to finish, and the ? turns a hashing failure into an early return with a 500, logging the cause on the server first.

After this line, the plain password is gone. The variable input.password was moved, so no later code in the handler can read it, print it, or store it by mistake. That is not an accident of style. Moving the password into the hashing call is what makes the rest of the handler safe by construction. The only password related value left is password_hash, the PHC string, and that is what the INSERT stores.

The INSERT with RETURNING

    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
        input.name,
        input.email,
        password_hash
    )
    .fetch_one(&pool)
    .await?;

sqlx::query_as! is a macro, a piece of code that runs at compile time and writes code for you. It takes a Rust type, a SQL string, and the values to bind into the placeholders. User is the type each returned row is decoded into, and it works because User derives FromRow, which teaches sqlx how to build a User from a database row. The $1, $2, and $3 are placeholders, numbered slots in the SQL string that sqlx fills with the values listed after the string, in order. $1 gets input.name, $2 gets input.email, and $3 gets password_hash.

The column lists are deliberately different. The INSERT names four columns, because the row needs a hash stored. The RETURNING clause names three, because the response must not carry one. RETURNING is a Postgres clause that makes the INSERT send the new row back, and fetch_one receives exactly one row and decodes it into a User. The &pool argument is a reference to the connection pool, which hands the query one connection, runs it, and takes the connection back when the query finishes.

Bind Order Is Placeholder Order:

The values after the SQL string fill $1, $2, and $3 strictly in order. Swapping input.email and password_hash would store the hash in the email column and the email in the hash column, and the code would still compile, because both columns are text. The compiler checks the types, not the meaning. Read the placeholder numbers against the value list before running the server.

The 201 response

    Ok((StatusCode::CREATED, Json(user)))
}

The handler returns a tuple, a pair of values grouped together, holding the status code and the JSON body. StatusCode::CREATED is 201, the status that means a new resource was created. Json(user) serializes the User struct into JSON, turning each field into a key with the same name. Axum turns the tuple into a finished response with a content-type: application/json header. The id field is in the response because User derives Serialize, which is the trait that converts a Rust value into a format like JSON, and the hash is not in the response because User has no field for it.

Why Hashing Runs on a Blocking Thread

Argon2 hashing is slow, deliberate CPU work that runs until it finishes, about a fifth of a second with the default settings. A Tokio async runtime runs many requests on a small set of threads, and a call that blocks one of those threads stalls every other request sharing it. The password module moves the work off those threads with tokio::task::spawn_blocking.

pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|error| {
                eprintln!("password hashing failed: {error}");
                AppError::InternalError
            })
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

spawn_blocking takes a closure, a small anonymous function, and runs it on a separate thread pool built for work that blocks. The move keyword moves the password string into the closure, because the closure runs on another thread and must own everything it uses. Inside, the Argon2 call is exactly the one from the hashing page, and .map turns the resulting hash into a String. A failure inside the closure is logged and becomes InternalError, so the client sees the generic 500 and the server log keeps the cause.

The .await after the call waits for the blocking thread to finish, without blocking the async thread that is waiting. The outer .map_err(|_| AppError::InternalError)? handles the one remaining failure: the blocking task itself being cancelled or panicking, which is a server fault and also becomes a 500. The ? at the end of the chain returns the inner result from the function, so the function returns Result<String, AppError>, a hash string or an error, and the handler treats it like any other fallible step.

// Wrong - the hash runs on an async worker thread and stalls it for a fifth of a second
pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_signup_input(&input.name, &input.email, &input.password)?;
    let password_hash = Argon2::default()
        .hash_password(input.password.as_bytes())
        .map(|hash| hash.to_string())
        .unwrap();
    // ...
}

This version compiles and even works, which is what makes it a trap. One signup at a time feels fine, and ten signups at once stall the runtime, because each hash holds an async worker thread that should be serving other requests. The fix is the wrapper above. The rule is simple: any call that does heavy CPU work for a noticeable time belongs on a blocking thread, and password hashing is the clearest example of one in this app.

The Concept Behind Hash Before Insert

Hashing before the INSERT is not a matter of taste. The database is the wrong place to fix a plain password, because once the password is in the row it is stored, backed up, replicated, and logged by the database's own machinery. Hashing in the handler means the plain password only ever exists in memory, inside one request, and it is gone before the row is written. The INSERT receives a hash string, and the database never sees the password at all.

The order also keeps the failure modes clean. If hashing fails, no row is written, and the client gets a 500 with nothing half created. If the INSERT fails, the hash was computed and thrown away, and nothing was stored. Either failure leaves the table exactly as it was, and the client can retry the request safely. A handler that inserted first and hashed later would leave a row with a plain password behind on the failure path, and the cleanup for that mistake would be worse than the mistake itself.

A beginner can think of the pipeline as a one way street. The password enters, the hash leaves, and there is no turn back. Validation stands at the entrance, hashing stands in the middle, and the database stands at the end, receiving only the finished product.

A Richer Complete Example

The smallest version creates one user and returns it. A realistic session also shows what happens when the same request runs twice, when the input is bad, and when the password is too short. Run these requests against the same server.

Sending a duplicate email reaches the database, because the handler cannot know what is already in the table. The unique constraint refuses the row, and the failure becomes a 500 through the From implementation:

curl -i -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Again", "email": "asha@example.com", "password": "correct horse battery staple"}'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 32

{"error":"something went wrong"}

The server log keeps the detail the client never sees:

database error: error returned from database: duplicate key value violates unique constraint "users_email_key" at line 666

The at line 666 at the end is a line number inside the Postgres server source code, the place in the server where the error was raised. It is not a line in the reader's code, and the number changes with the Postgres version, so it is not something to match on. It is part of the log detail, and it stays in the log. That 500 is honest for this page, because the app has no error variant for a conflict yet. The duplicate is a client mistake, not a server failure, and giving it its own status is a separate piece of work.

Sending a short password never reaches the database and never runs Argon2, and the response is a 422 with the validation message:

curl -i -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha", "email": "asha2@example.com", "password": "short"}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 50

{"error":"password must be at least 8 characters"}

Sending an empty name fails the same way, before any hashing:

curl -i -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "   ", "email": "nobody@example.com", "password": "correct horse battery staple"}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 34

{"error":"name must not be empty"}

The name in that request was three spaces. trim() strips spaces from both ends before the emptiness check, so a name of only spaces counts as empty. The three requests together show the pipeline's order in action. Bad input stops at validation, a duplicate stops at the database, and only a good request pays the cost of hashing and lands a row.

The Request Flow

The path of a signup request through the app looks like this:

Client sends POST /signup with JSON body
        |
        v
Axum parses the body into SignupInput
        |
        v
Handler checks name, email, and password
        |
        +-- bad input --> 422 with {"error": message}
        |
        v
hash_password runs Argon2 on a blocking thread
        |
        +-- hashing failure --> 500 with {"error": "something went wrong"}
        |
        v
query_as! runs INSERT ... RETURNING id, name, email
        |
        +-- database failure --> 500 with {"error": "something went wrong"}
        |
        v
Handler returns 201 with the new user as JSON

Every step has one job, and a failure at any step stops the request there. The client never receives a half-created user, because the row is either fully inserted and returned, or not inserted at all, and the password never appears in any response on any path.

Testing the Signup Handler

The handler can be tested without starting a server. The tests below build the router with a real pool, send mock POST requests through it with oneshot, and check the status and the body. oneshot is a method from tower::ServiceExt that sends one request directly through the router, with no network involved.

tests/auth_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::{app, db::create_pool};
use tower::ServiceExt;

async fn router() -> axum::Router {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url).await.unwrap();
    sqlx::query!("DELETE FROM users").execute(&pool).await.unwrap();
    app(pool)
}

async fn post(router: axum::Router, uri: &str, body: &str) -> (StatusCode, String) {
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri(uri)
                .header("Content-Type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    let status = response.status();
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    (status, String::from_utf8(bytes.to_vec()).unwrap())
}

#[tokio::test]
async fn signup_returns_201_without_hash() {
    let (status, body) = post(
        router().await,
        "/signup",
        r#"{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    assert!(body.contains("\"name\":\"Asha\""));
    assert!(!body.contains("password_hash"));
    assert!(!body.contains("argon2"));
}

#[tokio::test]
async fn signup_with_short_password_returns_422() {
    let (status, body) = post(
        router().await,
        "/signup",
        r#"{"name": "Asha", "email": "asha@example.com", "password": "short"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert!(body.contains("at least 8 characters"));
}

The first test is the important one. It checks the status, checks the name is in the body, and then checks two things are absent: the words password_hash and argon2 must not appear anywhere in the response. A response that leaked the hash would fail both of those checks, so the test guards the exact property this page cares about. The second test needs no table cleanup, because a 422 never writes a row, and it never runs Argon2 either. Both tests read DATABASE_URL from the environment, so run them with the same value the server uses:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo test -- --test-threads=1
test signup_returns_201_without_hash ... ok
test signup_with_short_password_returns_422 ... ok

The --test-threads=1 flag runs the tests one at a time. The tests share one table, and running them at the same time could make one test delete rows another test is reading. Serial runs keep the shared table safe. These two tests were run against a live Postgres database while writing this page, and both passed.

Tests Need a Real Database:

These tests talk to a real Postgres database, not a fake one. That is deliberate. A signup handler is mostly a database call plus a hash, and testing it against a fake would test the fake, not the handler. Keep a separate database for tests if the app ever grows real data, so a test run never deletes rows a person cares about.

Common Beginner Mistakes

Storing the password and hashing it later

// Wrong - the plain password is in the table before anything hashes it
let user = sqlx::query_as!(
    User,
    "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
    input.name,
    input.email,
    input.password
)
.fetch_one(&pool)
.await?;

This compiles, because the column is text and the password is text, and the row it writes claims to hold a hash while holding a password. The login check would then try to parse a readable password as a PHC string, fail, and answer 500 for every login. The fix is the order on this page. Hash first, insert the hash, and never let the plain password reach the SQL string at all.

Returning the hash in the response

// Wrong - the hash travels to the client in the JSON body
#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub password_hash: Option<String>,
}

This compiles, and the response would carry the hash to every client that signs up, including anyone watching the traffic. The hash is not a password, but it is the exact value an attacker needs to start guessing offline, so handing it out removes the whole point of storing it server side. The fix is the split from the column page. User holds three fields and is the only struct that becomes JSON, and the hash lives in a struct that never serialises.

A Hash in a Response Is a Leak:

A password hash sent to a client is no longer a server secret. It can be copied, stored, and attacked at leisure, with no rate limit and no lockout to slow the guessing down. If a response body ever contains $argon2id$, the struct is wrong, not the client, and the fix is to remove the field from the struct that serialises.

Letting the client send the id

// Wrong - the client must not choose the id
#[derive(Debug, Deserialize)]
pub struct SignupInput {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub password: String,
}

The id is assigned by the database sequence, and the client has no way to know which ids are free. If the client sends an id, the INSERT either collides with an existing row or fights the sequence, and the next row the database creates on its own can collide with the client-supplied one. Leave id out of the input struct entirely. The response struct carries the id, and the input struct does not.

Forgetting Deserialize on SignupInput

// Wrong - Json<SignupInput> cannot build a value without this
#[derive(Debug)]
pub struct SignupInput {
    pub name: String,
    pub email: String,
    pub password: String,
}

Json<SignupInput> needs to turn JSON text into a SignupInput value, and without the derive there is no code that does that. The compiler reports that SignupInput does not implement Deserialize, and the fix is the one-line derive above the struct. The error message names the trait, so it points at the fix directly.

Checking the password after hashing it

// Wrong - the expensive step runs before the cheap check rejects the input
let password_hash = hash_password(input.password).await?;
check_signup_input(&input.name, &input.email, &input.password)?;

This version moves the password into the hashing call first, so the validation line after it cannot even compile, because input.password was moved. The compiler catches this one, and the lesson generalises. Cheap checks go first, expensive work goes second, and the code should read in the order the work happens. Validation, then hashing, then the INSERT, and the ? operators make each step the gate for the next.

Checking That Everything Compiles

Before running cargo run, run cargo check. This verifies the code compiles without producing an executable, which is faster. The query_as! macro needs the database at compile time, so DATABASE_URL must be set for the check as well as for the run:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo check

If the output ends with a Finished line and no errors, there are no type errors, and the SQL passed the compile time check against the real table. Then run cargo run to start the server. If the check fails with a database error, the usual cause is a missing table or a missing column, and the fix is to run the migrations first, because the macro checks the SQL against the live schema.

Final Complete Example

Here is everything from this page put together. The project has one route, one handler, the password module, and the shared error and pool files.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    Unauthorized,
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/password.rs
use argon2::{
    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
    Argon2,
};

use crate::errors::AppError;

pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|error| {
                eprintln!("password hashing failed: {error}");
                AppError::InternalError
            })
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

pub async fn verify_password(password: String, stored_hash: String) -> Result<bool, AppError> {
    tokio::task::spawn_blocking(move || {
        let parsed = match PasswordHash::new(&stored_hash) {
            Ok(parsed) => parsed,
            Err(error) => {
                eprintln!("stored password hash could not be parsed: {error}");
                return Err(AppError::InternalError);
            }
        };
        Ok(Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok())
    })
    .await
    .map_err(|_| AppError::InternalError)?
}
src/handlers.rs
use axum::{
    Json,
    extract::State,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::{
    errors::AppError,
    password::hash_password,
};

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct SignupInput {
    pub name: String,
    pub email: String,
    pub password: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_signup_input(name: &str, email: &str, password: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    if password.chars().count() < 8 {
        return Err(AppError::ValidationError(
            "password must be at least 8 characters".to_string(),
        ));
    }
    Ok(())
}

pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_signup_input(&input.name, &input.email, &input.password)?;
    let password_hash = hash_password(input.password).await?;
    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
        input.name,
        input.email,
        password_hash
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(user)))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;
pub mod password;

use axum::{Router, routing::post};
use handlers::signup;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/signup", post(signup))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Run it with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo run

Then sign up with:

curl -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}'

Summary

A signup handler is a small pipeline with a strict order, and the order is the insight. Validation before hashing, so bad input never pays the cost of Argon2. Hashing before the INSERT, so the plain password never reaches the table. An INSERT list that names the hash and a RETURNING list that does not, so the row is stored complete and the response stays clean. The password is moved into the hashing call and never comes back, the hash runs on a blocking thread so the async runtime stays free, and the client receives a 201 with an id, a name, and an email, and nothing else. The decision to carry forward is the split between the two lists. Whenever a new sensitive value arrives, write it in the INSERT and leave it out of the RETURNING, and let the struct that becomes JSON prove the split by having no field for it.