Authenticate API requests with generated keys
Service authentication
Better Auth · Function
apiKey() adds Better Auth's API Key plugin. It supports API-key creation, management, verification, authentication, and configurable operational policies.
apiKey configures Better Auth's API Key plugin. It can create, manage, and verify keys, while plugin options control ownership, headers, prefixes, rate limits, storage, and optional mock sessions.
apiKey(options?)| Name | Type | Description |
|---|---|---|
options | ApiKeyOptions | Optional plugin configuration controlling headers, ownership, prefixes, expiration, limits, storage, permissions, and related behavior. |
An API Key Better Auth plugin configuration object.
x-api-key by default; configure apiKeyHeaders when clients send keys through another header.import { betterAuth } from "better-auth";
import { apiKey } from "@better-auth/api-key";
export const auth = betterAuth({
plugins: [
apiKey({
defaultPrefix: "myapp",
apiKeyHeaders: ["x-api-key", "authorization"],
}),
],
});Registers the API Key plugin with a custom key prefix and accepted request headers.
Service authentication
Quota enforcement
Multi-tenant access
High-throughput verification
apiKey() installs the API Key plugin in betterAuth. It enables API-key creation, management, and verification, with configuration for headers, ownership, prefixes, limits, and storage.
Follow-up: How would you support separate key policies? Pass multiple configuration objects, each identified by a unique configId and independently configured.
The default request header is x-api-key. The apiKeyHeaders option can replace it with one header or accept several header names.
Follow-up: How can key extraction support a non-header source? Configure customAPIKeyGetter to receive the endpoint context and return the key or null.
The plugin stores keys in the database by default. It can use secondary-storage for faster lookups, but that mode requires secondaryStorage to be configured.
Follow-up: What should a deployment consider when using secondary storage? Configure fallback behavior when a key is absent from secondary storage if database recovery is needed.
apiKeyClientenableSessionForAPIKeysapiKeyHeaderscustomAPIKeyGetterconfigIdreferencesdefaultPrefixstorage