Better Auth in Rust

API Key

Create, manage, and validate API keys with rate limiting and usage tracking.

The ApiKeyPlugin provides API key management with support for rate limiting, usage quotas, expiration, and permissions.

Setup

These examples assume you've already defined AppAuthSchema. If you want a complete setup from entity definitions through Axum mounting, start with the Axum integration guide.

use better_auth::plugins::ApiKeyPlugin;

let auth = BetterAuth::<AppAuthSchema>::new(config)
    .store(store)
    .plugin(ApiKeyPlugin::new())
    .build()
    .await?;

Configuration

use better_auth::plugins::api_key::{ApiKeyConfig, RateLimitDefaults, KeyExpirationConfig};

let auth = BetterAuth::<AppAuthSchema>::new(config)
    .store(store)
    .plugin(
        ApiKeyPlugin::builder()
            .key_length(64)
            .prefix("sk_".to_string())
            .enable_metadata(true)
            .build()
    )
    .build()
    .await?;
OptionTypeDefaultDescription
key_lengthusize64Length of the random key in characters (excluding prefix)
prefixOption<String>NoneGlobal prefix for all generated keys
default_remainingOption<i64>NoneDefault usage quota for new keys
enable_metadataboolfalseAllow storing metadata on keys
require_nameboolfalseRequire a name when creating keys
enable_session_for_api_keysboolfalseEmulate sessions for API-key-authenticated requests

How It Works

Key Generation

API keys are generated as random alphabetic strings ([a-zA-Z]) of the configured length. The key format is:

{prefix}{random_alpha_chars}

Only the SHA-256 hash of the key is stored in the database. The full key is returned only once during creation and cannot be retrieved later.

Key Structure

Each API key has:

  • start: First 6 characters of the full key including prefix (for UI identification)
  • prefix: Optional prefix (e.g., sk_, pk_)
  • enabled: Whether the key is active
  • remaining: Usage quota (decremented on each use, null = unlimited)
  • expiresAt: Optional expiration date (set via expiresIn in seconds)
  • Rate limiting: Counter-based rate limits with configurable time window and max requests

API Endpoints

The API Key plugin exposes 5 client-facing endpoints. All require an authenticated session.

EndpointMethodDescription
/api-key/createPOSTCreate a new API key (returns key only once)
/api-key/getGETGet key metadata by ID (query param id)
/api-key/listGETList all keys for the authenticated user
/api-key/updatePOSTUpdate key settings (body field keyId)
/api-key/deletePOSTDelete an API key (body field keyId)

The full key value is returned only during creation. Store it securely — it cannot be retrieved later.

Fields like permissions, remaining, refillAmount, refillInterval, rateLimitEnabled, rateLimitTimeWindow, and rateLimitMax are server-only and cannot be set from HTTP client requests.

Errors

StatusCondition
400Missing or invalid required fields
401Not authenticated
404API key not found (or not owned by user)

On this page