Skip to main content
Sonamu provides an authentication system based on better-auth. It supports various authentication methods including email/password authentication and social login, with authentication APIs automatically registered at /api/auth/*.

Basic Structure

auth Settings

Type

Type: BetterAuthOptions (configuration type from better-auth library)

secret (required)

secret is the signing key for session cookies, email verification tokens, and the JWT plugin’s key encryption. Anyone who knows it can forge sessions and tokens for any user, so generate a random value for each environment and never commit it.
.env.production
better-auth looks up the secret in auth.secret, then BETTER_AUTH_SECRET, then AUTH_SECRET. To rotate keys, use the secrets option or BETTER_AUTH_SECRETS (<version>:<value>,...).
Without a secret, better-auth signs with a default constant published in its source and rejects it only when NODE_ENV=production. Sonamu therefore refuses to start the server in every environment except test (development, staging, and production) when the secret is missing or a publicly known value. If you have run with a public value, rotate the secret and revoke existing sessions. The check also covers the keys in secrets or BETTER_AUTH_SECRETS and the legacy secret kept for decrypting existing data, so a public legacy key left in your rotation settings also blocks startup.

Email/Password Authentication

Social Login (Google)

Social Login (GitHub)

Customizing basePath

The default path is /api/auth. To change it:

baseURL

Password reset links, email verification links, and trustedOrigins are built from the baseURL. Clients control the request Host header, so Sonamu always takes the baseURL from configuration:
  1. server.auth.baseURL
  2. better-auth environment variables (BETTER_AUTH_URL and others)
  3. The origin of server.baseUrl plus basePath (when it is an absolute http(s) URL)
  4. Locally only (development, test): http://{listen.host}:{listen.port} plus basePath, with a warning
In staging or production, the server refuses to start when none of 1-3 is set.

Entity Generation

You need to generate the required entities before using better-auth.

Generate Entities via CLI

This command generates the following entities:
If a User entity already exists, only missing fields will be added when running the command.
The default subset A of credential entities leaves out secret fields such as session tokens, password hashes, and OAuth tokens. Existing subsets are not changed, so review them yourself.

Generate Entities with Plugins

To use better-auth plugins, specify the required plugins with the --plugins option:
Supported plugins:
When using plugins, you also need to enable them in sonamu.config.ts. See the Plugin Configuration section below for details.

Field Mapping

Since Sonamu uses snake_case column names, better-auth’s camelCase field names are automatically mapped:

Authentication APIs

Once better-auth is registered, the following APIs become automatically available:

Sign Up

Sign In

Sign Out

Current Session

Social Login (Google)

For the complete API list, refer to the better-auth documentation.

Accessing User Information from Context

In authenticated requests, you can access user information through Context.

User Type

Session Type

Access Control with Guards

guardHandler configuration:

Client-Side Integration

Using with React

Plugin Configuration

To use better-auth plugins, add them to the auth.plugins array in sonamu.config.ts.
Before configuring plugins, you must first generate the required entities and fields using pnpm sonamu auth generate --plugins=....

Two-Factor Authentication (2FA)

Enable TOTP-based two-factor authentication:
2FA-related APIs:
  • POST /api/auth/two-factor/enable - Start 2FA setup
  • POST /api/auth/two-factor/verify-totp - Verify an authenticator app (TOTP) code
  • POST /api/auth/two-factor/disable - Disable 2FA
Users with 2FA enabled cannot get a new login session from an email verification or change-email link. Sonamu immediately removes sessions newly issued by /api/auth/verify-email (including autoSignInAfterVerification) from the cookie and the database. The verification or email change still takes effect; users sign in through the normal flow, which requires 2FA.

Admin Plugin

Supports user roles, banning, and impersonation:
Fields added to User table by Admin plugin:
  • role - User role (default: β€œuser”)
  • banned - Ban status
  • ban_reason - Ban reason
  • ban_expires - Ban expiration time (Unix timestamp)

Username Plugin

Allows login with username instead of email:
Fields added to User table by Username plugin:
  • username - Normalized username (lowercase, unique index)
  • display_username - Display username (preserves original case)

Phone Number Plugin

Supports phone number verification:
Fields added to User table by Phone Number plugin:
  • phone_number - Phone number (unique index)
  • phone_number_verified - Phone number verification status

Passkey Plugin

Supports WebAuthn/FIDO2 based passkey authentication:
Tables created by Passkey plugin:
  • passkeys - User passkey information (public key, credential ID, etc.)
Passkey-related APIs:
  • POST /api/auth/passkey/generate-register-options - Generate passkey registration options
  • POST /api/auth/passkey/verify-registration - Verify passkey registration
  • POST /api/auth/passkey/generate-authentication-options - Generate passkey authentication options
  • POST /api/auth/passkey/verify-authentication - Verify passkey authentication
The @better-auth/passkey package is required to use the Passkey plugin.

SSO Plugin

Supports SSO login through external IdPs (OIDC, SAML):
Tables created by SSO plugin:
  • sso_providers - SSO provider settings (including OIDC/SAML configuration)
The @better-auth/sso package is required to use the SSO plugin.

API Key Plugin

Supports API key based authentication:
Tables created by API Key plugin:
  • api_keys - API key information (hashed key, rate limit settings, etc.)
API Key-related APIs:
  • POST /api/auth/api-key/create - Create API key
  • POST /api/auth/api-key/revoke - Revoke API key
  • GET /api/auth/api-key/list - List API keys

JWT Plugin

Supports JWT token issuance and JWKS key management:
Tables created by JWT plugin:
  • jwks - JSON Web Key Set information (public key, private key)
JWT-related APIs:
  • GET /api/auth/.well-known/jwks.json - JWKS endpoint
  • POST /api/auth/jwt/generate - Generate JWT token

Organization Plugin

Supports organization, member, invitation, and team management:
Tables created by Organization plugin:
  • organizations - Organization information
  • members - Organization members
  • invitations - Organization invitations
  • teams - Teams
  • team_members - Team members
Fields added to Session table by Organization plugin:
  • active_organization_id - Current active organization ID
  • active_team_id - Current active team ID
Organization-related APIs:
  • POST /api/auth/organization/create - Create organization
  • POST /api/auth/organization/invite - Invite member
  • POST /api/auth/organization/accept-invitation - Accept invitation
  • POST /api/auth/organization/set-active - Set active organization

Anonymous Plugin

Supports anonymous user authentication. Allows creating temporary users without sign-up:
Fields added to User table by Anonymous plugin:
  • is_anonymous - Whether the user is anonymous
Anonymous-related APIs:
  • POST /api/auth/sign-in/anonymous - Anonymous login
  • POST /api/auth/anonymous/link - Link anonymous account to a regular account

Using Multiple Plugins Together

Each plugin’s schema (*_SCHEMA) maps Sonamu’s snake_case column names to better-auth’s camelCase field names. It must be passed along with the corresponding plugin.

Practical Examples

Basic Configuration

Social Login + Email Verification

Important Notes

1. Entity Generation Required

2. Environment Variables Setup

3. CORS Configuration

When the client runs on a different domain:

4. Compatibility with Existing User Entity

If a User entity already exists, running pnpm sonamu auth generate will only add missing fields. Existing data is preserved.

Next Steps

After completing authentication setup:
  • Context - Accessing user information from Context
  • Guards - API access control