Skip to main content
AuthContext is part of Context, providing user authentication state and session information. It is implemented based on better-auth.

Type Definition

Properties

user

Information about the currently authenticated user. null if not logged in. The User type is provided by better-auth and includes the following fields by default:
Usage example:

session

Current session information. null if not logged in. The Session type is provided by better-auth and includes the following fields:
Usage example:

Configuration

To use AuthContext, you need to configure authentication in sonamu.config.ts.

Basic Configuration

Adding Social Login

Access Control with Guards

To require authentication for API methods, you can use the guards option:
Guard handling logic is implemented in guardHandler:
guardHandler runs inside AsyncLocalStorage, so you can access the current request’s Context via Sonamu.getContext().

Extending User Type

If you’ve added fields to the User entity in your project, you can modify the entity through Sonamu UI. Added fields are accessible on the user object, but type assertions are required for TypeScript type safety:

Authentication Flow

  1. Client sends login request to /api/auth/sign-in/email
  2. better-auth handles authentication and creates session
  3. Session token is stored in cookie
  4. Subsequent requests identify user via cookie token
  5. user/session is injected into Context before API method execution
  6. Access user info via Sonamu.getContext()