new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Better Auth · Plugins · all subjects

api-key/configuration

26 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

API key header customization with apiKeyHeaders option

The default header key for API keys is 'x-api-key', but this can be changed by setting the apiKeyHeaders option in the plugin options. The option accepts either an array of header names or a single string. Example: apiKeyHeaders: ["x-api-key", "xyz-api-key"].

customAPIKeyGetter function for extracting API keys from requests

You can pass a customAPIKeyGetter function to the plugin options, which receives the HookEndpointContext and should return the API key or null if the request is invalid. This allows custom logic for extracting API keys from any location in the request.

Multiple configurations in API key plugin with configId

The API key plugin supports multiple configurations with different settings, each identified by a unique configId. Each configuration can have its own prefix, rate limits, permissions, and other options. This is useful for public vs private keys, read-only vs read-write keys, or different rate limits for different tiers. Pass an array of configuration objects to the apiKey plugin function.

API key configuration object structure for multiple configs

Each configuration in an array passed to apiKey() has the following properties: configId (string, unique identifier), defaultPrefix (string, prefix for generated keys), enableMetadata (boolean, optional), rateLimit (object with enabled, maxRequests, timeWindow properties), and references ("user" or "organization").

API Key plugin configId option

The configId option is a unique identifier for an API Key plugin configuration. It is a string type parameter that is required when using multiple configurations. The default value is "default".

API Key plugin references option

The references option determines what the API key references, which determines ownership over the API key. It accepts either "user" or "organization" as values, with default being "user". When set to "user", API keys are owned by users and require userId on creation. When set to "organization", API keys are owned by organizations and require organizationId on creation.

API Key plugin apiKeyHeaders option

The apiKeyHeaders option specifies the header name to check for the API key. It accepts a string or array of strings. The default value is "x-api-key".

API Key plugin customAPIKeyGetter option

The customAPIKeyGetter option accepts a function that takes a GenericEndpointContext parameter and returns a string or null. This custom function is used to get the API key from the context.

API Key plugin customAPIKeyValidator option

The customAPIKeyValidator option accepts a function that takes an object with ctx (GenericEndpointContext) and key (string) properties, and returns a boolean or Promise<boolean>. This custom function is used to validate the API key.

API Key plugin customKeyGenerator option

The customKeyGenerator option accepts a function that takes an object with length (number) and prefix (string or undefined) properties, and returns a string or Promise<string>. This custom function is used to generate the API key.

API Key plugin startingCharactersConfig option

The startingCharactersConfig option customizes the starting characters configuration. It has two nested options: shouldStore (boolean, default true) determines whether to store the starting characters in the database and sets start to null if false; charactersLength (number, default 6) determines the length of the starting characters to store in the database including the prefix length.

API Key plugin defaultKeyLength option

The defaultKeyLength option is a number that specifies the length of the API key. Longer is better. The default value is 64. This does not include the prefix length.

API Key plugin defaultPrefix option

The defaultPrefix option is a string that specifies the prefix of the API key. It is recommended to append an underscore to the prefix to make it more identifiable, for example "hello_".

API Key plugin maximumPrefixLength and minimumPrefixLength options

The maximumPrefixLength option is a number that specifies the maximum length of the prefix. The minimumPrefixLength option is a number that specifies the minimum length of the prefix.

API Key plugin requireName option

The requireName option is a boolean that specifies whether to require a name for the API key. The default value is false.

API Key plugin maximumNameLength and minimumNameLength options

The maximumNameLength option is a number that specifies the maximum length of the name. The minimumNameLength option is a number that specifies the minimum length of the name.

API Key plugin enableMetadata option

The enableMetadata option is a boolean that specifies whether to enable metadata for an API key.

API Key plugin keyExpiration option

The keyExpiration option customizes the key expiration with nested options: defaultExpiresIn (number or null, default null) specifies the default expires time in milliseconds with null meaning no expiration; disableCustomExpiresTime (boolean, default false) disables the expires time passed from the client if true; minExpiresIn (number, default 1) specifies the minimum expiresIn value allowed from the client in days; maxExpiresIn (number, default 365) specifies the maximum expiresIn value allowed from the client in days.

API Key plugin schema option

The schema option accepts a custom schema for the API key plugin of type InferOptionSchema<ReturnType<typeof apiKeySchema>>.

API Key plugin deferUpdates option

The deferUpdates option is a boolean that defers non-critical updates (rate limiting counters, timestamps, remaining count) to run after the response is sent using the global backgroundTasks handler. This can significantly improve response times on serverless platforms. The default value is false. This requires backgroundTasks.handler to be configured in the main auth options. Enabling this introduces eventual consistency where the response returns optimistic data before the database is updated.

API Key plugin permissions option

The permissions option controls access at a granular level with a nested defaultPermissions property that accepts Statements or a function taking referenceId (string) and ctx (GenericEndpointContext) and returning Statements or Promise<Statements>. The referenceId is either the user ID or organization ID depending on the references setting.

API Key plugin disableKeyHashing option

The disableKeyHashing option is a boolean that disables hashing of the API key. It is strongly recommended to not disable hashing as storing API keys in plaintext makes them vulnerable to database breaches, potentially exposing all users' API keys.

API Key permissions structure

Permissions follow a resource-based structure where permissions are a record of resource types to arrays of allowed actions. Example structure: { files: ["read", "write", "delete"], users: ["read"], projects: ["read", "write"] }. When verifying an API key, all required permissions must be present in the API key's permissions for validation to succeed.

Setting default permissions for API Keys

Default permissions can be configured as a static object or as a dynamic function. As a static object: permissions: { defaultPermissions: { files: ["read"], users: ["read"] } }. As a dynamic function: permissions: { defaultPermissions: async (referenceId, ctx) => { return { files: ["read"], users: ["read"] }; } } where referenceId is either userId or orgId depending on config.

Vercel deferUpdates configuration example for API Key plugin

Example of configuring deferUpdates for Vercel: import { waitUntil } from "@vercel/functions"; export const auth = betterAuth({ advanced: { backgroundTasks: { handler: waitUntil, }, }, plugins: [ apiKey({ deferUpdates: true, }), ], });

Cloudflare Workers deferUpdates configuration example for API Key plugin

Example of configuring deferUpdates for Cloudflare Workers: import { AsyncLocalStorage } from "node:async_hooks"; const execCtxStorage = new AsyncLocalStorage<ExecutionContext>(); export const auth = betterAuth({ advanced: { backgroundTasks: { handler: waitUntil, }, }, plugins: [ apiKey({ deferUpdates: true, }), ], }); // In your request handler, wrap with execCtxStorage.run(ctx, ...)

Give your agent this brain