Skip to main content
Learn how to set up user authentication in Sonamu. Sonamu provides an integrated authentication system based on better-auth.

Authentication System Overview

better-auth Integration

Proven authentication libraryEmail/password, Social login

Auto Entity Generation

Generate entities via CLIUser, Session, Account, Verification

Context Based

User info per requestSonamu.getContext()

Guards System

Declarative permission control@api guards option

Quick Start

1. Generate Auth Entities

Automatically generate entities required by better-auth:
This command generates 4 entities:
If entities already exist, only missing fields are added. Fields with changed types are automatically updated.

2. Run Migrations

After generating entities, run migrations:

3. Configure Authentication

Enable authentication in sonamu.config.ts:
This enables basic email/password authentication.

API Endpoints

API endpoints provided by better-auth are automatically registered:

Accessing User Info in Context

Access authenticated user information through Context:

AuthContext Type

User and Session types are provided by better-auth.

Access Control with Guards

Basic Guard Usage

Implementing guardHandler

Guard logic is implemented in guardHandler in sonamu.config.ts:

Social Login Setup

Google Login

GitHub Login

Adding User Roles

The default User entity in better-auth doesn’t have a role field. If you need role-based authentication, add it directly to the User entity:

1. Add Field in Sonamu UI

Add role field to User entity:
  • Name: role
  • Type: string
  • Default: "user"

2. Add Enum (Optional)

3. Check Role in guardHandler

Client Integration

Using in React

Field Mapping

better-auth uses camelCase, but Sonamu uses snake_case. The following fields are automatically mapped:

Checklist

Things to verify after setting up authentication:
  • Run pnpm sonamu auth generate
  • Generate and apply migrations
  • Configure server.auth in sonamu.config.ts
  • Implement guardHandler
  • Verify user/session access in Context
  • Add role to User entity if role-based auth is needed

Next Steps

Session Management

Managing sessions and tokens

Context

Learn more about Context

@api Decorator

API decorator options

Error Handling

Handling authentication errors