Skip to content
Docs
Changelog

Authentication and Organizations

Better Auth owns identity, sessions, Organizations, platform roles and OAuth.

Markdown

Session outcomes

Password sign-in can return a Session, a pending two-factor challenge, an unverified email, a Ban or a refusal. Treat those as distinct outcomes. session-outcome.ts and two-factor-outcome.ts provide the shared interpretation; hooks own navigation and error presentation.

The server registers two-factor, admin, organization, passkey, Expo and MCP OAuth plugins. Google and Apple sign-in are optional and off until configured (Social sign-in). Email verification policy comes from AUTH_SKIP_EMAIL_VERIFICATION; setup makes the intended policy explicit. Server reads use Better Auth's signed Session snapshot (at most 60 s old) or the database; sensitive operations always read the database (see Session reads).

Session reads

The session row in the database is the authority for who is signed in. Better Auth's cookie cache (session.cookieCache: compact, signed with HMAC, maxAge 60 s) keeps a snapshot of the session and user in the better-auth.session_data cookie (__Secure- on https). Server reads use that snapshot while it is valid, so most requests read no session from the database (ADR-0015).

ReadSource
The browser's presentation read (GET /api/auth/get-session): the /_auth guard, useSession, tab focusThe snapshot while it is younger than 60 s; otherwise the database, which re-issues it
SSR guard and prefetches, every oRPC procedure, the files gateway (getRequestSession, once per request)The same snapshot; otherwise the database, which re-issues it on that response
Admin procedures and the /admin guard, billing, push registration, tool approvals and assistant runs, webhook endpoint and OAuth connection changes, presigned URL minting (the request authority at database, getAuthorizedSession)The database (disableCookieCache)
Every /api/auth/* request except GET /get-session: password, email, 2FA, passkeys, sessions, Organizations, invitations, impersonation, account deletion, OAuthThe database: createAuth().handler strips the snapshot (withoutSessionSnapshot)
Membership in the Active Organization (the request authority: orgProcedure, tools, the files gateway)The member table on every request, and RLS (app.org_id()) on every statement
The read after this device changed its session (useAuthMutation({ resetSession }); refreshAuthSession on mobile)The database, which re-issues the snapshot

What a change looks like:

ChangeUI shellData
Sign-out on this deviceGone at once: Better Auth expires both cookiesRefused at once
Sign-out in another tab of the same browserThat tab leaves for /login at once (session-identity.ts)Refused at once (same cookies)
Session revoked on another device: sign out everywhere, revoke a session, password change or reset, admin revoke, banUp to 60 sUp to 60 s, then 401 and /login
Presigned download and upload URLs—New URLs require a database session check; URLs minted before revocation work until expiry, at most 15 minutes
A copy of the cookies taken before a sign-out—Up to 60 s, like a revocation
Member removed from the Active OrganizationMay show the Organization for up to 60 sRefused at once: 403 from the membership check, no rows through RLS
Platform admin demoted/admin and admin navigation re-read the role at onceAdmin procedures re-read it at once

The window is the snapshot's maxAge: a shorter one reads the database more often. session.cookieCache.version invalidates every snapshot at once; bump it when the session or user fields the server reads change. A new procedure that creates or reveals a credential builds on userProcedure or adminProcedure (backend conventions).

Organizations and roles

Signup provisions a personal Organization. A User may be a Member of several Organizations; the Session selects one Active Organization. Todos and files belong to that Organization. Platform role admin grants global administration; Org roles owner, admin and member do not grant platform administration.

Membership must be checked at the operation, even if the UI already selected an Organization. An MCP token has no active selection and stays pinned to the User's personal Organization. See connecting agents.

Invitations

An invitation email is the app writing to a stranger on a signed-in User's behalf, so invite-member is treated as outbound mail, not as a form. Four controls apply, all in packages/auth (invitation-policy.ts):

  • Role. Only the Organization roles owner and admin hold invitation: create; a member holds no write permission. These are Better Auth's default roles, passed explicitly in the plugin configuration so a change is a visible diff.
  • Verified inviter. The inviter's email must be verified, regardless of AUTH_SKIP_EMAIL_VERIFICATION. With the default true, an account signs in unverified and can create Organizations, but its first invitation is refused with INVITER_EMAIL_NOT_VERIFIED until the address is confirmed; the web dialog and the mobile invite group show that state and offer to send the verification email. The choice is deliberate: skipping verification is a sign-in convenience for the account holder, not a licence to send mail in their name.
  • Daily caps. Rolling 24-hour counts on the invitation table: 20 per inviter across all Organizations (INVITATION_DAILY_LIMIT_REACHED) and 50 per Organization across all inviters (ORGANIZATION_INVITATION_DAILY_LIMIT_REACHED), both HTTP 429. Better Auth's invitationLimit caps pending invitations per Organization at 50 (INVITATION_LIMIT_REACHED). Constants live in INVITATION_POLICY.
  • Rate limit. /organization/invite-member has its own customRules entry, 10 requests per 10 minutes per client IP, next to the credential endpoints.

Counting and then inserting is not atomic, so each request first takes two transaction-level advisory locks, one for the inviter and one for the Organization (reserveInvitationQuota, both in one statement in key order). It holds them until its transaction ends, the insert and the email included, so concurrent requests consume the quota one at a time and the last slot goes to exactly one of them. The pending cap is counted again under the same lock, because Better Auth reads invitationLimit before the lock is taken.

The checks run in beforeCreateInvitation, before the row is written and before any mail is sent, and again in a root hooks.before for the resend: true path, which re-sends an existing invitation without creating one. That hook runs before Better Auth has authorized the caller, so it first checks that the caller is a member of the Organization: someone outside it takes no lock and gets Better Auth's own refusal, not a quota answer. Counting runs on the handle Better Auth already holds (the auth.better-auth system scope, ADR-0009): one inviter's invitations span Organizations, so no tenant scope could see them all. The email itself never puts inviter text in the subject; see Email.

A refusal is a typed APIError; packages/errors maps each code to a message in every locale, and both clients show it through the shared mutation helper. Re-sending an existing invitation is not counted against the daily caps (the row already exists); the IP rule bounds it.

Rate limits

Better Auth rate limiting is on everywhere except Vitest. Its Postgres storage uses a separate connection and one upsert per counted request, so a rolled-back failure still counts. The hourly auth cleanup sweeps expired rows. The key is the trusted client IP (cf-connecting-ip on Workers, resolved by client-ip.ts) and the auth path.

PathLimitReason
/get-sessionExemptThe read can answer from the signed snapshot without a database statement.
/jwksExemptPublic keys; MCP loads them at most once a minute per isolate.
/sign-in/email, /sign-up/email5 per 60 secondsLimit credential guessing and account creation.
/sign-in/social10 per 60 secondsLimit provider redirects and native identity-token posts (Google, Apple).
/request-password-reset, /reset-password3 per 60 secondsLimit password reset attempts.
/native-session/exchange10 per 60 secondsLimit guesses at a native sign-in's one-time code.
/organization/invite-member10 per 600 secondsLimit outbound invitations.

Every other path uses Better Auth's defaults: 100 per 10 seconds, with 3 per 10 seconds for built-in sign-in, sign-up, password change and email change paths unless overridden above. A 429 response carries Retry-After; the handler copies Better Auth 1.7.16’s X-Retry-After value to the standard header. Rate-limit tests opt in with NODE_ENV=production.

Password reset

The reset email links to the web reset page with the one-time token in the URL fragment: <site>/reset-password#token=… (password-reset-link.ts). A browser sends a fragment to no server, so the token appears in no request URL, and Workers Logs record request URLs. The page reads the fragment after hydration, removes it from the address bar and posts the token in the body of POST /api/auth/reset-password. It reads it again on hashchange, so a newer link opened in the same tab replaces an expired one.

Better Auth's own link, GET /api/auth/reset-password/<token>?callbackURL=…, would put the token in a path the Worker receives and then in the query string of a redirect. The app never sends that link and answers the path with 404 (GET and HEAD). POST /api/auth/reset-password with a ?token= query parameter answers 400: Better Auth would read the token from there too, and the page only posts it in the body. The telemetry scrubber (packages/error-reporting/src/scrub.ts) also redacts /reset-password/<token> (the whole path segment, percent-encoded or not) and any token=, code=, verifier= or cookie= parameter in a reported text.

The link always points at the site (BETTER_AUTH_URL, or the request's own origin). The redirectTo a client sends with request-password-reset is still checked against the trusted origins, and then ignored.

request-password-reset answers the same for an address with and without an account, and the reset email is the one email the caller does not get confirmed. It is sent after the request's transaction committed and the response never waits for it: the Worker keeps the send alive through waitUntil, and a Node server, which has no waitUntil and whose process outlives the response, leaves it running. So neither the answer nor the time to answer depends on the mail transport, on either runtime. A test that needs the outcome passes its own waitUntil to createAuth and awaits the tasks it was handed. When the transport refuses the email, the server logs The password-reset email was not delivered (with the error, without the address) and deletes the token, so a link nobody received cannot be redeemed. Verification and invitation emails keep the other contract: a refused send rolls the request back and answers 502 EMAIL_SEND_FAILED.

The native app asks for a reset the same way and sends no redirectTo. A custom scheme (<NATIVE_APP_SCHEME>://) can be registered by any app on the device, so a link that redirected into it would hand the token to whichever app the system picks. The person opens the HTTPS link, chooses the new password in the browser and returns to the app to log in; the app has no reset screen. To finish the reset inside the app, give the app verified links to the site (iOS Universal Links, Android App Links) and read the token from the fragment; that needs the Apple team id and the Android signing fingerprints, which the template does not have.

Web and native

Web auth hooks coordinate TanStack Query, forms and redirects. Mobile uses the Better Auth Expo client, secure credential storage and native passkey integration. Its route gate revalidates the Session and hides private content during a transition. Logout, expiry or an authoritative 401 clears private state. A 403 does not automatically sign out an otherwise valid Session.

Every web form sets method="post" (W17), the two-factor backup code among them. The server-rendered ones (sign-in, sign-up, reset and change password) also keep submit disabled until useHydrated() is true, so a click before hydration never sends credentials in a GET URL.

Social sign-in (Google and Apple)

Sign-up and sign-in with Google and Apple ship off. A provider is registered only when every one of its variables is set (packages/env/src/social.ts); with some missing it stays off, the server logs Social sign-in with <provider> is off once per isolate, and pnpm doctor names the missing variables. Clients read which providers are on from the public appConfig.get response (auth.socialProviders, names only, never a value) and show only those buttons, on the web sign-in and sign-up pages and in the app.

VariableProviderValueSecret
GOOGLE_CLIENT_IDGoogleOAuth client ID, type Web applicationNo
GOOGLE_CLIENT_SECRETGoogleThat client's secretYes
APPLE_CLIENT_IDAppleServices ID (com.example.app.web): the web flow's client and the client secret's subNo
APPLE_TEAM_IDApple10-character Team ID: the client secret's issNo
APPLE_KEY_IDApple10-character ID of the Sign in with Apple key: the client secret's kidNo
APPLE_PRIVATE_KEYAppleThe key's .p8 content (PKCS #8 PEM); one line with \n escapes is acceptedYes
APPLE_APP_BUNDLE_IDENTIFIERAppleiOS bundle identifiers accepted as the native identity token's audience, comma-separated (com.example.app,com.example.app.dev)No

Locally, pnpm run setup offers both providers (skip them and nothing changes), reads the Apple key from the .p8 path you give, refuses half a provider, and writes the values to apps/web/.env and apps/web/.dev.vars. Without prompts: --google-client-id with GOOGLE_CLIENT_SECRET in the environment of the setup command, and --apple-client-id, --apple-team-id, --apple-key-id, --apple-key-file, --apple-bundle-ids (default: --mobile-id and its .dev variant). Secrets never go in arguments.

In production all seven are Worker secrets, never vars: PR preview Workers are generated from wrangler.jsonc and would inherit a provider without its credentials. pnpm run setup --worker-secrets publishes the complete providers' local values to the Worker named in apps/web/wrangler.jsonc with wrangler secret bulk (JSON on stdin); use it when development and production share the OAuth clients. Otherwise write the production values to a JSON file outside the repository, run the command below, and delete the file. The deploy workflows do not manage these secrets, and Worker secrets persist across deploys. A preview has none, so it shows no social buttons.

pnpm --filter web exec wrangler secret bulk social.json --name <project>-web --config wrangler.jsonc

Google

  1. Consent screen

    In the Google Cloud console, open Google Auth Platform (APIs & Services → OAuth consent screen). Set the app name, a support email and your site's domain as an authorized domain. The scopes are openid, email and profile, which need no Google verification review. While the publishing status is Testing, only the test users you list can sign in; publish the app before launch.

  2. OAuth client

    Credentials → Create credentials → OAuth client ID, type Web application. Add each origin under Authorized JavaScript origins and its callback under Authorized redirect URIs: <origin>/api/auth/callback/google, for example https://app.example.com/api/auth/callback/google and http://localhost:3005/api/auth/callback/google for development.

  3. Variables

    Copy the client ID and secret into GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.

The server shows Google's account chooser every time (prompt=select_account) and accepts only the redirect flow: an ID token posted by a client is refused (disableIdTokenSignIn). The app uses the same redirect, so the server's callback is the only redirect URI to register.

Google in the native app

The app opens the provider in the system browser, and the server's callback ends in a redirect to the app's custom scheme (<NATIVE_APP_SCHEME>://sign-in). Any installed app can register that scheme, so the redirect carries no credential. @better-auth/expo would copy the session cookie into a ?cookie= parameter of it; the nativeSessionHandoff plugin (native-session-handoff.ts) removes that parameter and returns a one-time code instead, bound to a secret only the app that started the sign-in holds (the idea of PKCE, RFC 7636):

  1. The app creates a random verifier, keeps it in memory, and asks for the callback URL <scheme>://sign-in?handoff_challenge=<SHA-256 of the verifier>.
  2. After Google's callback the server stores the hash of a new random code with the challenge and the session, for 60 seconds, and redirects to the callback URL with code=<code>.
  3. The app posts { code, verifier } to POST /api/auth/native-session/exchange over HTTPS and receives the session cookie in the response. The code is deleted on use; a wrong verifier, a used code or an expired one answers INVALID_HANDOFF_CODE.

An app that only received the redirect has the code but not the verifier. An app-scheme sign-in without a valid challenge is refused up front on /sign-in/social with NATIVE_HANDOFF_REQUIRED (and any callback reaching the scheme without one gets error=native_handoff_required, no code, and its session deleted), so the app and the server ship together. Sign in with Apple is not affected: it uses the native sheet and posts the identity token directly.

The session lives in one place, the app. The callback runs in the system browser, where Better Auth would set the session cookie; the plugin removes every cookie that response sets and keeps only the ones it clears, so the browser stays signed out and the exchange is the only response that issues the cookie. The app receives the session the callback created, not a second one: a copy would record two sign-ins for one, and would be created on a path the two-factor rule for social sign-ins does not check. A code nobody redeems leaves that session row unused until it expires; no one holds its token.

The plugin matches the sign-in callbacks @better-auth/expo copies the cookie on (/callback, /oauth2/callback for a generic OAuth provider, /magic-link/verify). As a last check the auth handler removes a cookie parameter from every redirect to a non-http(s) URL, whatever path produced it; an OAuth client's code (MCP) is left alone.

The code exchange does not stop another app from starting its own sign-in with the same scheme and showing the real Google page. Only links the operating system verifies do (iOS Universal Links, Android App Links, or an https callback in ASWebAuthenticationSession). They need the Apple team id and the Android signing certificate fingerprints, so the template does not configure them.

Apple

  1. App ID

    In Apple Developer → Certificates, Identifiers & Profiles → Identifiers, open the iOS app's App ID and enable Sign in with Apple. Enable it on the .dev App ID too if development builds sign in.

  2. Services ID

    Identifiers → + → Services IDs. Its identifier (for example com.example.app.web) is APPLE_CLIENT_ID. Enable Sign in with Apple → Configure: choose the primary App ID, add your host under Domains and Subdomains (no scheme) and <origin>/api/auth/callback/apple under Return URLs. Apple accepts only HTTPS and no localhost, so web sign-in with Apple needs a deployed or tunnelled HTTPS origin. If the portal asks you to verify the domain, put the file it offers in apps/web/public/.well-known/, deploy, and confirm with curl that the URL returns it before you verify.

  3. Key

    Keys → + → Sign in with Apple (configure it with the primary App ID). Download the .p8 (Apple offers it once): its ID is APPLE_KEY_ID, its content APPLE_PRIVATE_KEY. Your Team ID (Membership details) is APPLE_TEAM_ID.

  4. Bundle identifiers

    APPLE_APP_BUNDLE_IDENTIFIER lists the app's bundle identifier, plus <bundle id>.dev when development builds sign in against the same server.

  5. Email relay

    People who hide their address get a private relay address. Mail to it is delivered only from a registered source: Services → Sign in with Apple for Email Communication → register the domain or address of EMAIL_FROM (it must pass SPF). Otherwise the welcome, verification and password reset emails to @privaterelay.appleid.com are dropped.

Apple's client secret is not a static value: it is an ES256 JWT signed with the .p8 key and valid for at most six months. The server signs it itself with Web Crypto (workerd and Node alike), with a 30-day lifetime, keeps it in memory per isolate and signs a new one when less than a day is left, so nobody rotates it (apple-client-secret.ts). A key that cannot sign (not a PKCS #8 P-256 key) keeps Apple off and logs why; every other sign-in method keeps working. Apple returns the web flow as a cross-site POST (response_mode=form_post), so https://appleid.apple.com is a trusted origin while Apple is on.

Accounts and linking

A social sign-up goes through the same database hooks as an email sign-up, so the User ends up the same: a personal Organization with an owner membership, the user.created and org.created audit entries, auth.sign_in for the Session, and the Active Organization set on it. A password User is welcomed once the address is verified; Google and Apple verify it first, so a social sign-up is welcomed at once.

SituationResult
No User has the addressA new User, as above.
A User has the same address, verified, and the provider reports it verifiedThe provider account is linked to that User, who is signed in.
A User has the same address, not verifiedRefused with account_not_linked. An unverified address may have been typed by someone else, and with AUTH_SKIP_EMAIL_VERIFICATION=true (the default) password sign-ups stay unverified. The person signs in with email and password (or resets the password) and verifies the address from the verification email; the next Google or Apple sign-in links.
The provider reports the address unverifiedNever linked. A new User is unverified like a password sign-up; with AUTH_SKIP_EMAIL_VERIFICATION=false it gets no Session until the address is verified.
A different address, such as an Apple relay address next to a password account's real oneNever linked: a separate User.

Two-factor: Better Auth challenges only the credential sign-ins, so a User with two-factor on gets no Session from Google or Apple. The callback returns to the page with ?error=TWO_FACTOR_REQUIRED (the native sign-in answers 403 with that code) and the person signs in with email, password and code. A provider account that was linked on that attempt stays linked.

No provider is a trusted provider (which would skip the provider's email_verified), different addresses never link (allowDifferentEmails: false), and linking never overwrites the User's name or image. Provider tokens are stored encrypted (encryptOAuthTokens); the template never calls Google or Apple with them. The policy lives in social-providers.ts and the account options of index.ts.

Apple sends the person's name only the first time they authorize the app (the web form post's user field, or the native credential's full name), never in the identity token, and Google may omit it. Without a name, the address's local part stands in (profileName); for a relay address that is its random local part, which the person can change in settings. The personal Organization is named after it. A relay address (…@privaterelay.appleid.com, always verified) is stable per app and person, so it signs in every time like any other address.

Mobile

  • Apple, iOS only: the native sheet (expo-apple-authentication, ios.usesAppleSignIn in the app config). The app creates a random nonce, gives Apple its SHA-256 and sends the raw nonce with the identity token (signIn.social({ provider: "apple", idToken: { token, nonce } })). Better Auth checks Apple's signature, the audience (APPLE_APP_BUNDLE_IDENTIFIER) and that the token's nonce is the SHA-256 of the raw one. The server refuses an Apple identity token without a nonce (ID_TOKEN_NONCE_REQUIRED), so a captured token cannot be replayed. On the first sign-in the app sends the name Apple returned.
  • Google: the @better-auth/expo browser flow, with no native module and no extra client ID. The system browser goes to Google, then to the server's /api/auth/callback/google, and back to the app through its scheme (<NATIVE_APP_SCHEME>://, -dev for development builds), which the server trusts as a native origin.
  • App Store guideline 4.8: on iOS the Google button appears only when Sign in with Apple is offered as well, and Apple comes first (visibleSocialProviders in apps/mobile/src/features/auth/auth.social.ts). Android never shows Apple.
  • Limits: Expo Go cannot sign in with Apple (its identity token's audience is Expo Go's bundle identifier, not yours); use a development build. Google from a physical device needs an origin Google accepts as a redirect URI (HTTPS, or localhost on the simulator), so use a tunnel or a preview URL. On iOS a refused Google sign-in (for example account_not_linked) currently looks like a cancel, because the Expo plugin reads only the cookie from the browser result; Android shows the error.
  • expo-apple-authentication and expo-crypto are native modules: rebuild the development client after pulling the change that added them.

Extend safely

Add auth behavior to the server factory and its tests, then expose the outcome through a hook. Keep email callbacks, membership checks and audit recording in their existing owners. Test revoked Sessions and Organization changes as well as successful login. Never treat an impersonated admin's original identity as permission to access /admin.

Key files

Edit on GitHubDocumentation is in English.
Cookie settings
We use essential cookies to make our app work. With your consent, we also use optional cookies to improve your experience.

Read our Cookie Policy and Privacy Policy.