Xpersona
A

Axum Code Review

CLAWHUB · Unverified

Reviews axum web framework code for routing patterns, extractor usage, middleware, state management, and error handling. Use when reviewing Rust code that us...

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:axum-code-review
  1. Install using `clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:axum-code-review` in an isolated environment before connecting it to live workloads.
  2. No published capability contract is available yet, so validate auth and request/response behavior manually.
  3. Review the upstream CLAWHUB listing at https://clawhub.ai/anderskev/axum-code-review before using production credentials.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-axum-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

88,185 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: axum-code-review
description: Reviews axum web framework code for routing patterns, extractor usage, middleware, state management, and error handling. Use when reviewing Rust code that uses axum, tower, or hyper for HTTP services. Covers axum 0.7+ patterns including State, Path, Query, Json extractors.
---

# Axum Code Review

## Review Workflow

1. **Check Cargo.toml** — Note axum version (0.6 vs 0.7+ have different patterns), Rust edition (2021 vs 2024), tower, tower-http features. Edition 2024 changes RPIT lifetime capture in handler return types and removes the need for `async-trait` in custom extractors.
2. **Check routing** — Route organization, method routing, nested routers
3. **Check extractors** — Order matters (body extractors must be last), correct types
4. **Check state** — Shared state via `State<T>`, not global mutable state
5. **Check error handling** — `IntoResponse` implementations, error types

## Gates (before reporting findings)

Run **in order**. Do not write a finding until the step that applies has passed.

1. **Version and edition on disk** — **Pass when:** You have read the relevant `Cargo.toml` (crate or workspace root) and can state `axum` (and related tower/tower-http) versions and Rust `edition`. **Then** apply 0.6 vs 0.7+ or Edition 2024–specific checklist items only when that file supports them.

2. **Per-finding evidence** — **Pass when:** Each issue cites `[FILE:LINE]` from the **current** tree for the handler, router, layer, or type under review (not from memory, docs-only, or another branch).

3. **Category check vs protocol** — **Pass when:** For the finding type (routing conflict, extractor order, error leak, middleware order, etc.), you ran the matching checks from the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill (e.g. full handler signature for extractor order; surrounding error mapping before “raw error to client”). **Then** add the finding.

4. **Output shape** — **Pass when:** The report lines match **Output Format** below (severity + description).

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| Route definitions, nesting, method routing | [references/routing.md](references/routing.md) |
| State, Path, Query, Json, body extractors | [references/extractors.md](references/extractors.md) |
| Tower middleware, layers, error handling | [references/middleware.md](references/middleware.md) |

## Review Checklist

### Routing
- [ ] Routes organized by domain (nested routers for `/api/users`, `/api/orders`)
- [ ] Fallback handlers defined for 404s
- [ ] Method routing explicit (`.get()`, `.post()`, not `.route()` with manual method matching)
- [ ] No route conflicts (overlapping paths with different extractors)

### Extractors
- [ ] Body-consuming extractors (`Json`, `Form

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "axum-code-review",
  "version": "1.0.3",
  "publishedAt": 1780280754815
}

references/extractors.md

# Extractors

## Extractor Ordering

Body-consuming extractors (`Json`, `Form`, `Bytes`, `String`) must be the LAST parameter. The HTTP body can only be consumed once.

```rust
// BAD - Json consumes body before Path can extract
async fn handler(Json(body): Json<CreateUser>, Path(id): Path<u64>) { ... }

// GOOD - non-body extractors first, body extractor last
async fn handler(Path(id): Path<u64>, Json(body): Json<CreateUser>) { ... }
```

## Common Extractors

### State

Shared application state. The type must implement `Clone`.

```rust
#[derive(Clone)]
struct AppState {
    pool: PgPool,        // PgPool is Clone (it's an Arc internally)
    config: Arc<Config>, // wrap non-Clone types in Arc
}

async fn handler(State(state): State<AppState>) -> impl IntoResponse {
    let users = query_as!(User, "SELECT ...").fetch_all(&state.pool).await?;
    Json(users)
}
```

### Path

Extract path parameters. Type must implement `Deserialize`.

```rust
// Single parameter
async fn get_user(Path(id): Path<Uuid>) -> impl IntoResponse { ... }

// Multiple parameters
async fn get_comment(
    Path((post_id, comment_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse { ... }

// Named parameters via struct
#[derive(Deserialize)]
struct CommentPath {
    post_id: Uuid,
    comment_id: Uuid,
}
async fn get_comment(Path(path): Path<CommentPath>) -> impl IntoResponse { ... }
```

### Query

Extract query string parameters.

```rust
#[derive(Deserialize)]
struct ListParams {
    #[serde(default = "default_page")]
    page: u32,
    #[serde(default = "default_per_page")]
    per_page: u32,
    search: Option<String>,
}

fn default_page() -> u32 { 1 }
fn default_per_page() -> u32 { 20 }

async fn list_users(Query(params): Query<ListParams>) -> impl IntoResponse { ... }
```

### Json

Deserializes JSON request body. Must be the last extractor.

```rust
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}

async fn create_user(
    State(state): State<AppState>,
    Json(input): Json<CreateUser>,
) -> Result<impl IntoResponse, AppError> {
    let user = insert_user(&state.pool, &input).await?;
    Ok((StatusCode::CREATED, Json(user)))
}
```

### Extension

For request-scoped data injected by middleware (e.g., authenticated user).

```rust
// Middleware injects
req.extensions_mut().insert(AuthUser { id: user_id });

// Handler extracts
async fn handler(Extension(user): Extension<AuthUser>) -> impl IntoResponse { ... }
```

## Custom Extractors and `async fn` in Traits (Edition 2024)

Since Rust 1.75, `async fn` is stable in trait definitions and implementations. Custom extractors no longer need `#[async_trait]`.

```rust
// BAD (pre-1.75 / unnecessary dependency)
use async_trait::async_trait;

#[async_trait]
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // ...
    }
}

// GOOD (Rust 1.75

references/middleware.md

# Middleware

## Tower Layer Pattern

Axum uses Tower for middleware. Layers wrap services to add cross-cutting concerns.

```rust
use tower_http::{
    cors::CorsLayer,
    compression::CompressionLayer,
    timeout::TimeoutLayer,
    trace::TraceLayer,
};

let app = Router::new()
    .route("/api/health", get(health))
    .nest("/api/users", users::router())
    .layer(
        ServiceBuilder::new()
            .layer(TraceLayer::new_for_http())
            .layer(TimeoutLayer::new(Duration::from_secs(30)))
            .layer(CompressionLayer::new())
            .layer(CorsLayer::permissive()) // configure properly for production
    )
    .with_state(state);
```

### Layer Ordering

Layers execute in **reverse order** of how they're added. The last `.layer()` call runs first on the request and last on the response.

```rust
Router::new()
    .layer(A)  // runs 3rd on request, 1st on response
    .layer(B)  // runs 2nd on request, 2nd on response
    .layer(C)  // runs 1st on request, 3rd on response
```

With `ServiceBuilder`, the order is top-to-bottom (more intuitive):

```rust
ServiceBuilder::new()
    .layer(C)  // runs 1st on request
    .layer(B)  // runs 2nd on request
    .layer(A)  // runs 3rd on request
```

## Common tower-http Layers

| Layer | Purpose |
|-------|---------|
| `TraceLayer` | Request/response logging with tracing spans |
| `TimeoutLayer` | Request timeout (returns 408 on timeout) |
| `CorsLayer` | CORS headers |
| `CompressionLayer` | Response compression (gzip, br, etc.) |
| `RequestBodyLimitLayer` | Limit request body size |
| `SetRequestHeaderLayer` | Add/override request headers |
| `PropagateHeaderLayer` | Copy request headers to response |

## Custom Middleware with axum::middleware

For request/response transformation with access to axum extractors:

```rust
use axum::middleware::{self, Next};

async fn auth_middleware(
    State(state): State<AppState>,
    mut req: Request,
    next: Next,
) -> Result<Response, AppError> {
    let token = req.headers()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .ok_or(AppError::Unauthorized)?;

    let user = validate_token(&state.pool, token).await?;
    req.extensions_mut().insert(user);

    Ok(next.run(req).await)
}

// Apply to specific routes
let protected = Router::new()
    .route("/profile", get(profile))
    .route_layer(middleware::from_fn_with_state(state.clone(), auth_middleware));

let app = Router::new()
    .route("/health", get(health))  // unprotected
    .merge(protected)
    .with_state(state);
```

## Tower Service Trait and `async fn` in Traits (Edition 2024)

Custom Tower `Service` implementations that previously required `#[async_trait]` can now use native `async fn`. However, the Tower `Service` trait itself uses `poll_ready`/`call` (not async fn), so this primarily applies to higher-level abstractions built on top of Tower.

For axum middleware specifically, `axum::middleware::from_fn` already uses plain async funct

references/routing.md

# Routing

## Basic Routing

```rust
use axum::{routing::{get, post, put, delete}, Router};

let app = Router::new()
    .route("/users", get(list_users).post(create_user))
    .route("/users/{id}", get(get_user).put(update_user).delete(delete_user))
    .with_state(state);
```

Note: axum 0.7.x uses `{id}` path syntax. Earlier versions used `:id`.

## Nested Routers

Organize routes by domain. Each module can define its own router.

```rust
// users.rs
pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(list).post(create))
        .route("/{id}", get(show).put(update).delete(destroy))
}

// main.rs
let app = Router::new()
    .nest("/api/users", users::router())
    .nest("/api/orders", orders::router())
    .fallback(handle_404)
    .with_state(state);
```

### Nested Router State

Nested routers must use the same state type or a subset. Use `Router::with_state()` to provide different state to nested routers:

```rust
// Sub-router with different state
let admin_router = Router::new()
    .route("/stats", get(admin_stats))
    .with_state(admin_state); // different state type

let app = Router::new()
    .nest("/admin", admin_router)  // already has its state
    .with_state(app_state);        // main app state
```

## Fallback Handlers

```rust
async fn handle_404() -> impl IntoResponse {
    (StatusCode::NOT_FOUND, Json(json!({"error": "not found"})))
}

let app = Router::new()
    .route("/api/health", get(health))
    .fallback(handle_404);
```

## Route Conflicts

Routes conflict when two patterns can match the same path. axum panics at startup when this happens.

```rust
// CONFLICT - both match /users/123
.route("/users/{id}", get(get_user))
.route("/users/{name}", get(get_user_by_name))

// SOLUTION - differentiate by prefix or use query params
.route("/users/by-id/{id}", get(get_user))
.route("/users/by-name/{name}", get(get_user_by_name))
```

## Method Routing

```rust
// Explicit per-method routing (preferred)
.route("/items", get(list_items).post(create_item))

// Method router for custom handling
use axum::routing::MethodRouter;

fn items_router() -> MethodRouter<AppState> {
    get(list_items)
        .post(create_item)
        .options(preflight)
}
```

## LazyLock for Static Route Configuration (Edition 2024)

Static route tables or regex patterns previously initialized with `once_cell::sync::Lazy` or `lazy_static!` should use `std::sync::LazyLock` (stable since Rust 1.80):

```rust
// BAD (unnecessary dependency)
use once_cell::sync::Lazy;
static ROUTE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^/api/v\d+/").unwrap());

// GOOD (std library, no extra dependency)
use std::sync::LazyLock;
static ROUTE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^/api/v\d+/").unwrap());
```

## RPIT Capture in Router Functions (Edition 2024)

Functions returning `Router` are unaffected (concrete type). But helper functions returning `impl IntoResponse` used as fallback handlers or utility responses may o

Sponsored

Ads related to Axum Code Review and adjacent AI workflows.