Skip to main content
The Wacht Rust SDK consists of two primary components:
  1. WachtClient: The typed HTTP client for interacting with the Wacht backend API (e.g., retrieving users, creating organizations).
  2. AuthLayer & RequireAuth: The Axum middleware and extractors for validating incoming requests.

1. Configure the Environment

The from_env() initializer expects two environment variables:
# Your Wacht API key (do NOT expose this to the frontend)
WACHT_SECRET_API_KEY=wk_test_...

# Your Wacht deployment domain
WACHT_FRONTEND_API_URL=https://auth.yourdomain.com

2. Initialize the Client

use wacht::WachtClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // This fetches public keys and initializes the connection pool
    let client = WachtClient::from_env().await?;
    
    // You can now make API calls:
    // let user = client.users().user_id_get("user_123").send().await?;
    
    Ok(())
}

3. Protect an Axum Route

If you are building an API, use the AuthLayer to validate session tokens and attach the RequireAuth extractor to handlers that need the user’s identity.
use axum::{Router, routing::get, Json};
use wacht::middleware::{AuthLayer, RequireAuth};
use serde_json::json;

// This handler will ONLY run if the request has a valid Wacht Bearer token
async fn get_profile(auth: RequireAuth) -> Json<serde_json::Value> {
    Json(json!({
        "message": format!("Hello, {}!", auth.user_id),
        "session": auth.session_id
    }))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize global configuration and fetch public signing keys
    wacht::init_from_env().await?;

    let app = Router::new()
        .route("/profile", get(get_profile))
        .layer(AuthLayer::new());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;
    
    Ok(())
}