AuthContext is part of Context, providing user authentication state and session information. It is implemented based on better-auth.
Type Definition
import type { Session, User } from "better-auth";type AuthContext = { /** Currently logged in user (null if unauthenticated) */ user: User | null; /** Current session info (null if unauthenticated) */ session: Session | null;};
Properties
user
user: User | null;
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:
type User = { id: string; name: string; email: string; emailVerified: boolean; image: string | null; createdAt: Date; updatedAt: Date;};
To require authentication for API methods, you can use the guards option:
class UserModelClass extends BaseModelClass { @api({ httpMethod: "GET", guards: ["user"] }) async getMyData() { const { user } = Sonamu.getContext(); // guards: ["user"] guarantees user is not null return this.findById("A", user!.id); } @api({ httpMethod: "GET", guards: ["admin"] }) async getAllUsers() { // guards: ["admin"] allows only admins return this.findMany("A", {}); }}
Guard handling logic is implemented in guardHandler:
// sonamu.config.tsimport { Sonamu } from "sonamu";export default { server: { apiConfig: { guardHandler: (guard, request, api) => { const { user } = Sonamu.getContext(); if (guard === "user" && !user) { throw new UnauthorizedException("Login required"); } if (guard === "admin") { if (!user || (user as any).role !== "admin") { throw new UnauthorizedException("Admin permission required"); } } return true; }, }, },} satisfies SonamuConfig;
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:
const { user } = Sonamu.getContext();// If you added a role fieldconst userRole = (user as any).role;// Or use type guardsinterface ExtendedUser extends User { role: "admin" | "user" | "manager";}function isExtendedUser(user: User | null): user is ExtendedUser { return user !== null && "role" in user;}if (isExtendedUser(user)) { console.log(user.role); // Type-safe}
Authentication Flow
Client sends login request to /api/auth/sign-in/email
better-auth handles authentication and creates session
Session token is stored in cookie
Subsequent requests identify user via cookie token
user/session is injected into Context before API method execution