### Install Onboarding Plugin Package Source: https://context7_llms Install the @better-auth-extended/onboarding package using npm, pnpm, yarn, or bun. This command adds the necessary files for the plugin to your project's dependencies. ```bash npm install @better-auth-extended/onboarding ``` ```bash pnpm add @better-auth-extended/onboarding ``` ```bash yarn add @better-auth-extended/onboarding ``` ```bash bun add @better-auth-extended/onboarding ``` -------------------------------- ### Install Better Auth CLI Source: https://context7_llms Instructions for installing the Better Auth CLI using npm, yarn, or bun. This command downloads and runs the CLI tool to generate necessary files. ```bash npm dlx @better-auth/cli generate ``` ```bash yarn dlx @better-auth/cli generate ``` ```bash bun x @better-auth/cli generate ``` -------------------------------- ### Install Preferences Plugin using Package Managers Source: https://context7_llms Install the @better-auth-extended/preferences plugin using your preferred package manager. This command adds the necessary package to your project's dependencies. ```bash npm install @better-auth-extended/preferences ``` ```bash pnpm add @better-auth-extended/preferences ``` ```bash yarn add @better-auth-extended/preferences ``` ```bash bun add @better-auth-extended/preferences ``` -------------------------------- ### Install App Invite Plugin (npm, pnpm, yarn, bun) Source: https://context7_llms Installs the @better-auth-extended/app-invite plugin using various package managers. This is the first step to integrating the app invite functionality into your project. ```bash npm install @better-auth-extended/app-invite ``` ```bash pnpm add @better-auth-extended/app-invite ``` ```bash yarn add @better-auth-extended/app-invite ``` ```bash bun add @better-auth-extended/app-invite ``` -------------------------------- ### Install @better-auth-extended/test-utils with npm, pnpm, yarn, or bun Source: https://context7_llms This snippet shows how to install the @better-auth-extended/test-utils package using different package managers. It is a dependency for testing Better-Auth plugins. ```bash npm install @better-auth-extended/test-utils ``` ```bash pnpm add @better-auth-extended/test-utils ``` ```bash yarn add @better-auth-extended/test-utils ``` ```bash bun add @better-auth-extended/test-utils ``` -------------------------------- ### Setup Two-Factor Authentication Onboarding Preset Source: https://context7_llms Shows how to integrate the `setup2FAStep` preset from `@better-auth-extended/onboarding/presets` to allow users to enable two-factor authentication. This step is marked as required, ensuring that users set up 2FA. ```typescript import { setup2FAStep } from "@better-auth-extended/onboarding/presets"; onboarding({ steps: { twoFactor: setup2FAStep({ required: true, }), }, completionStep: "twoFactor", }); ``` -------------------------------- ### Complete Onboarding Step (Client and Server) Source: https://context7_llms Shows how to complete a specific onboarding step, such as 'profile', using the `onboardingStep` function. It includes examples for both client-side calls with direct parameters and server-side calls requiring a request body. ```typescript const { data, error } = await authClient.onboarding.step.profile({ bio, // required gender, // required dateOfBirth, // required }); ``` ```typescript const data = await auth.api.onboardingStepProfile({ body: { bio, gender, dateOfBirth, } }); ``` -------------------------------- ### Configure Onboarding Plugin in Auth Source: https://context7_llms Integrate the Onboarding plugin into your Better Auth configuration by adding it to the plugins array. This example demonstrates setting up 'legalConsent' and 'profile' steps with custom input schemas and handlers. ```typescript import { betterAuth } from "better-auth"; import { onboarding, createOnboardingStep, } from "@better-auth-extended/onboarding"; import { z } from "zod"; export const auth = betterAuth({ // ... other config options plugins: [ onboarding({ steps: { legalConsent: createOnboardingStep({ input: z.object({ tosAccepted: z.boolean(), privacyPolicyAccepted: z.boolean(), marketingConsent: z.boolean().optional().default(false), }), async handler(ctx) { const { tosAccepted, privacyPolicyAccepted, marketingConsent } = ctx.body; if (!tosAccepted || !privacyPolicyAccepted) { // Don't mark step as completed throw ctx.error("UNAVAILABLE_FOR_LEGAL_REASONS"); } }, required: true, once: true, }), profile: createOnboardingStep({ input: z.object({ bio: z.string().optional(), gender: z.enum(["m", "f", "d"]).optional(), dateOfBirth: z.date().optional(), }), async handler(ctx) { // Create or update user profile const profile = await createProfile(ctx.body); return profile; }, }), }, completionStep: "profile", }), ], }); async function createProfile(profileData) { // Placeholder for profile creation logic console.log("Creating profile with data:", profileData); return { id: "user-123", ...profileData }; } ``` -------------------------------- ### Skip Optional Onboarding Step (Client and Server) Source: https://context7_llms Demonstrates how to skip an optional onboarding step using the `skipStep` function. This is useful for steps that do not need to be completed but should be marked as skipped. Examples are shown for client and server. ```typescript const { data, error } = await authClient.onboarding.skipStep.myCompletionStep({}); ``` ```typescript const data = await auth.api.skipOnboardingStepMyCompletionStep({}); ``` -------------------------------- ### Get Project UI Preferences Source: https://context7_llms Retrieve multiple project UI preferences at once. ```APIDOC ## GET /api/preferences/project/$ui ### Description Retrieve multiple project UI preferences at once using a defined group. ### Method GET ### Endpoint /api/preferences/project/$ui #### Query Parameters - **scopeId** (string) - Required - The ID of the scope. ### Response #### Success Response (200) - **data** (object) - An object containing the project UI preferences. #### Response Example { "data": { "layout": "compact", "fontSize": "medium" } } ``` -------------------------------- ### Progressive Disclosure in Onboarding Steps Source: https://context7_llms Demonstrates the best practice of progressive disclosure by breaking down the onboarding process into smaller, manageable steps. This example shows how to define multiple `createOnboardingStep` configurations for different stages like welcome, profile, preferences, and verification. ```typescript const steps = { welcome: createOnboardingStep({ /* welcome step */ }), profile: createOnboardingStep({ /* basic profile */ }), preferences: createOnboardingStep({ /* user preferences */ }), verification: createOnboardingStep({ /* email/phone verification */ }), }; ``` -------------------------------- ### Example: Setting 'canWrite' permission Source: https://context7_llms This TypeScript example demonstrates how to set the 'canWrite' permission for a scope using a specific statement and permissions. This configuration requires the admin plugin to be set up for the request to succeed. ```typescript canWrite: { statement: "preferences", permissions: ["write"], }; ``` -------------------------------- ### Create Custom Onboarding Step with Preferences Source: https://context7_llms Demonstrates how to create a custom onboarding step using `createOnboardingStep` from `@better-auth-extended/onboarding`. This example defines input validation using Zod for user preferences (theme and notifications) and an asynchronous handler to update user preferences in the database. ```typescript import { createOnboardingStep } from "@better-auth-extended/onboarding"; import { z } from "zod"; const preferencesStep = createOnboardingStep({ input: z.object({ theme: z.enum(["light", "dark", "system"]).optional().default("system"), notifications: z.boolean().optional().default(false), }), async handler(ctx) { const { theme, notifications } = ctx.body; const preferences = await ctx.context.adapter.update({ model: "preferences", where: [ { field: "userId", value: ctx.context.session.id, }, ], update: { theme, notifications, }, }); return preferences; }, once: false, }); ``` -------------------------------- ### Check Onboarding Step Access (Client and Server) Source: https://context7_llms Illustrates how to check if a user has access to a particular onboarding step, like 'legalConsent', using the `canAccessOnboardingStep` function. Examples are provided for both client and server-side implementations. ```typescript const { data, error } = await authClient.onboarding.canAccessStep.legalConsent({}); ``` ```typescript const data = await auth.api.canAccessOnboardingStepLegalConsent({}); ``` -------------------------------- ### Setup New Password Onboarding Preset Source: https://context7_llms Illustrates the usage of the `setupNewPasswordStep` preset from `@better-auth-extended/onboarding/presets`. This preset is designed to prompt users for a new password, which is useful for resetting temporary passwords. It allows configuration of password requirements like minimum and maximum length. ```typescript import { setupNewPasswordStep } from "@better-auth-extended/onboarding/presets"; onboarding({ steps: { newPassword: setupNewPasswordStep({ required: true, passwordSchema: { minLength: 12, maxLength: 128, }, }), }, completionStep: "newPassword", }); ``` -------------------------------- ### Database Operations with Better-Auth Adapter (TypeScript) Source: https://context7_llms Demonstrates performing database operations using the `db` adapter provided by Better-Auth. This example shows how to create a new record in a table named 'sometable'. ```typescript await db.create({ model: "sometable", data: { hello: "world", }, }); ``` -------------------------------- ### Test Better Auth plugin functionality with provided utilities Source: https://context7_llms This TypeScript example shows how to write tests for a Better Auth plugin using the utilities provided by `@better-auth-extended/test-utils`. It includes signing up a test user and making calls to plugin-specific client methods for assertion. ```typescript const { headers, user } = await signUpWithTestUser(); describe("My Plugin", () => { it("should do something cool", async () => { const result = await client.myPlugin.doSomethingCool(); expect(result).toBe(true); }); }); ``` -------------------------------- ### Get Project UI Preferences Group (Server-Side) Source: https://context7_llms Retrieves all UI preferences for a project on the server. It takes a query object containing the scope ID. ```typescript const data = await auth.api.getProjectUiPreferences({ query: { scopeId, // required } }); ``` -------------------------------- ### Setup Invitation Email with Better Auth Source: https://context7_llms Configures the 'better-auth' instance with the 'app-invite' plugin to handle sending invitation emails. It requires a `sendInvitationEmail` function that constructs and sends an invitation link containing the invitation ID. ```typescript import { betterAuth } from "better-auth"; import { appInvite } from "@better-auth-extended/app-invite"; import { sendAppInvitation } from "./email"; export const auth = betterAuth({ plugins: [ appInvite({ async sendInvitationEmail(data) { const inviteLink = `https://example.com/accept-invitation/${data.id}`; sendAppInvitation({ name: data.name, email: data.email, invitedByUsername: data.inviter.name, invitedByEmail: data.inviter.email, inviteLink, }); }, }), ], }); ``` -------------------------------- ### Get Project UI Preferences Group (Client-Side) Source: https://context7_llms Retrieves all UI preferences for a project using the auth client. Requires a scope ID and returns the preferences data or an error. ```typescript const { data, error } = await authClient.preferences.project.$ui.get({ scopeId, // required }); ``` -------------------------------- ### GET /getAppInvitation Source: https://context7_llms Retrieves a specific invitation. This function is available on the client side and requires the invitation ID as a query parameter. ```APIDOC ## GET /getAppInvitation ### Description Retrieves a specific invitation. This function is available on the client side and requires the invitation ID as a query parameter. ### Method GET ### Endpoint /getAppInvitation ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the invitation to retrieve. ### Request Example ```json { "id": "invitation_id_123" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the details of the requested invitation. #### Response Example ```json { "data": { "id": "invitation_id_123", "email": "user@example.com", "status": "pending", "inviter": { "name": "Inviter Name" } } } ``` ``` -------------------------------- ### Get User Theme Preference Source: https://context7_llms Retrieve a single user theme preference value by scope ID. ```APIDOC ## GET /api/preferences/user/theme ### Description Retrieve a single user theme preference value by scope ID. ### Method GET ### Endpoint /api/preferences/user/theme #### Query Parameters - **scopeId** (string) - Required - The ID of the scope. ### Response #### Success Response (200) - **data** (object) - The user theme preference object. #### Response Example { "data": { "theme": "light" } } ``` -------------------------------- ### Get General Preference Source: https://context7_llms Retrieve a single general preference value by scope, key, and scope ID. ```APIDOC ## GET /api/preferences/get ### Description Retrieve a single general preference value by scope, key, and scope ID. ### Method GET ### Endpoint /api/preferences/get #### Query Parameters - **scope** (string) - Required - The scope of the preference. - **key** (string) - Required - The key of the preference. - **scopeId** (string) - Required - The ID of the scope. ### Response #### Success Response (200) - **data** (object) - The preference object. #### Response Example { "data": { "scope": "user", "key": "language", "value": "en" } } ``` -------------------------------- ### Get User Theme Preference (Server-Side) Source: https://context7_llms Retrieves the user's theme preference on the server. It takes a query object containing the scope ID. ```typescript const data = await auth.api.getUserThemePreference({ query: { scopeId, } }); ``` -------------------------------- ### Get Test Instance of Better-Auth (TypeScript) Source: https://context7_llms Initializes a test instance of Better-Auth, optionally accepting a configuration object for both the auth instance and test configuration. This allows customization of Better-Auth options, client options, and test user settings. ```typescript const { auth, db, client, testUser, signUpWithTestUser, signInWithTestUser, signInWithUser, cookieSetter, customFetchImpl, sessionSetter, context, resetDatabase, } = await getTestInstance({ options: { // Better-Auth options plugins: [myPlugin()], }, clientOptions: { // Client options plugins: [myPluginClient], }, }); ``` -------------------------------- ### Get User Theme Preference (Client-Side) Source: https://context7_llms Retrieves the user's theme preference using the auth client. Requires a scope ID and returns data or an error. ```typescript const { data, error } = await authClient.preferences.user.theme.get({ scopeId, // required }); ``` -------------------------------- ### Get Generic Preference (Server-Side) Source: https://context7_llms Retrieves a specific preference on the server using scope, key, and scope ID. It expects these parameters within the query object. ```typescript const data = await auth.api.getPreference({ query: { scope, key, scopeId, // required } }); ``` -------------------------------- ### Get Generic Preference (Client-Side) Source: https://context7_llms Retrieves a specific preference by scope, key, and scope ID using the auth client. It returns the preference data or an error. ```typescript const { data, error } = await authClient.preferences.getPreference({ scope, key, scopeId, // required }); ``` -------------------------------- ### Input Validation with Zod Schema Source: https://context7_llms Highlights the importance of input validation using Zod schemas within `createOnboardingStep`. This example defines an input schema that requires either an email or a phone number, and validates the format of each using Zod's built-in validators and custom refinements. ```typescript createOnboardingStep({ input: z .object({ email: z.email("Invalid email address"), phone: z.regex(/^\+?[\d\s-()]+$/, "Invalid phone number"), }) .refine((data) => data.email || data.phone, { message: "Either email or phone is required", path: ["email"], }), async handler(ctx) { // ... }, }); ``` -------------------------------- ### Get Invitation Details - Client and Server Source: https://context7_llms Allows retrieval of specific invitation details using the `getAppInvitation` function. The client-side function takes an `id` parameter, while the server-side uses `getAppInvitation` with a `query` object containing the `id`. ```typescript const { data, error } = await authClient.getAppInvitation({ id, }); ``` ```typescript const data = await auth.api.getAppInvitation({ query: { id, } }); ``` -------------------------------- ### Define Invitation Permissions with Admin Plugin Source: https://context7_llms This example demonstrates how to define permissions for canceling invitations using the 'statement' and 'permissions' properties. It requires the admin plugin to be configured for the Permission type to be valid. The 'statement' specifies the resource, and 'permissions' lists the allowed actions. ```typescript canCancelInvitation: { statement: "appInvite", permissions: ["create"], }; ``` -------------------------------- ### Enabling Secondary Storage for Onboarding Source: https://context7_llms Demonstrates how to configure the `onboarding` function to utilize secondary storage instead of the primary database. This is often used for performance or data separation reasons. ```typescript onboarding({ secondaryStorage: true, }); ``` -------------------------------- ### Define Custom Onboarding Step Source: https://context7_llms This code demonstrates how to define a custom onboarding step using the `createOnboardingStep` function from `@better-auth-extended/onboarding`. It shows the basic structure including an asynchronous handler and comments on other potential configurations. ```typescript import { createOnboardingStep } from "@better-auth-extended/onboarding"; const step = createOnboardingStep({ async handler(ctx) { // process step }, // ... other configuration }); ``` -------------------------------- ### Configuring Required and Optional Onboarding Steps Source: https://context7_llms Illustrates how to differentiate between essential and optional onboarding steps using the `required` flag within `createOnboardingStep`. Steps marked as `required: true` must be completed, while others are optional. ```typescript const steps = { terms: createOnboardingStep({ required: true }), // Must complete profile: createOnboardingStep({ required: false }), // Optional preferences: createOnboardingStep(), // Optional }; ``` -------------------------------- ### Use getTestInstance to set up Better Auth with plugins Source: https://context7_llms This TypeScript code demonstrates how to use the `getTestInstance` function from `@better-auth-extended/test-utils` to create a testing environment for Better Auth plugins. It allows for configuring the database, client plugins, and user data for testing. ```typescript import { betterAuth } from "better-auth"; import { getTestInstance } from "@better-auth-extended/test-utils"; import { myPlugin, myPluginClient } from "./my-plugin"; const { auth, db, client, testUser, signUpWithTestUser } = await getTestInstance({ options: { database: new Database(), // Your database adapter plugins: [myPlugin()], }, clientOptions: { plugins: [myPluginClient()], }, }); ``` ```typescript import { betterAuth } from "better-auth"; import { getTestInstance } from "@better-auth-extended/test-utils"; import { myPlugin, myPluginClient } from "./my-plugin"; const auth = betterAuth({ database: new Database(), // Your database adapter plugins: [myPlugin()], secret: "better-auth.secret", emailAndPassword: { enabled: true, autoSignIn: true, }, rateLimit: { enabled: false, }, advanced: { disableCSRFCheck: true, cookies: {}, }, }); const { db, client, testUser, signUpWithTestUser } = await getTestInstance({ auth, clientOptions: { plugins: [myPluginClient()], }, }); ``` -------------------------------- ### Integrate Onboarding Client Plugin Source: https://context7_llms Add the onboarding client plugin to your Better Auth client instance. This allows the client-side application to interact with the onboarding flow, including defining a redirect handler. ```typescript import { createAuthClient } from "better-auth/client"; import { onboardingClient } from "@better-auth-extended/onboarding/client"; import type { auth } from "./your/path"; // Import as type const authClient = createAuthClient({ plugins: [ onboardingClient({ onOnboardingRedirect: () => { window.location.href = "/onboarding"; }, }), ], }); ``` -------------------------------- ### Configuring One-Time vs Repeatable Onboarding Steps Source: https://context7_llms Explains the use of the `once` flag in `createOnboardingStep` to control whether a step can be submitted multiple times. `once: true` (or omitted, as it defaults to true) makes it a one-time submission, while `once: false` allows repeated submissions. ```typescript const steps = { terms: createOnboardingStep(), // Submit only once profile: createOnboardingStep({ once: true }), // Submit only once preferences: createOnboardingStep({ once: false }), // Allow multiple submits }; ``` -------------------------------- ### Run Vitest tests Source: https://context7_llms This bash command shows how to execute tests using Vitest, a fast testing framework. It is typically used after setting up tests with utilities like those from `@better-auth-extended/test-utils`. ```bash vitest foobar ``` -------------------------------- ### Set Project UI Preferences Source: https://context7_llms Set multiple project UI preferences at once. ```APIDOC ## PUT /api/preferences/project/$ui ### Description Set multiple project UI preferences at once using a defined group. ### Method PUT ### Endpoint /api/preferences/project/$ui #### Request Body - **scopeId** (string) - Required - The ID of the scope. - **values** (object) - Required - An object containing the preferences to set. ### Response #### Success Response (200) - **message** (string) - Success message. #### Response Example { "message": "Project UI preferences updated successfully." } ``` -------------------------------- ### Run Database Migrations (npm, pnpm, yarn, bun) Source: https://context7_llms Executes database migrations for the App Invite plugin. This command adds a new table to your database to support the plugin's functionality. It can be run using various package managers. ```bash npx @better-auth/cli migrate ``` ```bash pnpm dlx @better-auth/cli migrate ``` ```bash yarn dlx @better-auth/cli migrate ``` ```bash bun x @better-auth/cli migrate ``` -------------------------------- ### Configure Onboarding Redirect in Client Source: https://context7_llms This snippet shows how to configure custom redirect logic for the onboarding flow within the client-side plugin. The `onOnboardingRedirect` callback allows you to define custom behavior, such as navigating to an onboarding page. ```typescript onboardingClient({ onOnboardingRedirect: () => { // Custom redirect logic window.location.href = "/onboarding"; }, }); ``` -------------------------------- ### Check if User Needs Onboarding (Client and Server) Source: https://context7_llms Demonstrates how to check if a user requires onboarding using the `shouldOnboard` function. This function can be called on both the client-side via `authClient` and server-side via `auth.api`. ```typescript const { data, error } = await authClient.onboarding.shouldOnboard({}); ``` ```typescript const data = await auth.api.shouldOnboard({}); ``` -------------------------------- ### Sign Up with Test User (TypeScript) Source: https://context7_llms Asynchronously signs up a user using the pre-configured test user credentials. It returns an object containing headers, user details, session information, and an authentication token. ```typescript const { headers, user, session, token } = await signUpWithTestUser(); ``` -------------------------------- ### List Invitations (Client-Side) Source: https://context7_llms This snippet demonstrates how to list invitations from the client side using the `authClient.listInvitations` method. It requires all search, filter, and pagination parameters to be provided. The result includes invitation data or an error object. ```typescript const { data, error } = await authClient.listInvitations({ searchField, searchValue, searchOperator, limit, offset, sortBy, sortDirection, filterField, filterValue, filterOperator, }); ``` -------------------------------- ### List Invitations (Server-Side) Source: https://context7_llms This snippet shows the server-side implementation for listing invitations using `auth.api.listAppInvitation`. It takes a `query` object containing all the search, filter, and pagination parameters. This function returns the invitation data. ```typescript const data = await auth.api.listAppInvitation({ query: { searchField, searchValue, searchOperator, limit, offset, sortBy, sortDirection, filterField, filterValue, filterOperator, } }); ``` -------------------------------- ### Generate Database Schema (npm, pnpm, yarn, bun) Source: https://context7_llms Generates the database schema for the App Invite plugin. This is an alternative to running migrations directly and can be useful for inspecting or managing the schema separately. It supports multiple package managers. ```bash npx @better-auth/cli generate ``` ```bash pnpm dlx @better-auth/cli generate ``` ```bash yarn dlx @better-auth/cli generate ``` ```bash bun x @better-auth/cli generate ``` -------------------------------- ### List App Invitations Source: https://context7_llms Retrieves a list of app invitations with support for searching, filtering, sorting, and pagination. ```APIDOC ## POST /api/auth/listAppInvitation ### Description Retrieves a list of app invitations based on provided search, filter, and pagination parameters. ### Method POST ### Endpoint /api/auth/listAppInvitation ### Parameters #### Query Parameters - **searchField** (string) - Required - The field to search on. Allowed values: `email`, `name`, or `domainWhitelist`. - **searchValue** (string) - Required - The value to search for. - **searchOperator** (string) - Required - The operator for the search. Allowed values: `contains`, `starts_with`, or `ends_with`. - **limit** (number) - Required - The maximum number of invitations to return. - **offset** (number) - Required - The number of invitations to skip. - **sortBy** (string) - Required - The field to sort the invitations by. - **sortDirection** (string) - Required - The direction to sort the invitations by. Defaults to `asc`. - **filterField** (string) - Required - The field to filter the invitations by. - **filterValue** (string) - Required - The value to filter the invitations by. - **filterOperator** (string) - Required - The operator for the filter. Allowed values: `eq`, `ne`, `lt`, `lte`, `gt`, or `gte`. ### Request Example ```json { "searchField": "email", "searchValue": "test@example.com", "searchOperator": "contains", "limit": 10, "offset": 0, "sortBy": "createdAt", "sortDirection": "desc", "filterField": "status", "filterValue": "active", "filterOperator": "eq" } ``` ### Response #### Success Response (200) - **data** (array) - An array of invitation objects. - **id** (string) - Unique identifier for each invitation. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **inviterId** (string) - The ID of the inviter. - **status** (string) - The status of the invitation. - **domainWhitelist** (string) - A comma-separated whitelist of domains for a public invitation. - **expiresAt** (Date) - Timestamp of when the invitation expires. - **createdAt** (Date) - Timestamp of when the invitation was created. #### Response Example ```json { "data": [ { "id": "inv_123", "name": "John Doe", "email": "john.doe@example.com", "inviterId": "user_abc", "status": "active", "domainWhitelist": "example.com", "expiresAt": "2024-12-31T23:59:59Z", "createdAt": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Add App Invite Client Plugin (TypeScript) Source: https://context7_llms Includes the App Invite client plugin in your Better Auth client instance. This allows the client to interact with the app invite functionality. ```typescript import { createAuthClient } from "better-auth/client"; import { appInviteClient } from "@better-auth-extended/app-invite/client"; const authClient = createAuthClient({ plugins: [appInviteClient()], }); ``` -------------------------------- ### Invite User - Client and Server Source: https://context7_llms Allows inviting users to the application. The client-side and server-side functions accept user email, a boolean to resend invitations, and an optional domain whitelist for security. ```typescript const { data, error } = await authClient.inviteUser({ email, resend, domainWhitelist, }); ``` ```typescript const data = await auth.api.inviteUser({ body: { email, resend, domainWhitelist, } }); ``` -------------------------------- ### Add Preferences Client Plugin Source: https://context7_llms Include the Preferences client plugin in your Better Auth client instance to enable client-side preference management. This involves importing and calling the preferencesClient function. ```typescript import { createAuthClient } from "better-auth/client"; import { preferencesClient } from "@better-auth-extended/preferences/client"; const authClient = createAuthClient({ plugins: [preferencesClient()], }); ``` -------------------------------- ### Sign In with Custom User (TypeScript) Source: https://context7_llms Asynchronously signs in a user with provided email and password credentials. It returns an object containing headers, user details, session information, and an authentication token. ```typescript const { headers, user, session, token } = await signInWithUser(email, password); ``` -------------------------------- ### Sign In with Test User (TypeScript) Source: https://context7_llms Asynchronously signs in a user using the pre-configured test user credentials. It returns an object containing headers, user details, session information, and an authentication token. ```typescript const { headers, user, session, token } = await signInWithTestUser(); ``` -------------------------------- ### Accept Invitation - Client and Server Source: https://context7_llms Enables users to accept an invitation. Requires the invitation ID, user's name and email, and a password. The server-side function uses `acceptAppInvitation` with a 'body' parameter. ```typescript const { data, error } = await authClient.acceptInvitation({ invitationId, name, email, password, }); ``` ```typescript const data = await auth.api.acceptAppInvitation({ body: { invitationId, name, email, password, } }); ``` -------------------------------- ### Set User Theme Preference (Client-Side) Source: https://context7_llms Sets or updates the user's theme preference using the auth client. Requires a scope ID and the desired value ('light', 'dark', or 'system'). ```typescript const { data, error } = await authClient.preferences.user.theme.set({ scopeId, // required value, }); ``` -------------------------------- ### Configure Preferences Plugin in Auth Config Source: https://context7_llms Integrate the Preferences plugin into your Better Auth configuration. This involves importing the plugin and defining user and project-specific preference scopes with their schemas and default values. ```typescript import { betterAuth } from "better-auth"; import { preferences, createPreferenceScope } from "@better-auth-extended/preferences"; import { z } from "zod"; export const auth = betterAuth({ // ... other config options plugins: [ preferences({ scopes: { user: createPreferenceScope({ preferences: { theme: { type: z.enum(["light", "dark", "system"]) }, notifications: { type: z.boolean() }, }, defaultValues: { theme: "system", notifications: false, }, }), project: createPreferenceScope({ preferences: { buildChannel: { type: z.enum(["stable", "beta"]) }, envSecrets: { type: z.record(z.string(), z.string()), sensitive: true }, }, requireScopeId: true, groups: { ui: { preferences: { buildChannel: true, envSecrets: true }, operations: ["read", "write"], }, }, }), }, }), ], }); ``` -------------------------------- ### Configure App Invite Plugin in Auth (TypeScript) Source: https://context7_llms Adds the App Invite plugin to your Better Auth configuration. This involves importing the plugin and providing a function to send invitation emails. The `sendInvitationEmail` function is required for personal invites. ```typescript import { betterAuth } from "better-auth"; import { appInvite } from "@better-auth-extended/app-invite"; export const auth = betterAuth({ // ... other config options plugins: [ appInvite({ // required for personal invites sendInvitationEmail: (data) => { // ... send invitation to the user }, }), ], }); ``` -------------------------------- ### POST /inviteUser Source: https://context7_llms Invites a user to the app. This function can be used on both the client and server sides. It requires the user's email, and optionally accepts a boolean to resend the invitation and a list of allowed domains for public invitations. ```APIDOC ## POST /inviteUser ### Description Invites a user to the app. This function can be used on both the client and server sides. It requires the user's email, and optionally accepts a boolean to resend the invitation and a list of allowed domains for public invitations. ### Method POST ### Endpoint /inviteUser ### Parameters #### Query Parameters - **email** (string) - Required - The email address of the user to invite. Leave empty to create a public invitation. - **resend** (boolean) - Optional - A boolean value that determines whether to resend the invitation email, if the user is already invited. Defaults to `false`. - **domainWhitelist** (string) - Optional - An optional comma-separated list of domains that allows public invitations to be accepted only from approved domains (e.g., `example.com,*.example.org`). ### Request Example ```json { "email": "user@example.com", "resend": false, "domainWhitelist": "example.com" } ``` ### Response #### Success Response (200) - **data** (object) - Contains invitation details upon successful invitation. #### Response Example ```json { "data": { "id": "invitation_id_123", "email": "user@example.com", "status": "pending" } } ``` ``` -------------------------------- ### Set Project UI Preferences Group (Client-Side) Source: https://context7_llms Sets multiple UI preferences for a project using the auth client. Requires a scope ID and an object containing the values to set. ```typescript const { data, error } = await authClient.preferences.project.$ui.set({ scopeId, // required values, }); ``` -------------------------------- ### List Invitations Source: https://context7_llms Allows a user to list all invitations issued by themselves. By default, 100 invitations are returned. ```APIDOC ## List Invitations ### Description Allows a user to list all invitations issued by themselves. By default, 100 invitations are returned. ### Method GET ### Endpoint /listInvitations ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of invitations to return. Defaults to 100. ### Request Example ```json { "limit": 50 } ``` ### Response #### Success Response (200) - **data** (array) - An array of invitation objects. #### Response Example ```json { "data": [ { "id": "invitation_id_123", "email": "user1@example.com", "status": "pending" }, { "id": "invitation_id_456", "email": "user2@example.com", "status": "accepted" } ] } ``` ``` -------------------------------- ### Type Definition for listAppInvitation Source: https://context7_llms This type definition outlines the structure and possible values for the parameters used when listing application invitations. It includes optional fields for searching, filtering, sorting, and pagination, along with their respective types and descriptions. ```typescript type listAppInvitation = { /** * The field to search on, which can be `email`, `name`, or `domainWhitelist`. */ searchField?: string /** * The value to search for. */ searchValue?: string /** * The operator to use for the search. Can be `contains`, `starts_with` or `ends_with` */ searchOperator?: string /** * The number of invitations to return. */ limit?: number /** * The number of invitations to skip. */ offset?: number /** * The field to sort the invitations by. */ sortBy?: string /** * The direction to sort the invitations by. Defaults to `asc`. */ sortDirection?: string /** * The field to filter the invitations by. */ filterField?: string /** * The value to filter the invitations by. */ filterValue?: string /** * The operator to use for the filter. It can be `eq`, `ne`, `lt`, `lte`, `gt`, or `gte`. */ filterOperator?: string } ``` -------------------------------- ### POST /acceptInvitation Source: https://context7_llms Accepts an invitation to the app. This function is used when a user clicks on an invitation link. It requires the invitation ID, user's name, email, and password. ```APIDOC ## POST /acceptInvitation ### Description Accepts an invitation to the app. This function is used when a user clicks on an invitation link. It requires the invitation ID, user's name, email, and password. ### Method POST ### Endpoint /acceptInvitation ### Parameters #### Request Body - **invitationId** (string) - Required - The ID of the invitation to accept. - **name** (string) - Optional - The name of the user that accepts the invitation. (overriden if predefined in the invitation). - **email** (string) - Optional - The email address of the user that accepts the invitation. Required for public invites. - **password** (string) - Required - The password used to sign in after accepting the invitation. ### Request Example ```json { "invitationId": "invitation_id_123", "name": "John Doe", "email": "user@example.com", "password": "securepassword" } ``` ### Response #### Success Response (200) - **data** (object) - Contains user and session details upon successful acceptance. #### Response Example ```json { "data": { "user": { "id": "user_id_456", "name": "John Doe" }, "sessionToken": "session_token_abc" } } ``` ``` -------------------------------- ### Set User Theme Preference Source: https://context7_llms Set or update a single user theme preference value. ```APIDOC ## PUT /api/preferences/user/theme ### Description Set or update a single user theme preference value. ### Method PUT ### Endpoint /api/preferences/user/theme #### Request Body - **scopeId** (string) - Required - The ID of the scope. - **value** ("light" | "dark" | "system") - Required - The theme value to set. ### Response #### Success Response (200) - **message** (string) - Success message. #### Response Example { "message": "User theme preference updated successfully." } ``` -------------------------------- ### Set User Theme Preference (Server-Side) Source: https://context7_llms Sets or updates the user's theme preference on the server. It takes a body object containing the scope ID and the value. ```typescript const data = await auth.api.setUserThemePreference({ body: { scopeId, // required value, } }); ``` -------------------------------- ### Reset Better-Auth Database (TypeScript) Source: https://context7_llms Provides functionality to reset the Better-Auth database, either by clearing all authentication-related tables or by specifying which tables to reset. ```typescript // Reset all auth tables await resetDatabase(); // Reset specific tables await resetDatabase(["user", "session"]); ``` -------------------------------- ### Set Project UI Preferences Group (Server-Side) Source: https://context7_llms Sets multiple UI preferences for a project on the server. It takes a body object containing the scope ID and an object with the preference values. ```typescript const data = await auth.api.setProjectUiPreferences({ body: { scopeId, // required values, } }); ``` -------------------------------- ### Define Scopes and Preferences in TypeScript Source: https://context7_llms This TypeScript code defines two scopes, 'user' and 'project', with their respective preferences. The 'user' scope includes 'theme' and 'notifications', while the 'project' scope has 'buildChannel' and 'envSecrets', along with group configurations for UI operations. It utilizes the '@better-auth-extended/preferences' library for defining these scopes and Zod for schema validation. ```typescript import { preferences, createPreferenceScope } from "@better-auth-extended/preferences"; import { z } from "zod"; preferences({ scopes: { user: createPreferenceScope({ preferences: { theme: { type: z.enum(["light", "dark", "system"]) }, notifications: { type: z.boolean() }, }, defaultValues: { theme: "system", notifications: false, }, }), project: preferences.createScope({ preferences: { buildChannel: { type: z.enum(["stable", "beta"]) }, envSecrets: { type: z.record(z.string(), z.string()), sensitive: true }, }, requireScopeId: true, groups: { ui: { preferences: { buildChannel: true, envSecrets: true }, operations: ["read", "write"], }, }, }), }, }); ``` -------------------------------- ### Update Invitation Status - Client and Server Source: https://context7_llms Provides functions to update the status of an invitation. The client offers `cancelInvitation`, `rejectInvitation`, and `acceptInvitation`. The server-side equivalents are `cancelAppInvitation`, `rejectAppInvitation`, and `acceptAppInvitation`, all requiring the `invitationId`. ```typescript const { data, error } = await authClient.cancelInvitation({ invitationId, }); ``` ```typescript const data = await auth.api.cancelAppInvitation({ body: { invitationId, } }); ``` ```typescript const { data, error } = await authClient.rejectInvitation({ invitationId, }); ``` ```typescript const data = await auth.api.rejectAppInvitation({ body: { invitationId, } }); ``` -------------------------------- ### Set General Preference Source: https://context7_llms Set or update a single general preference value. ```APIDOC ## PUT /api/preferences/set ### Description Set or update a single general preference value. ### Method PUT ### Endpoint /api/preferences/set #### Request Body - **scope** (string) - Required - The scope of the preference. - **key** (string) - Required - The key of the preference. - **value** (any) - Required - The value to set. - **scopeId** (string) - Required - The ID of the scope. ### Response #### Success Response (200) - **message** (string) - Success message. #### Response Example { "message": "Preference updated successfully." } ``` -------------------------------- ### POST /rejectInvitation Source: https://context7_llms Rejects an invitation. This function can be used on both the client and server sides. It requires the invitation ID. ```APIDOC ## POST /rejectInvitation ### Description Rejects an invitation. This function can be used on both the client and server sides. It requires the invitation ID. ### Method POST ### Endpoint /rejectInvitation ### Parameters #### Request Body - **invitationId** (string) - Required - The ID of the invitation to reject. ### Request Example ```json { "invitationId": "invitation_id_123" } ``` ### Response #### Success Response (200) - **data** (object) - Confirmation of rejection. #### Response Example ```json { "data": { "message": "Invitation rejected successfully." } } ``` ``` -------------------------------- ### Set Session Headers using sessionSetter (TypeScript) Source: https://context7_llms Employs the `sessionSetter` utility to extract session details from a successful sign-in response and apply them to a `Headers` object. This facilitates setting session headers for subsequent requests. ```typescript const headers = new Headers(); await client.signIn.email( { email: testUser.email, password: testUser.password, }, { onSuccess: sessionSetter(headers), } ); const response = await client.listSessions({ fetchOptions: { headers, }, }); ``` -------------------------------- ### Set Generic Preference (Server-Side) Source: https://context7_llms Sets or updates a specific preference on the server using scope, key, value, and scope ID. These are provided in the request body. ```typescript const data = await auth.api.setPreference({ body: { scope, key, value, scopeId, // required } }); ``` -------------------------------- ### Bypass Fetch Request with customFetchImpl (TypeScript) Source: https://context7_llms Allows bypassing the default fetch request to the Better-Auth server by providing a `customFetchImpl`. This directly invokes the endpoint on the server, useful for specific testing scenarios or optimizations. ```typescript const client = createAuthClient({ baseURL: "http://localhost:3000", fetchOptions: { customFetchImpl, }, }); ``` -------------------------------- ### Set Generic Preference (Client-Side) Source: https://context7_llms Sets or updates a specific preference by scope, key, value, and scope ID using the auth client. Returns the updated preference data or an error. ```typescript const { data, error } = await authClient.preferences.setPreference({ scope, key, value, scopeId, // required }); ```