[options]
```
--------------------------------
### Create Organization (Client-Side)
Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md
Create a new organization using the client-side setup. The creator is automatically assigned the 'owner' role. Optional fields include logo and metadata.
```typescript
const createOrg = async () => {
const { data, error } = await authClient.organization.create({
name: "My Company",
slug: "my-company",
logo: "https://example.com/logo.png",
metadata: { plan: "pro" },
});
};
```
--------------------------------
### Full Server Configuration (auth.ts)
Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md
Configure a full server setup for Better Auth, including plugins, session management, account linking, and rate limiting.
```typescript
import { auth } from "better-auth";
import { DrizzleAdapter } from "@better-auth/drizzle-adapter";
import { db } from "../db"; // Your Drizzle instance
export const { handlers, auth, signIn, signOut } = auth({
adapter: DrizzleAdapter(db, schema), // Example using Drizzle adapter
plugins: [
// Add feature plugins here, e.g., twoFactor, organization
],
session: {
expires: "24h", // Session expiry
maxAge: 60 * 60 * 24, // Session max age in seconds
updateAge: 60 * 60, // Session update age in seconds
},
account: {
accountLinking: true, // Enable account linking for multiple providers
},
rateLimit: {
// Rate limiting configuration
}
});
export type Session = typeof auth.$Infer.Session;
```
--------------------------------
### Server-Side Organization Plugin Setup
Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md
Configure the organization plugin on the server. Set limits for organizations per user and members per organization. Ensure the 'organization' table exists in your database.
```typescript
import { betterAuth } from "better-auth";
import { organization } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
organization({
allowUserToCreateOrganization: true,
organizationLimit: 5, // Max orgs per user
membershipLimit: 100, // Max members per org
}),
],
});
```
--------------------------------
### Server-Side Setup with Two-Factor Plugin
Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md
Configure the twoFactor plugin on the server with a specified issuer. Ensure the 'twoFactorSecret' column exists on your user table after migration.
```typescript
import { betterAuth } from "better-auth";
import { twoFactor } from "better-auth/plugins";
export const auth = betterAuth({
appName: "My App",
plugins: [
twoFactor({
issuer: "My App",
}),
],
});
```
--------------------------------
### Session Type Usage Examples
Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md
Shows how to infer the session type and check for an active session, accessing associated user data.
```typescript
// Type inference
type AppSession = typeof auth.$Infer.Session;
```
```typescript
// Check session
const session = await auth.api.getSession({ headers });
if (session) {
console.log(session.user.email);
}
```
--------------------------------
### PostgreSQL Direct Connection
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Connect directly to a PostgreSQL database using the 'pg' package. Ensure 'pg' is installed and DATABASE_URL is set.
```typescript
import pg from "pg";
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
export const auth = betterAuth({
database: pool,
});
```
--------------------------------
### MySQL Direct Connection
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Connect directly to a MySQL database using the 'mysql2/promise' package. Ensure 'mysql2' is installed and DATABASE_URL is set.
```typescript
import mysql from "mysql2/promise";
const pool = mysql.createPool({
connectionString: process.env.DATABASE_URL,
});
export const auth = betterAuth({
database: pool,
});
```
--------------------------------
### TOTP Setup - Disable 2FA
Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md
Disable Two-Factor Authentication. Requires password verification and revokes all trusted devices.
```APIDOC
## Disable 2FA
Requires password verification. Revokes all trusted devices.
```typescript
const { error } = await authClient.twoFactor.disable({
password: "user-password",
});
```
```
--------------------------------
### Setup Invitation Email Sending
Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md
Customize the invitation email content and sending mechanism. This server-side configuration allows for personalized invitation emails.
```typescript
import { betterAuth } from "better-auth";
import { organization } from "better-auth/plugins";
import { sendEmail } from "./email";
export const auth = betterAuth({
plugins: [
organization({
sendInvitationEmail: async (data) => {
const { email, organization, inviter, invitation } = data;
await sendEmail({
to: email,
subject: `Join ${organization.name}`,
html: `
${inviter.user.name} invited you to join ${organization.name}
Accept Invitation
`,
});
},
}),
],
});
```
--------------------------------
### Complete Better Auth Security Configuration
Source: https://github.com/better-auth/skills/blob/main/_autodocs/security.md
A comprehensive Better Auth configuration example demonstrating various security settings including trusted origins, rate limiting, session security, OAuth security, and advanced options.
```typescript
import { betterAuth } from "better-auth";
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET,
baseURL: "https://api.example.com",
// Trusted origins
trustedOrigins: [
"https://app.example.com",
"https://*.preview.example.com",
],
// Rate limiting
rateLimit: {
enabled: true,
storage: "secondary-storage",
customRules: {
"/api/auth/sign-in/email": { window: 60, max: 5 },
"/api/auth/sign-up/email": { window: 60, max: 3 },
},
},
// Session security
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
freshAge: 60 * 60,
cookieCache: {
enabled: true,
maxAge: 300,
strategy: "jwe", // Encrypted session data
},
},
// OAuth security
account: {
encryptOAuthTokens: true,
storeStateStrategy: "cookie",
},
// Advanced settings
advanced: {
useSecureCookies: true,
disableCSRFCheck: false,
cookiePrefix: "myapp",
defaultCookieAttributes: {
sameSite: "lax",
},
ipAddress: {
ipAddressHeaders: ["x-forwarded-for"],
ipv6Subnet: 64,
},
backgroundTasks: {
handler: (promise) => waitUntil(promise),
},
},
// Audit logging
databaseHooks: {
session: {
create: {
after: async ({ data, ctx }) => {
await auditLog("session.created", { userId: data.userId });
},
},
},
},
});
```
--------------------------------
### Plugin Schema Customization Example
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Shows how to customize plugin schema, including table names and field mappings. You can also add additional fields to the schema.
```typescript
organization({
schema: {
organization: {
modelName: "workspace", // Custom table name
fields: {
name: "workspaceName", // Custom field mapping
},
additionalFields: {
plan: { type: "string", required: false },
},
},
},
})
```
--------------------------------
### Prisma ORM Adapter Configuration
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Configure the Prisma adapter for Better Auth. Requires '@prisma/client' and specific setup steps including schema generation and migration.
```typescript
import { PrismaClient } from "@prisma/client";
import { prismaAdapter } from "better-auth/adapters/prisma";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql", // or "mysql", "sqlite"
}),
});
```
--------------------------------
### Displaying QR Code for TOTP Setup
Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md
A React component to display a QR code generated from a TOTP URI. Requires the 'react-qr-code' library.
```tsx
import QRCode from "react-qr-code";
const TotpSetup = ({ totpURI }: { totpURI: string }) => {
return ;
};
```
--------------------------------
### Run Info Command
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Display detailed information about your Better Auth configuration, including detected framework, adapter, plugins, and environment variables.
```bash
npx @better-auth/cli info
```
--------------------------------
### Initialize Better Auth Instance
Source: https://github.com/better-auth/skills/blob/main/_autodocs/core-api.md
Demonstrates how to create and configure a Better Auth server instance with various options like database, secret, app name, email/password, social providers, and plugins.
```typescript
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: prisma,
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
appName: "My App",
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
},
},
plugins: [
twoFactor({ issuer: "My App" }),
],
});
```
--------------------------------
### Drizzle Schema Extension Example
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Example of extending the Drizzle schema with custom fields like 'plan' for users and defining session table structure.
```typescript
export const users = pgTable("users", {
id: text().primaryKey(),
email: text().notNull().unique(),
name: text().notNull(),
plan: text().default("free"),
});
export const sessions = pgTable("sessions", {
id: text().primaryKey(),
userId: text().notNull(),
token: text().notNull().unique(),
expiresAt: timestamp().notNull(),
});
```
--------------------------------
### Configuring OTP Email Delivery
Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md
Set up custom OTP delivery via email. This example uses a placeholder 'sendEmail' function and configures code validity period, digits, and allowed attempts.
```typescript
import { betterAuth } from "better-auth";
import { twoFactor } from "better-auth/plugins";
import { sendEmail } from "./email";
export const auth = betterAuth({
plugins: [
twoFactor({
otpOptions: {
sendOTP: async ({ user, otp }, ctx) => {
await sendEmail({
to: user.email,
subject: "Your verification code",
text: `Your code is: ${otp}`,
});
},
period: 5, // Code validity in minutes (default: 3)
digits: 6, // Number of digits (default: 6)
allowedAttempts: 5, // Max verification attempts (default: 5)
},
}),
],
});
```
--------------------------------
### Drizzle Output Format
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Example of the generated Drizzle schema output.
```typescript
export const users = pgTable("users", {
id: text().primaryKey(),
email: text().notNull().unique(),
name: text().notNull(),
// ... auth fields
});
```
--------------------------------
### Client Sign Up with Email
Source: https://github.com/better-auth/skills/blob/main/_autodocs/authentication-methods.md
Use the client-side SDK to sign up a new user with their email and password. Ensure the callbackURL is correctly configured.
```typescript
const { data, error } = await authClient.signUp.email({
email: "user@example.com",
password: "secure-password",
name: "User Name",
callbackURL: "https://app.example.com/callback",
dontAutoSignIn: false,
});
```
--------------------------------
### Run Migrate Command (Built-in Kysely Adapter)
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Execute the migrate command for the built-in Kysely adapter, which automatically applies schema changes.
```bash
npx @better-auth/cli migrate
```
--------------------------------
### Sign Up with Email
Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md
Register a new user using their email and password. Callbacks can handle success or error states, including redirecting the user.
```typescript
const { data, error } = await authClient.signUp.email({
email: "user@example.com",
password: "secure-password",
name: "User Name",
callbackURL?: "https://app.example.com/callback",
dontAutoSignIn?: false,
}, {
onSuccess(context) {
// Handle success - session is created
window.location.href = "/dashboard";
},
onError(context) {
// Handle error
console.error(context.error.message);
}
});
```
--------------------------------
### Configure passkey Plugin Client
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Initialize the passkey client plugin. This typically requires no configuration options for basic usage.
```typescript
import { passkeyClient } from "@better-auth/passkey/client";
plugins: [passkeyClient()]
```
--------------------------------
### Get Organization
Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md
Fetches detailed information about a specific organization, including its members, pending invitations, and associated teams.
```APIDOC
## Get Organization
```typescript
const { data, error } = await authClient.organization.getFullOrganization({
organizationId: "org-id",
});
// Returns: { organization, members, invitations, teams }
```
```
--------------------------------
### Load Environment Variables from .env File
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Load Better Auth and database configuration from a .env file.
```bash
# .env
BETTER_AUTH_SECRET=...
DATABASE_URL=...
npx @better-auth/cli migrate
```
--------------------------------
### SQLite Direct Connection (Node.js)
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Connect directly to a SQLite database using the 'better-sqlite3' library. Ensure 'better-sqlite3' is installed.
```typescript
import Database from "better-sqlite3";
const db = new Database("./auth.db");
export const auth = betterAuth({
database: db, // Pass instance directly
});
```
--------------------------------
### Configure Passkey Plugin
Source: https://github.com/better-auth/skills/blob/main/_autodocs/authentication-methods.md
Sets up the WebAuthn passkey plugin. Requires configuration of the relying party ID, name, and origin URL for security.
```typescript
import { passkey } from "@better-auth/passkey";
plugins: [
passkey({
rpID: "example.com", // Domain name (no https://)
rpName: "My App", // Display name
origin: "https://example.com", // Full origin URL
}),
]
```
--------------------------------
### Run Migrate Command with Custom Config
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Use the migrate command with a custom configuration file path.
```bash
npx @better-auth/cli migrate --config src/config/auth.ts
```
--------------------------------
### Client-side Session Check
Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md
Use the `useSession` hook in the client to get session data. It returns `{ data: session, isPending }`.
```javascript
useSession()
```
--------------------------------
### Vercel Build Step Configuration
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Configure the build command and environment variables in vercel.json for deployment.
```json
{
"buildCommand": "npm run db:push && npm run build",
"env": {
"DATABASE_URL": "@database_url",
"BETTER_AUTH_SECRET": "@auth_secret"
}
}
```
--------------------------------
### betterAuth()
Source: https://github.com/better-auth/skills/blob/main/_autodocs/core-api.md
Initializes and configures a Better Auth server instance with provided options. This is the primary function to set up the authentication system.
```APIDOC
## betterAuth()
### Description
Creates and configures a Better Auth server instance.
### Signature
```typescript
betterAuth(options: InitOptions): Auth
```
### Parameters
#### Path Parameters
* None
#### Query Parameters
* None
#### Request Body
* None
### Parameters Table
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| options | InitOptions | Yes | — | Configuration object for auth instance |
### Return Type
```typescript
Auth {
handler: (request: Request) => Promise
api: {
getSession(options: { headers: Headers }): Promise
signInEmail(body: SignInEmailBody): Promise
signUpEmail(body: SignUpEmailBody): Promise
signOut(options: { headers: Headers }): Promise
requestPasswordReset(body: { email: string; redirectTo?: string }): Promise
resetPassword(body: { newPassword: string; token: string }): Promise
changePassword(body: { oldPassword: string; newPassword: string }, options: { headers: Headers }): Promise
changeEmail(body: { newEmail: string }, options: { headers: Headers }): Promise
getUser(options: { headers: Headers }): Promise
listSessions(options: { headers: Headers }): Promise
revokeSession(options: { headers: Headers; body: { token: string } }): Promise
revokeSessions(options: { headers: Headers }): Promise
listAccounts(options: { headers: Headers }): Promise
unlinkAccount(body: { accountId: string }, options: { headers: Headers }): Promise
createOrganization?(body: CreateOrganizationBody, options?: { headers: Headers }): Promise
addMember?(body: AddMemberBody, options?: { headers: Headers }): Promise
removeMember?(body: { memberIdOrEmail: string }, options?: { headers: Headers }): Promise
updateMemberRole?(body: UpdateMemberRoleBody, options?: { headers: Headers }): Promise
inviteMember?(body: InviteMemberBody, options?: { headers: Headers }): Promise
listMembers?(options?: { headers: Headers }): Promise
listInvitations?(options?: { headers: Headers }): Promise
listOrganizations?(options?: { headers: Headers }): Promise
getOrganization?(body: { organizationId: string }, options?: { headers: Headers }): Promise
}
$Infer: {
Session: typeof session
}
}
```
### Usage Example
```typescript
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: prisma,
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
appName: "My App",
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
},
},
plugins: [
twoFactor({ issuer: "My App" }),
],
});
```
### Framework Handlers
Convert the Auth instance to a framework-specific handler:
```typescript
// Next.js App Router
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);
// Express
import { toNodeHandler } from "better-auth/node";
app.all("/api/auth/*", toNodeHandler(auth));
// SvelteKit
import { svelteKitHandler } from "better-auth/svelte-kit";
export const { GET, POST } = svelteKitHandler(auth);
// Hono
import { toHonoHandler } from "better-auth/hono";
app.all("/api/auth/*", toHonoHandler(auth));
```
```
--------------------------------
### Configure Database Adapter for Drizzle
Source: https://github.com/better-auth/skills/blob/main/better-auth/best-practices/SKILL.md
Import and configure the Drizzle ORM adapter for Better Auth. Ensure your Drizzle setup is compatible.
```typescript
import { DrizzleAdapter } from "better-auth/adapters/drizzle";
```
--------------------------------
### Plugin Configuration Pattern
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Illustrates the general pattern for configuring plugins with optional settings. If options are omitted, default values are used.
```typescript
pluginName(options?: {
// Configuration options
// Each plugin defines its own options
})
If `options` omitted, uses defaults.
```
--------------------------------
### Get Invitation URL
Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md
Generates a unique URL for an invitation. This URL can be shared with the invitee to accept the invitation. This method does not send an email.
```APIDOC
## GET /organization/invitation-url
### Description
Generates a unique URL for an invitation. This URL can be shared with the invitee to accept the invitation. This method does not send an email.
### Method
GET
### Endpoint
/organization/invitation-url
### Parameters
#### Query Parameters
- **email** (string) - Required - The email address of the person to invite.
- **role** (string) - Required - The role to assign to the invited member (e.g., "member", "admin").
- **callbackURL** (string) - Optional - A URL to redirect the user to after accepting the invitation.
- **organizationId** (string) - Optional - The ID of the organization. If omitted, the active organization is used.
### Response
#### Success Response (200)
- **url** (string) - The unique URL for the invitation.
#### Response Example
```json
{
"url": "https://app.example.com/accept-invite/inv-12345"
}
```
```
--------------------------------
### Get Session (Any Framework)
Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md
Fetch the current user's session data directly using the auth client. This method is framework-agnostic.
```typescript
const session = await authClient.getSession();
if (session) {
console.log(session.user.email);
} else {
// Not authenticated
}
```
--------------------------------
### Set DATABASE_URL for Connection Issues
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Troubleshoot 'Database connection failed' errors by ensuring the DATABASE_URL environment variable is correctly set.
```bash
DATABASE_URL=postgresql://user:password@localhost/dbname \
npx @better-auth/cli migrate
```
--------------------------------
### Minimal Server Configuration (auth.ts)
Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md
Set up the minimal server configuration for Better Auth, requiring at least a database connection or adapter and enabling email/password authentication.
```typescript
import { auth } from "better-auth";
export const { handlers, auth, signIn, signOut } = auth({
database: {
// Connection or adapter details here
},
emailAndPassword: { enabled: true },
});
export type Session = typeof auth.$Infer.Session;
```
--------------------------------
### Get Invitation URL
Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md
Retrieve a unique URL for invitation acceptance. The `organizationId` is optional and defaults to the active organization. The `callbackURL` is also optional.
```typescript
const { data, error } = await authClient.organization.getInvitationURL({
email: "newuser@example.com",
role: "member",
callbackURL: "https://app.example.com/dashboard", // Optional
organizationId?: "org-id", // Uses active if omitted
});
// Share data.url via email, Slack, etc.
// Does NOT call sendInvitationEmail
```
--------------------------------
### Get Full Organization Details
Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md
Fetch detailed information about a specific organization, including its members, invitations, and teams, using the client-side method.
```typescript
const { data, error } = await authClient.organization.getFullOrganization({
organizationId: "org-id",
});
// Returns: { organization, members, invitations, teams }
```
--------------------------------
### Create Auth Client (Vanilla JS)
Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md
Instantiate the client for browser-side authentication operations. Ensure the baseURL matches your auth API configuration.
```typescript
import { createAuthClient } from "better-auth/client";
export const authClient = createAuthClient({
baseURL: "http://localhost:3000",
});
```
--------------------------------
### Set Custom Invitation Expiration
Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md
Configure the expiration time for organization invitations. The default is 48 hours. This example sets the expiration to 7 days.
```typescript
organization({
invitationExpiresIn: 60 * 60 * 24 * 7, // 7 days
});
```
--------------------------------
### Database Migration CLI Commands
Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md
Run these commands to manage database migrations for different adapters. Always re-run after adding or changing plugins.
```bash
# For built-in Kysely adapter
npx @better-auth/cli@latest migrate
# For Prisma
npx @better-auth/cli@latest generate --output prisma/schema.prisma
npx prisma migrate dev
# For Drizzle
npx @better-auth/cli@latest generate --output src/db/auth-schema.ts
npx drizzle-kit push
```
--------------------------------
### Configure organization Plugin Client
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Initialize the organization client plugin. This typically requires no configuration options for basic usage.
```typescript
import { organizationClient } from "better-auth/client/plugins";
plugins: [organizationClient()]
```
--------------------------------
### Better Auth CLI: Generate Prisma Schema
Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md
Generate the Prisma schema file using the Better Auth CLI, then run Prisma migrations.
```bash
npx @better-auth/cli@latest generate --output prisma/schema.prisma
npx prisma migrate dev
```
--------------------------------
### SCIM Plugin Server Import
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Import and configure the SCIM plugin for user provisioning. Requires a secret key from environment variables.
```typescript
import { scim } from "@better-auth/scim";
plugins: [
scim({
secret: process.env.SCIM_SECRET,
}),
]
```
--------------------------------
### OTP Setup - Send OTP
Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md
Send an OTP code to the user's registered email or phone number. This triggers the `sendOTP` handler configured on the server.
```APIDOC
## Send OTP
```typescript
const { error } = await authClient.twoFactor.sendOtp();
// Triggers sendOTP handler configured on server
```
```
--------------------------------
### Client Configuration for Vanilla JS
Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md
Import and configure the Better Auth client for Vanilla JavaScript applications using the `better-auth/client` package. Client plugins can be included in the configuration.
```typescript
import { createAuthClient } from "better-auth/client";
const { signIn, signUp, signOut, useSession, getSession } = createAuthClient({
// Add client plugins here if needed
// plugins: [
// ...
// ]
});
export { signIn, signUp, signOut, useSession, getSession };
```
--------------------------------
### Configure passkey Plugin on Server
Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md
Enable WebAuthn/FIDO2 passwordless authentication. Configure Relying Party ID, name, and origin for secure passkey operations.
```typescript
import { passkey } from "@better-auth/passkey";
plugins: [
passkey({
rpID: "example.com",
rpName?: "My App",
origin: "https://example.com",
}),
]
```
--------------------------------
### twoFactor.verifyTotp()
Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md
Verifies a Time-based One-Time Password (TOTP) code, typically used during sign-in or setup. It can accept codes from a small time window around the current time.
```APIDOC
## twoFactor.verifyTotp()
### Description
Verifies a TOTP code during signin or setup. Accepts codes from the period before/after the current time (window = 1).
### Method
Not specified (assumed to be a client-side SDK method call)
### Parameters
#### Request Body
- **code** (string) - Required - The 6-digit TOTP code.
- **trustDevice** (boolean) - Optional - A flag to remember the device.
```
--------------------------------
### Enable 2FA (TOTP) with Password Verification
Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md
Initiate the 2FA enablement process by providing the user's password. This returns a TOTP URI for QR code generation and backup codes.
```typescript
const { data, error } = await authClient.twoFactor.enable({
password: "user-password",
});
if (data) {
// data.totpURI - for QR code generation
// data.backupCodes - for user to save securely
}
```
--------------------------------
### Run Migrate with Environment Variables
Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md
Set environment variables like BETTER_AUTH_SECRET and DATABASE_URL before running the migrate command.
```bash
BETTER_AUTH_SECRET=your-secret
BETTER_AUTH_URL=https://api.example.com
DATABASE_URL=postgresql://...
npx @better-auth/cli migrate
```