Skip to main content
createTheAuth() accepts a TheAuthConfig object. The only required field is database. Everything else is optional and enables features incrementally.

Common development setup

A minimal config for local development with username and password sign-in, theAuth-managed sessions, and no email sending:

Top-level options

DatabaseConfig
required
Database connection config. Required.
AgentConfig
Agent identity settings.
{ adapter?: AuthAdapter; session?: SessionConfig }
Human auth adapter and session config.
ApprovalConfig
CIBA async approval flow config. See Approval flows.
TheAuthHooks
Lifecycle hooks for sandboxing and custom validation. See Hooks.
HookSafetyConfig
Timeout and failure policy for beforeAuthorize and beforeAgentCreate. Defaults: 2000 ms, deny on timeout or error for beforeAuthorize, throw for beforeAgentCreate. Environment variables THEAUTH_HOOK_TIMEOUT_MS, THEAUTH_HOOK_ON_TIMEOUT and THEAUTH_HOOK_ON_ERROR set the defaults. See Hook safety.
PolicyEngineConfig
Unified policy engine cache, combine strategy, and audit sampling. See Policy engine.
{ web?: DidWebConfig }
did:web domain and path. See DIDs.
TheAuthPlugin[]
Plugin factories such as gdpr(), rateLimit(), twoFactor(). See Plugins.
string
Base URL for the auth server (e.g. https://auth.example.com). Read by plugins that build callback URLs or decide on secure cookies (OAuth, passkey, OAuth proxy).
"memory" | "database" | SecondaryStorage | { default?, rateLimit?, deviceCodes?, ... }
default:"\"memory\""
Where short-lived state lives: rate limit counters, device login codes and similar. Memory is lost on restart and not shared between instances, so use "database" or Redis when you run more than one server. See Secondary storage.
{ trustedProxyCount?: number; trustedHeader?: string }
How plugin endpoint rate limits find the real client IP. Forwarded headers are ignored unless you set the number of proxies you run or a header your edge overwrites (for example cf-connecting-ip). Without either, all clients share one rate limit bucket. See Rate limiting.
SessionFreshnessConfig
WebhookConfig[]
Webhook endpoints to notify on auth events. See Webhooks.
PasswordResetConfig
Password reset flow. See Password reset config.
Other optional top-level modules, each of which creates the matching theauth.<name> instance property when provided: magicLink, emailOtp, emailVerification, totp, passkey, org, sso, admin, apiKeys, username, phone, captcha, and redirects. Several of these require auth.session as noted in their own pages. Options that TheAuthConfig declares but createTheAuth() does not act on:
  • mcp: createTheAuth() does not read it. The OAuth 2.1 authorization server is built with createMcpModule from @glinr/theauth/mcp, which takes a McpConfig (see MCP config). theauth.mcp on the instance is only the MCP tool server registry.
  • secret: not read by createTheAuth(). Set the session secret in auth.session.secret and the MCP signing secret in McpConfig.signingSecret.
  • emitAgenticJwtClaims: not read by createTheAuth(). See Standards for the places it does work.
There is no trust or telemetry option. The trust module is always created with its defaults.

Database config

"sqlite" | "sqlite-native" | "postgres" | "mysql" | "d1"
required
Database driver to use.
string
File path for SQLite, connection string for Postgres/MySQL. Required for every provider except D1.
D1Database
D1Database binding from the Worker environment. Required when provider is “d1”.
boolean
Skip automatic CREATE TABLE IF NOT EXISTS on init. Use when you manage migrations externally (Flyway, drizzle-kit push, etc.). Defaults to false.

Agent config

Controls the agent identity lifecycle.
boolean
required
Required by the type, but not read: agent management is always available. Set it to true.
number
default:"10"
Maximum number of active agents per owner. agent.create() throws when the owner is at the limit.
string[]
Accepted but not applied: new agents get only the permissions you pass to agent.create().
boolean
default:"true"
Write every authorize() outcome (allowed and denied) to the audit log. This includes attempts by revoked or expired agents (reason agent_revoked or agent_expired). Unknown agent ids and unknown tokens write no row. When false, no rows are written by the permission engine at all.
string
default:"\"24h\""
Default agent lifetime when agent.create() is called without expiresAt. Format is a number followed by s, m, h, or d (for example "30m", "24h", "7d"); anything else makes create() throw. Every agent therefore has an expiry unless you pass expiresAt.

MCP config

Options for the OAuth 2.1 authorization server for MCP-compliant tool access. These are the fields of McpConfig, passed to createMcpModule from @glinr/theauth/mcp (see MCP). Passing them as the mcp option of createTheAuth() has no effect today.
boolean
required
Enable the MCP authorization server.
string
Token issuer URL. Appears as the iss claim in JWTs.
string
Base path for MCP endpoints.
string
required
Secret used to sign JWTs. At least 32 characters; createMcpModule throws without it. It does not fall back to any other secret.
number
Access token lifetime in seconds. Defaults to 3600 (1 hour).
number
Refresh token lifetime in seconds. Defaults to 604800 (7 days).
number
Authorization code lifetime in seconds. Defaults to 600 (10 minutes).
boolean
Reject all MCP requests without a valid Bearer token.
string[]
Custom OAuth scopes supported by this server.
string[]
Allowed resource URIs for RFC 8707 resource indicators.
string
URL of your login page. Users are redirected here when unauthenticated.
URL of your consent page. Users are redirected here to approve scopes.
Array<{ clientId, clientSecret?, redirectUris, clientName?, scope? }>
OAuth clients registered at startup (first-party apps, CLIs, test fixtures).
(userId: string, scopes: string[]) => Promise<Record<string, unknown>>
Async function to add custom claims to issued tokens.
boolean
Emit agent_id, agent_type, and trust_tier on access tokens, using getAgenticContext. See Standards.
(userId: string) => Promise<{ agentId?, agentType?, trustTier? }>
Supplies the values for those claims.

Auth config

Connects theAuth to your existing auth provider so it can resolve the human user behind incoming requests.
When auth is omitted, theauth.auth.resolveUser() always returns null (manual user management mode). Built-in adapters exported from @glinr/theauth/auth include betterAuthAdapter, authJsAdapter, clerkAdapter, bearerAuth, cookieAuth, headerAuth, apiKeyAdapter, and customAuth.

Secret rotation

Secrets that sign or encrypt data accept a list so you can rotate without invalidating what is already issued: secret: [current, ...previous]. The first entry signs and encrypts, every entry verifies and decrypts. Add the new secret at the front and deploy, then remove the old one after the longest lifetime of anything it signed. Entries can also be { id, secret }, and the id is emitted with the signature (X-TheAuth-Key-Id for webhooks, a cookie field for sessions) so verifiers try that key first. Entries must be at least 32 bytes, and empty or duplicate entries throw at startup. The list form is supported by webhook endpoint secret (see Webhooks), createStatelessSessions and createSessionCookieCache (see Session hardening). auth.session.secret and McpConfig.signingSecret remain single strings.

Session config

string
required
Signing secret for session JWTs. Min 32 characters.
number
default:"604800 (7 days)"
Session lifetime in seconds.
Declared on the type but not read: plugins that set the session cookie (OAuth, passkey) and the default token lookup always use theauth_session. To rename the cookie, use sessionName on createCookieSessionManager (see Cookie options).
number
default:"no limit"
Maximum non-expired sessions per user. Enforced inside sessionManager.create. Impersonation sessions are not counted.
'evict-oldest' | 'reject'
default:"'evict-oldest'"
What to do when maxConcurrent is reached. reject makes create throw MultiSessionLimitError.
(revoked: Session[]) => Promise<void> | void
Called after sessions are revoked by revoke, revokeAll or limit eviction. Errors are swallowed. Used to fan out OIDC back-channel logout.

Sign-in gate config

A top-level signInGate option. It controls forced password changes, required second factors and trusted devices on every session-issuing path. Without it only the forced password change is enforced. See Sign-in gate for the response shapes and routes.
Array<'password' | 'social' | 'magic_link' | 'passkey'>
default:"['password', 'social', 'magic_link']"
Methods that must pass a second factor when the user has one enabled. The default applies once the signInGate block is present. With no block, no method requires one.
string
HMAC secret for challenges and device cookies. Falls back to auth.session.secret.
number
default:"300"
Challenge lifetime.
number
default:"5"
Wrong codes allowed per challenge.
object
{ enabled, trustDurationSeconds, maxDevices, cookieName }. Off unless enabled is true. Defaults are 30 days, 10 devices and theauth_trusted_device.
TwoFactorFactor[]
Extra second factors besides TOTP.

Password reset config

A top-level passwordReset option (not nested under auth). It requires auth.session, and its flow relies on the username module, so configure username too. If auth.session is missing, theauth.passwordReset is null. The caller provides an email-sending callback.
(email: string, token: string, url: string) => Promise<void>
required
Callback to deliver the reset email. Receives email, raw token, and constructed URL.
string
required
Base URL for the reset page. Token is appended as ?token=…
number
default:"3600 (1h)"
Reset token lifetime in seconds.
boolean
default:"true"
Revoke all sessions when the password is successfully reset.
number
default:"8"
Minimum new password length.
number
default:"128"
Maximum new password length.
Always use an HTTPS URL for resetUrl in production. Reset tokens in plain HTTP links can be intercepted in transit or leaked via Referer headers.

Session freshness config

Controls when sessions are considered “fresh” for sensitive operations. Pass it as the top-level sessionFreshness option; it backs theauth.sessionFreshness.
number
default:"300 (5 minutes)"
Maximum session age in seconds to be considered fresh.

Plugins

Plugins are factories passed in the plugins array. They register HTTP endpoints and lifecycle hooks. All of these are exported from @glinr/theauth/auth: Email and password is the top-level emailPassword option (with emailVerification and passwordReset alongside it), see Email and password. The emailPassword() plugin in the separate @glinr/theauth-email package is deprecated. Username and password sign-in is the top-level username option. deviceAuth() (see Device authorization) and agentRegistration() (see Agent registration tokens) are exported from @glinr/theauth/auth too. Multi-session support lives in the session module, see Multi-session.

Environment variables pattern

Never hardcode secrets in config. Pass them through environment variables:

Dev vs production example

auth.session.secret and the MCP signingSecret must be at least 32 characters. In production, generate them with openssl rand -base64 32.

Next steps

Migration guides

Switch from better-auth, Clerk, or other providers.

Database setup

SQLite, Postgres, or MySQL configuration.

Framework adapters

Mount theAuth on your framework.
Last modified on October 19, 2026