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?;| Option | Type | Default | Description |
|---|---|---|---|
key_length | usize | 64 | Length of the random key in characters (excluding prefix) |
prefix | Option<String> | None | Global prefix for all generated keys |
default_remaining | Option<i64> | None | Default usage quota for new keys |
enable_metadata | bool | false | Allow storing metadata on keys |
require_name | bool | false | Require a name when creating keys |
enable_session_for_api_keys | bool | false | Emulate 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 activeremaining: Usage quota (decremented on each use,null= unlimited)expiresAt: Optional expiration date (set viaexpiresInin 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.
| Endpoint | Method | Description |
|---|---|---|
/api-key/create | POST | Create a new API key (returns key only once) |
/api-key/get | GET | Get key metadata by ID (query param id) |
/api-key/list | GET | List all keys for the authenticated user |
/api-key/update | POST | Update key settings (body field keyId) |
/api-key/delete | POST | Delete 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
| Status | Condition |
|---|---|
| 400 | Missing or invalid required fields |
| 401 | Not authenticated |
| 404 | API key not found (or not owned by user) |