Sign in

    #mizchi/npm_typed/better_auth

    MoonBit FFI bindings for better-auth - Authentication library for TypeScript.

    #Installation

    moon add mizchi/js moon add mizchi/npm_typed npm install better-auth

    Add to your moon.pkg:

    import { "mizchi/js", "mizchi/js_core" @core, "mizchi/npm_typed/better_auth", }

    #Documentation

    • Official docs: https://www.better-auth.com/
    • SQLite adapter: https://www.better-auth.com/docs/adapters/sqlite

    #Database Setup

    Before using better-auth, you need to generate and run database migrations:

    # Generate migration files npx @better-auth/cli@latest generate # Apply migrations to database npx @better-auth/cli@latest migrate

    #Example Usage

    let db = @sqlite.DatabaseSync::new("app.db")
    let auth = @better_auth.betterAuth(
    database=db |> @js.identity,
    providers=[@better_auth.EmailPassword::{ enabled: true }],
    secret="your-secret-key",
    )

    // Sign up
    let response = auth.api().signUpEmail(
    name="John Doe",
    email="john@example.com",
    password="password123",
    )
    if not(response.hasError()) {
    let user = response.user()
    let token = response.token()
    // Set cookie: better-auth.session_token=token
    }

    // Sign in
    let response = auth.api().signInEmail(
    email="john@example.com",
    password="password123",
    )
    if not(response.hasError()) {
    let token = response.token()
    // Set cookie: better-auth.session_token=token
    }

    // Get session
    let session = auth.api().getSession(headers)
    match session {
    Some(s) => {
    let user = s.user()
    let session = s.session()
    }
    None => {
    // Not authenticated
    }
    }

    #API Response Structure

    • signUpEmail / signInEmail returns { token, user } on success, { error } on failure
    • getSession returns { session, user } if authenticated, null otherwise

    #See Also

    • Full example: src/examples/realworld/ - TODO app with authentication

    Provider

    pub trait Provider {
    fn apply(Self,
    Any
    ) -> Unit
    }

    Provider trait - abstraction for auth providers

    Auth

    #external
    pub type Auth

    Auth instance

    Auth::api

    fn Auth::api(self : Auth) -> AuthApi

    Get the API from auth instance

    Auth::handler

    fn Auth::handler(self : Auth) ->
    Any

    Auth handler for HTTP frameworks

    Auth::to_any

    fn Auth::to_any(self : Auth) ->
    Any

    AuthApi

    #external
    pub type AuthApi

    Auth API - server-side methods

    AuthApi::getSession

    async fn AuthApi::getSession(self : AuthApi, headers :
    Any
    ) -> SessionResponse?

    Get session from request headers Returns SessionResponse with { session, user } if authenticated, or null

    AuthApi::signInEmail

    async fn AuthApi::signInEmail(self : AuthApi, email~ : String, password~ : String, remember_me? : Bool, callback_url? : String, headers? :
    Any
    ) -> AuthResponse

    Sign in with email

    AuthApi::signInSocial

    async fn AuthApi::signInSocial(self : AuthApi, provider~ : String, callback_url? : String) ->
    Any

    Sign in with social provider (returns redirect URL)

    AuthApi::signOut

    async fn AuthApi::signOut(self : AuthApi, headers :
    Any
    ) -> Unit

    Sign out

    AuthApi::signUpEmail

    async fn AuthApi::signUpEmail(self : AuthApi, name~ : String, email~ : String, password~ : String, image? : String, callback_url? : String) -> AuthResponse

    Sign up with email

    AuthApi::to_any

    fn AuthApi::to_any(self : AuthApi) ->
    Any

    AuthClient

    #external
    pub type AuthClient

    Auth client instance

    AuthClient::getSession

    async fn AuthClient::getSession(self : AuthClient) ->
    Any

    Get current session

    AuthClient::signIn

    fn AuthClient::signIn(self : AuthClient) -> SignInClient

    Get signIn methods from client

    AuthClient::signOut

    async fn AuthClient::signOut(self : AuthClient) -> Unit

    Sign out (client-side)

    AuthClient::signUp

    fn AuthClient::signUp(self : AuthClient) -> SignUpClient

    Get signUp methods from client

    AuthClient::to_any

    AuthResponse

    #external
    pub type AuthResponse

    Auth response from signUpEmail/signInEmail API Returns { token, user } on success, or { error } on failure

    AuthResponse::error

    Get error from response if present

    AuthResponse::errorMessage

    fn AuthResponse::errorMessage(self : AuthResponse) -> String?

    Get error message from response if present

    AuthResponse::hasError

    fn AuthResponse::hasError(self : AuthResponse) -> Bool

    Check if response has error

    AuthResponse::to_any

    AuthResponse::token

    fn AuthResponse::token(self : AuthResponse) -> String

    Get session token from response (for cookie setting) Note: signInEmail returns token directly, not nested in session

    AuthResponse::user

    fn AuthResponse::user(self : AuthResponse) -> User

    Get user from response

    EmailPassword

    pub(all) struct EmailPassword {
    enabled : Bool
    }

    Email and password provider

    GitHub

    pub(all) struct GitHub {
    client_id : String
    client_secret : String
    }

    GitHub OAuth provider
    impl Provider for GitHub

    Google

    pub(all) struct Google {
    client_id : String
    client_secret : String
    }

    Google OAuth provider
    impl Provider for Google

    Session

    #external
    pub type Session

    Session type stored in database

    Session::expiresAt

    fn Session::expiresAt(self : Session) -> String

    Get session expiresAt

    Session::id

    fn Session::id(self : Session) -> String

    Get session id

    Session::ipAddress

    fn Session::ipAddress(self : Session) -> String?

    Get session ipAddress

    Session::to_any

    fn Session::to_any(self : Session) ->
    Any

    Session::token

    fn Session::token(self : Session) -> String

    Get session token

    Session::userAgent

    fn Session::userAgent(self : Session) -> String?

    Get session userAgent

    Session::userId

    fn Session::userId(self : Session) -> String

    Get session userId

    SessionResponse

    #external
    pub type SessionResponse

    Session response from getSession API Returns { session, user } on success, or null if not authenticated

    SessionResponse::session

    fn SessionResponse::session(self : SessionResponse) -> Session

    Get session from response

    SessionResponse::to_any

    SessionResponse::user

    Get user from response

    SignInClient

    #external
    pub type SignInClient

    Sign in namespace

    SignInClient::email

    async fn SignInClient::email(self : SignInClient, email~ : String, password~ : String, remember_me? : Bool, callback_url? : String) -> AuthResponse

    Sign in with email (client-side)

    SignInClient::social

    async fn SignInClient::social(self : SignInClient, provider~ : String, callback_url? : String) ->
    Any

    Sign in with social provider (client-side) provider: "github" | "google"

    SignInClient::to_any

    SignUpClient

    #external
    pub type SignUpClient

    Sign up namespace

    SignUpClient::email

    async fn SignUpClient::email(self : SignUpClient, name~ : String, email~ : String, password~ : String, image? : String, callback_url? : String) -> AuthResponse

    Sign up with email (client-side)

    SignUpClient::to_any

    UseSessionResult

    #external
    pub type UseSessionResult

    useSession hook result

    UseSessionResult::data

    Get session data

    UseSessionResult::error

    Get error if any

    UseSessionResult::isPending

    fn UseSessionResult::isPending(self : UseSessionResult) -> Bool

    Check if session is pending

    UseSessionResult::to_any

    User

    #external
    pub type User

    User type returned from better-auth API

    User::createdAt

    fn User::createdAt(self : User) -> String

    Get user createdAt

    User::email

    fn User::email(self : User) -> String

    Get user email

    User::emailVerified

    fn User::emailVerified(self : User) -> Bool

    Get user emailVerified

    User::id

    fn User::id(self : User) -> String

    Get user id

    User::image

    fn User::image(self : User) -> String?

    Get user image

    User::name

    fn User::name(self : User) -> String?

    Get user name

    User::to_any

    fn User::to_any(self : User) ->
    Any

    User::updatedAt

    fn User::updatedAt(self : User) -> String

    Get user updatedAt

    betterAuth

    fn betterAuth(database~ :
    Any
    , providers~ : Array[&Provider], base_url? : String, secret? : String) -> Auth

    Create a new Auth instance with providers

    createAuthClient

    fn createAuthClient(base_url~ : String) -> AuthClient

    Create a new auth client