Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Better Auth API reference

Better Auth authentication

Identifiers
103
With full guides
89
Types
6

Topics covered

  • Setup
  • Email & password
  • Social providers
  • Sessions
  • Plugins
  • Two-factor auth
  • Organizations
  • Database adapters

Function

NameWhat it does
betterAuthFunction
createAuthClientcreateAuthClient initializes a Better Auth client for calling an authentication server. Configure its server URL when needed, then use the returned APIs for authentication and extend them with plugins.
signOutSigns out the current user through Better Auth’s client API. Optional fetch options can run logic such as redirecting to the login page after successful sign-out.
getSessiongetSession retrieves the currently active Better Auth session. On the client it is called through authClient; on the server, use auth.api.getSession with request headers.
twoFactorBetter Auth’s twoFactor plugin adds TOTP and OTP second-factor authentication, along with backup codes and trusted-device support. Register it in the server auth configuration and set an issuer for TOTP enrollment.
organizationFunction
adminadmin() enables Better Auth's Admin plugin for administrative user management. Add it to the server configuration, then apply the required schema and configure the client plugin when client-side admin operations are needed.
nextCookiesnextCookies is a Better Auth plugin for Next.js server actions. It automatically applies authentication cookies emitted through Set-Cookie response headers.
passkeyBetter Auth's passkey plugin enables passwordless WebAuthn authentication using device-stored credentials. Configure the plugin, update the database schema, and use client methods to register, sign in with, or manage passkeys.
magicLinkmagicLink adds passwordless email-link authentication to Better Auth. Configure a sendMagicLink callback to deliver the generated URL, then users can authenticate by following it.
emailOTPBetter Auth’s Email OTP plugin enables email-code sign-in, email verification, and password resets. Configure a delivery callback, then use the client plugin to request and consume OTPs.
apiKeyapiKey() adds Better Auth's API Key plugin. It supports API-key creation, management, verification, authentication, and configurable operational policies.
bearerThe Bearer plugin authenticates API requests with bearer tokens instead of browser cookies. It supports automatic or per-request token attachment and server-side session retrieval.
jwtBetter Auth's JWT plugin issues JWTs for external services and exposes JWKS verification keys. It complements, rather than replaces, the normal Better Auth session.
multiSessionBetter Auth's multi-session plugin keeps multiple account sessions active in one browser. It provides client operations for listing sessions, switching the active session, and revoking sessions.
customSessionFunction
toNextJsHandlertoNextJsHandler adapts a configured Better Auth instance for Next.js App Router route handlers. Export the returned HTTP methods from the authentication catch-all route.

Hook

NameWhat it does
useSessionHook

Type Alias

NameWhat it does
BetterAuthOptionsBetterAuthOptions describes the configuration object used to create a Better Auth instance. It covers application identity, URLs, databases, authentication features, secrets, and plugins.
SessionSession is Better Auth's inferred TypeScript type for the current session response. It includes both the session object and its associated user object, with configured extensions reflected in the type.
UserBetter Auth’s User type is the inferred shape of an authenticated user object. Plugins and configured additional fields can extend it, with the resulting type available across server and client code.
AccountType Alias
AuthType Alias
BetterAuthPluginBetterAuthPlugin is the contract for defining a Better Auth server plugin. Its only required property is a unique id; optional plugin features can add endpoints, schemas, hooks, middleware, and other behavior.
AuthContextType Alias
InferSessionInferSession is Better Auth’s inferred session type, derived through $Infer from a client or server auth instance. It includes both the session and user portions and incorporates supported configured or plugin-provided fields.
InferUserType Alias

Const

NameWhat it does
signInBetter Auth’s signIn client API supports email/password authentication through signIn.email and social authentication through signIn.social. Email sign-in accepts credentials plus optional session persistence and redirect settings.
signUpsignUp exposes the client’s email-registration method as authClient.signUp.email. It creates a user from the supplied name, email, password, and optional image, then signs the user in automatically by default.
usernameThe username plugin adds username-based authentication to Better Auth’s email/password flow. It supports username signup, login, updates, availability checks, validation, length limits, and normalization.
anonymousThe anonymous identifier is a non-reversible hash derived from the project’s package.json name and optionally its baseURL. Better Auth uses it to de-duplicate telemetry events per project without identifying users.
phoneNumberphoneNumber is Better Auth’s server plugin for phone-number authentication. It supports OTP verification and can enable phone-based sign-up and password sign-in flows.
genericOAuthgenericOAuth registers custom OAuth 2.0 or OIDC providers in Better Auth. It supports provider-specific discovery, endpoints, profile mapping, and the standard social sign-in flow.
oneTapThe oneTap constant is Better Auth’s server plugin for Google One Tap sign-in. Configure it in betterAuth with a Google client ID and pair it with the client-side oneTapClient plugin.
oAuthProxyOAuth Proxy lets trusted local and preview deployments use one OAuth client with a fixed production callback URL. It routes their OAuth flows through the production callback server.
openAPIThe openAPI plugin adds a Scalar-based OpenAPI reference for Better Auth, covering core and plugin endpoints. It also exposes the generated schema programmatically.
oidcProvideroidcProvider configures Better Auth as an OpenID Connect provider that other services can use for authentication. Add it to betterAuth, update the schema, and configure client registration as needed.
ssoThe Better Auth SSO plugin adds OIDC and SAML single sign-on support. Enable it with sso(), then register identity providers with their required configuration.
captchaThe Better Auth captcha plugin adds bot protection to selected authentication endpoints. It supports several CAPTCHA providers and validates submitted tokens server-side.
haveIBeenPwnedThe haveIBeenPwned plugin blocks passwords found in known data breaches. It uses the Have I Been Pwned API with a privacy-preserving hash-prefix lookup.
deviceAuthorizationdeviceAuthorization enables RFC 8628 device authorization for limited-input clients. Devices obtain codes, users approve them in a browser, and devices poll for a session or OAuth token.
lastLoginMethodConst
drizzleAdapterdrizzleAdapter connects Better Auth to a configured Drizzle ORM database. Pass the database instance and its provider, such as sqlite, pg, or mysql.
prismaAdapterprismaAdapter connects Better Auth to Prisma by wrapping an initialized Prisma Client. Configure it as the auth database adapter and specify the matching database provider.
mongodbAdaptermongodbAdapter configures Better Auth to use MongoDB as its database. Supply a MongoClient when the deployment supports transactions.
kyselyAdapterConst
memoryAdapterConst
googlegoogle is Better Auth’s provider identifier for Google social authentication. Use it in the provider configuration and in social sign-in requests.
githubBetter Auth's GitHub provider connects OAuth sign-in to a GitHub application. Configure client credentials under socialProviders.github, then invoke signIn.social with provider set to github.
appleapple is the Better Auth social-provider identifier for Sign in with Apple. Configure Apple credentials under socialProviders.apple, allow Apple's trusted origin, and invoke the flow with signIn.social({ provider: "apple" }).
discorddiscord is Better Auth's provider identifier for Discord OAuth. Configure it under socialProviders with Discord credentials, then pass it as the provider value to signIn.social.
facebookBetter Auth's Facebook provider uses Facebook OAuth credentials configured under socialProviders. Start the client flow with signIn.social({ provider: "facebook" }).
microsoftThe microsoft provider enables Microsoft Azure Entra ID OAuth sign-in and sign-up in Better Auth. Configure it under socialProviders.microsoft with an application client ID and an appropriate confidential-client credential.
twitchBetter Auth’s Twitch provider enables OAuth sign-in by configuring Twitch credentials under socialProviders.twitch. Clients start the flow with signIn.social({ provider: "twitch" }).
gitlabBetter Auth's GitLab provider enables OAuth sign-in through GitLab.com or a self-hosted GitLab instance. Configure credentials under socialProviders.gitlab, then invoke signIn.social with provider: "gitlab".
linkedinBetter Auth's LinkedIn provider enables OAuth/OpenID Connect sign-in using LinkedIn application credentials. Configure it under socialProviders.linkedin, then call signIn.social with provider: "linkedin".
spotifyBetter Auth’s Spotify provider enables OAuth sign-in by configuring Spotify client credentials under socialProviders.spotify, then calling signIn.social with provider: "spotify". Local development must use 127.0.0.1 instead of localhost for the redirect URI.
dropboxDropbox sign-in is configured as a Better Auth social provider with a Dropbox client ID and client secret. Clients start the flow with signIn.social({ provider: "dropbox" }).
kickKick is configured as a Better Auth social provider with a client ID and client secret. Clients begin authentication with signIn.social({ provider: "kick" }).
redditreddit is Better Auth’s provider identifier for Reddit OAuth sign-in. Configure Reddit credentials under socialProviders.reddit, then pass provider: "reddit" to signIn.social.
robloxBetter Auth's Roblox provider enables Roblox OAuth sign-in through socialProviders. Configure Roblox credentials, use the documented callback URL, and start login with signIn.social({ provider: "roblox" }).
zoomBetter Auth’s Zoom provider enables OAuth sign-in through a Zoom app. Configure the app credentials under socialProviders.zoom, then start authentication with signIn.social({ provider: "zoom" }).
tiktokBetter Auth's tiktok provider enables TikTok OAuth sign-in. Configure it with TikTok's client key and secret, then call signIn.social({ provider: "tiktok" }).

Module

NameWhat it does
signIn.emailsignIn.email authenticates a user through Better Auth’s client using a required email and password. Optional rememberMe and callbackURL fields control session persistence and the post-sign-in redirect.
signIn.socialsignIn.social starts client-side OAuth sign-in for a configured social provider. Pass the provider ID and optionally a redirect URL or extra authorization parameters.
signIn.phoneNumbersignIn.phoneNumber authenticates an existing Better Auth user with a phone number and password. It accepts rememberMe to control session persistence.
signIn.passkeysignIn.passkey starts a Better Auth passkey sign-in flow through WebAuthn. It supports browser autofill, optional WebAuthn extensions, and returning WebAuthn response details.
signIn.magicLinksignIn.magicLink starts passwordless authentication by requesting a magic link for an email address. After the recipient follows the link, Better Auth authenticates them and redirects according to the request options.
signIn.emailOtpsignIn.emailOtp() signs a user in with an email address and the one-time password sent to it. It is part of Better Auth's Email OTP plugin and supports optional first-registration profile fields.
signUp.emailCreates a Better Auth account using a required name, email, and password, with optional profile image and post-signup callback URL. Email-and-password authentication must be enabled first.
updateUserBetter Auth's client exposes updateUser for changing user information. Supply the desired profile fields in an object, such as image and name.
changeEmailBetter Auth’s changeEmail feature lets a user request a new email address. Enable it server-side, configure verification delivery, and start the flow with the client’s changeEmail method.
changePasswordChanges the authenticated user's password using the current password and a new password. It can optionally invalidate the user's other active sessions.
deleteUserauthClient.deleteUser permanently deletes the authenticated user's data. Enable user.deleteUser first, then authorize the request with a valid password or a recently authenticated session.
forgetPasswordBetter Auth password recovery sends a token-bearing reset link through a configured email callback. The user follows the link and submits a new password on the reset page.
resetPasswordresetPassword completes Better Auth’s email/password recovery flow. After the user receives a token-bearing reset link, call it with the token and the replacement password.
verifyEmailverifyEmail completes manual email verification from a token in a custom verification link. Calling it with the token lets Better Auth verify the user's email.
sendVerificationEmailsendVerificationEmail is the Better Auth callback used to deliver an email-verification link. Configure it under emailVerification; Better Auth provides the recipient, URL, token, and request context.
listSessionsModule
revokeSessionrevokeSession manually ends a specific Better Auth session by using its session token. It is useful for terminating a session from a signed-in device other than the one currently in use.
linkSocialauthClient.linkSocial links an additional social or OAuth provider to the signed-in user's existing Better Auth account. It can redirect through OAuth, request extra scopes, or use provider ID tokens directly.
unlinkAccountunlinkAccount removes one authentication method from the current user. Select the account with listAccounts, then pass its local record ID as accountId; the last account is protected by default.
listAccountslistAccounts retrieves every authentication method linked to the current user. Retain each returned account's id for unlinking or other account-specific operations.
auth.api.getSessionauth.api.getSession retrieves the current server-side session by receiving the incoming request headers. Use its result to access session data or reject unauthenticated requests.
auth.api.signInEmailSigns a user in on the server with an email and password. Optional settings control session persistence and the post-sign-in redirect.
auth.api.signUpEmailCreates a user with email and password through Better Auth's server API. Supply required identity and credential fields, with optional image and callback URL values.
auth.handlerauth.handler is Better Auth's Web Standard request handler. Mount it on a catch-all route matching the configured auth base path and pass the incoming Request to receive a Response.
auth.api.listUsersLists users through the Better Auth admin API, with optional search, pagination, sorting, and filtering. The server-side endpoint requires authenticated session cookies.

Pipe

NameWhat it does
databaseConfigure Better Auth with a supported database connection or adapter so it can persist users, sessions, and other authentication data. Omitting the database enables stateless operation, but most plugins require database storage.
emailAndPasswordBetter Auth’s built-in email/password authenticator supports registration, login, email verification, and password recovery. Enable it in the server configuration and provide email callbacks for verification or reset flows.
socialProviderssocialProviders configures social login providers in Better Auth. Each provider entry supplies OAuth credentials and can optionally customize redirects, scopes, and profile mapping.
pluginsBetter Auth plugins extend the framework with authentication features and custom behavior. Register server plugins in the auth configuration and client plugins when creating the client.
sessionBetter Auth uses cookie-based sessions: the server validates the session cookie on requests and returns the associated user when valid. Session expiration, freshness, storage, and management APIs are configurable.
userPipe
accountAn account is Better Auth’s record for an authentication method connected to a user. Account records support multiple providers, account listing, linking, unlinking, and account-specific provider operations.
advancedPipe
trustedOriginstrustedOrigins defines additional origins that Better Auth accepts during request validation. It supports exact origins, wildcard patterns, and dynamic functions, while the app's baseURL is trusted by default.
secretsecret configures the value Better Auth uses for encryption, signing, and hashing. It can be set explicitly or supplied through BETTER_AUTH_SECRET or AUTH_SECRET.
baseURLbaseURL sets Better Auth’s server origin. Configure it as a URL string for one domain or as an object for validated, per-request resolution across multiple hosts.
rateLimitBetter Auth provides a built-in limiter for client-initiated requests. Configure its window, request ceiling, storage, and path-specific rules through betterAuth's rateLimit option.
hooksBetter Auth hooks let you run custom middleware before or after an auth endpoint. They support request and response customization, validation, cookies, errors, auth context access, and background work.
databaseHooksBetter Auth databaseHooks provide before and after callbacks around core database operations. Use them to transform records before persistence or run follow-up logic after an operation completes.
onAPIErroronAPIError configures how Better Auth handles API failures. It can throw errors, invoke custom handling, redirect to an error URL, and customize the default error page.

Search across every package and filter by type in your dashboard.

Start learning