### Install and Run Astro Project
Source: https://github.com/better-auth/examples/blob/main/astro-example/README.md
Follow these commands to install dependencies and start the development server for the Astro example. Navigate to http://localhost:3000 to view the application.
```bash
pnpm install
pnpm run dev
```
--------------------------------
### Install and Start Expo Project
Source: https://github.com/better-auth/examples/blob/main/expo-example/README.md
Use these commands to install dependencies and start the Expo development server.
```bash
pnpm install
pnpm start
```
--------------------------------
### Install and Run SvelteKit Better Auth Example
Source: https://github.com/better-auth/examples/blob/main/svelte-kit-example/README.md
Instructions for setting up and running the SvelteKit Better Auth example. Ensure you have pnpm installed and follow the steps to configure environment variables and dependencies.
```bash
cd /path/to/better-auth/ # Project root of this better-auth repo, not the root of this example
pnpm install
pnpm build
cd ./examples/svelte-kit-example/ # The root of this example project
pnpm migrate
pnpm dev
```
--------------------------------
### Run Nuxt Better Auth Project
Source: https://github.com/better-auth/examples/blob/main/nuxt-example/README.md
Commands to install dependencies and start the development server.
```bash
pnpm install
pnpm dev
```
--------------------------------
### Start Development Server
Source: https://github.com/better-auth/examples/blob/main/browser-extension-example/README.md
Run the development server to enable hot-reloading during extension development.
```bash
pnpm dev
# or
npm run dev
```
--------------------------------
### Run Development Server
Source: https://github.com/better-auth/examples/blob/main/tanstack-example/README.md
Start the development server for your TanStack Start project with Better Auth.
```bash
pnpm dev
```
--------------------------------
### Install Dependencies
Source: https://github.com/better-auth/examples/blob/main/tanstack-example/README.md
Run this command to install project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/better-auth/examples/blob/main/react-router-example/README.md
Run this command in your terminal to install all necessary project dependencies.
```bash
npm install
```
--------------------------------
### Start Development Server
Source: https://github.com/better-auth/examples/blob/main/react-router-example/README.md
Initiates the development server with Hot Module Replacement (HMR) enabled for a seamless development experience. The application will be accessible at http://localhost:5173.
```bash
npm run dev
```
--------------------------------
### Run Docker Container
Source: https://github.com/better-auth/examples/blob/main/react-router-example/README.md
Starts a Docker container from the 'my-app' image and maps port 3000 on the host to port 3000 in the container. This makes the application accessible via http://localhost:3000.
```bash
docker run -p 3000:3000 my-app
```
--------------------------------
### Create TanStack Router API Route
Source: https://context7.com/better-auth/examples/llms.txt
Defines API routes for authentication using TanStack Start.
```typescript
// app/routes/api/auth/$.ts
import { createAPIFileRoute } from "@tanstack/start/api";
import { auth } from "~/lib/auth";
export const APIRoute = createAPIFileRoute("/api/auth/$")({
GET: ({ request }) => {
return auth.handler(request);
},
POST: ({ request }) => {
return auth.handler(request);
},
});
```
--------------------------------
### Get Current Session (Server-side)
Source: https://context7.com/better-auth/examples/llms.txt
Retrieves session data on the server, typically used for protecting routes in Astro.
```typescript
// Astro page
---
import { auth } from "@/auth";
const session = await auth.api.getSession({
headers: Astro.request.headers,
});
if (!session) {
return Astro.redirect("/sign-in");
}
---
Welcome, {session.user.name}!
```
--------------------------------
### Create Production Build
Source: https://github.com/better-auth/examples/blob/main/browser-extension-example/README.md
Generate a production-ready bundle for the extension to be zipped and published.
```bash
pnpm build
# or
npm run build
```
--------------------------------
### Initialize Solid.js Auth Client
Source: https://context7.com/better-auth/examples/llms.txt
Sets up the auth client for Solid.js with reactive session handling and plugin configuration.
```typescript
// libs/auth-client.ts
import { passkeyClient, twoFactorClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/solid";
export const {
signIn,
signOut,
useSession,
signUp,
passkey: passkeyActions,
useListPasskeys,
twoFactor: twoFactorActions,
$Infer,
updateUser,
changePassword,
revokeSession,
revokeSessions,
} = createAuthClient({
baseURL:
process.env.NODE_ENV === "development"
? "http://localhost:3000"
: undefined,
plugins: [
passkeyClient(),
twoFactorClient({
twoFactorPage: "/two-factor",
}),
],
});
```
--------------------------------
### Initialize Svelte Auth Client
Source: https://context7.com/better-auth/examples/llms.txt
Sets up the auth client for SvelteKit applications.
```typescript
// lib/auth-client.ts
import { createAuthClient } from "better-auth/svelte";
export const client = createAuthClient({
baseURL: "http://localhost:3000",
});
export const { signIn, signUp, useSession } = client;
```
--------------------------------
### Configure Basic Auth with Email and Social Providers
Source: https://context7.com/better-auth/examples/llms.txt
Initializes the Better Auth server with SQLite, email/password authentication, and multiple social OAuth providers.
```typescript
// auth.ts
import { betterAuth } from "better-auth";
import Database from "better-sqlite3";
export const auth = betterAuth({
database: new Database("./db.sqlite"),
emailAndPassword: {
enabled: true,
async sendResetPassword(url, user) {
console.log("Reset password url:", url);
// Send email with password reset link
},
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
},
github: {
clientId: process.env.GITHUB_CLIENT_ID || "",
clientSecret: process.env.GITHUB_CLIENT_SECRET || "",
},
discord: {
clientId: process.env.DISCORD_CLIENT_ID || "",
clientSecret: process.env.DISCORD_CLIENT_SECRET || "",
},
},
account: {
accountLinking: {
enabled: true,
trustedProviders: ["google"],
},
},
rateLimit: {
enabled: true,
},
});
```
--------------------------------
### Build Docker Image
Source: https://github.com/better-auth/examples/blob/main/react-router-example/README.md
Builds a Docker image for the application with the tag 'my-app'. Ensure you are in the project's root directory.
```bash
docker build -t my-app .
```
--------------------------------
### Create Production Build
Source: https://github.com/better-auth/examples/blob/main/react-router-example/README.md
Generates an optimized production build of the application. The output will be placed in the 'build/' directory.
```bash
npm run build
```
--------------------------------
### Initialize Vue/Nuxt Auth Client
Source: https://context7.com/better-auth/examples/llms.txt
Sets up the auth client for Vue and Nuxt applications.
```typescript
// lib/auth-client.ts
import { createAuthClient } from "better-auth/vue";
export const authClient = createAuthClient();
export const {
signIn,
signOut,
signUp,
useSession,
requestPasswordReset,
resetPassword
} = authClient;
```
--------------------------------
### Initialize React Auth Client
Source: https://context7.com/better-auth/examples/llms.txt
Sets up the auth client for React applications with passkey and 2FA support.
```typescript
// lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
import { twoFactorClient } from "better-auth/client/plugins";
import { passkeyClient } from "@better-auth/passkey/client";
export const authClient = createAuthClient({
baseURL: "http://localhost:3000",
plugins: [passkeyClient(), twoFactorClient()],
});
export const { signIn, signUp, signOut, useSession, twoFactor } = authClient;
```
--------------------------------
### Generate or Migrate Database Schema
Source: https://github.com/better-auth/examples/blob/main/nextjs-mcp/README.md
Run the CLI command to generate or migrate the necessary database schemas for Better Auth.
```bash
npx @better-auth/cli generate ## or (migrate)
```
--------------------------------
### Email/Password Sign Up
Source: https://context7.com/better-auth/examples/llms.txt
Registers a new user with credentials and an optional profile image converted to base64.
```typescript
import { signUp } from "@/libs/auth-client";
// Convert image to base64 for storage
const convertImageToBase64 = (file: File): Promise => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
});
};
// Sign up new user
await signUp.email({
name: "John Doe",
email: "john@example.com",
password: "securepassword",
image: imageFile ? await convertImageToBase64(imageFile) : undefined,
callbackURL: "/",
fetchOptions: {
onError: (context) => {
alert(context.error.message);
},
onSuccess: (context) => {
window.location.href = "/";
},
},
});
```
--------------------------------
### Configure Auth with Two-Factor and Passkey Plugins
Source: https://context7.com/better-auth/examples/llms.txt
Extends the base configuration by adding passkey support and two-factor authentication with custom OTP delivery logic.
```typescript
// auth.ts
import { betterAuth } from "better-auth";
import { passkey } from "better-auth/plugins/passkey";
import { twoFactor } from "better-auth/plugins";
import Database from "better-sqlite3";
export const auth = betterAuth({
database: new Database("./db.sqlite"),
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
},
plugins: [
passkey(),
twoFactor({
otpOptions: {
async sendOTP(user, otp) {
console.log(`Sending OTP to ${user.email}: ${otp}`);
// Integrate with email service like Resend
// await resend.emails.send({
// from: "Acme ",
// to: user.email,
// subject: "Your OTP",
// html: `Your OTP is ${otp}`,
// });
},
},
}),
],
});
```
--------------------------------
### Migrate Database Tables
Source: https://github.com/better-auth/examples/blob/main/tanstack-example/README.md
Execute this command to migrate the necessary database tables for Better Auth using the CLI.
```bash
pnpx @better-auth/cli migrate
```
--------------------------------
### Configure Better Auth with MCP Plugin
Source: https://github.com/better-auth/examples/blob/main/nextjs-mcp/README.md
Initialize the Better Auth instance with the MCP plugin, specifying the login page path.
```ts
// auth.ts
import { betterAuth } from "better-auth";
import { mcp } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
mcp({
loginPage: "/sign-in" // path to a page where users login
})
]
})
```
--------------------------------
### Configure Expo Auth Client
Source: https://context7.com/better-auth/examples/llms.txt
Sets up the auth client for React Native/Expo applications using SecureStore for persistent storage.
```typescript
// lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
import { expoClient } from "@better-auth/expo/client";
import * as SecureStore from "expo-secure-store";
export const authClient = createAuthClient({
baseURL: "http://localhost:8081",
disableDefaultFetchPlugins: true,
plugins: [
expoClient({
scheme: "better-auth",
storage: SecureStore,
}),
],
});
```
--------------------------------
### Configure Better Auth with MCP Plugin
Source: https://context7.com/better-auth/examples/llms.txt
Initializes the Better Auth instance with the MCP plugin for OAuth discovery and authenticated handlers.
```typescript
// lib/auth.ts
import { betterAuth } from "better-auth";
import { mcp } from "better-auth/plugins";
import Database from "better-sqlite3";
export const auth = betterAuth({
database: new Database("./auth.db"),
baseURL: "http://localhost:3000",
plugins: [
mcp({
loginPage: "/login",
}),
],
emailAndPassword: {
enabled: true,
},
});
```
--------------------------------
### Authenticate with Email and Password
Source: https://context7.com/better-auth/examples/llms.txt
Performs user sign-in with email and password, including lifecycle hooks for UI state management.
```typescript
// React/Solid component
import { signIn } from "@/libs/auth-client";
// Sign in with email and password
await signIn.email({
email: "user@example.com",
password: "securepassword",
rememberMe: true,
callbackURL: "/dashboard",
fetchOptions: {
onRequest: () => {
// Show loading state
},
onResponse: () => {
// Hide loading state
},
onError: (ctx) => {
console.error(ctx.error.message);
// Handle error (show toast, alert, etc.)
},
onSuccess: async () => {
// Redirect or update UI
window.location.href = "/dashboard";
},
},
});
```
--------------------------------
### Environment Variables for Better Auth in Astro
Source: https://github.com/better-auth/examples/blob/main/astro-example/README.md
Configure these environment variables in your .env file to enable social sign-in with Google and GitHub. Ensure the callback URLs are correctly set in your provider's developer console.
```txt
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
BETTER_AUTH_SECRET=
```
--------------------------------
### Implement OAuth Discovery Metadata for MCP
Source: https://context7.com/better-auth/examples/llms.txt
Exposes OAuth discovery metadata via a route handler.
```typescript
// .well-known/oauth-authorization-server/route.ts
import { oAuthDiscoveryMetadata } from "better-auth/plugins";
import { auth } from "../../../lib/auth";
export const GET = oAuthDiscoveryMetadata(auth);
```
--------------------------------
### Implement React Router Loader and Action
Source: https://context7.com/better-auth/examples/llms.txt
Handles authentication requests via React Router loaders and actions.
```typescript
// app/routes/api.auth.$.ts
import { auth } from "../lib/auth";
export async function loader({ request }: { request: Request }) {
return auth.handler(request);
}
export async function action({ request }: { request: Request }) {
return auth.handler(request);
}
```
--------------------------------
### Configure Better Auth for Expo
Source: https://context7.com/better-auth/examples/llms.txt
Sets up authentication for React Native/Expo using PostgreSQL and the expo plugin.
```typescript
// lib/auth.ts
import { betterAuth } from "better-auth";
import { expo } from "@better-auth/expo";
import { Pool } from "pg";
export const auth = betterAuth({
database: new Pool({
connectionString: process.env.DATABASE_URL,
}),
emailAndPassword: {
enabled: true,
},
plugins: [expo()],
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
google: {
clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
trustedOrigins: ["exp://"],
});
```
--------------------------------
### Expose OAuth Discovery Metadata
Source: https://github.com/better-auth/examples/blob/main/nextjs-mcp/README.md
Create a route to expose OAuth discovery metadata using the oAuthDiscoveryMetadata helper.
```ts
// .well-known/oauth-authroization-server/route.ts
import { oAuthDiscoveryMetadata } from "better-auth/plugins";
import { auth } from "../../../lib/auth";
export const GET = oAuthDiscoveryMetadata(auth);
```
--------------------------------
### List User Passkeys
Source: https://context7.com/better-auth/examples/llms.txt
Retrieves and renders a list of passkeys registered to the current user.
```typescript
import { useListPasskeys } from "@/libs/auth-client";
function PasskeyList() {
const passkeys = useListPasskeys();
return (
{passkeys().data?.map((passkey) => (
- {passkey.name || "My Passkey"}
))}
);
}
```
--------------------------------
### List Active Sessions (Server-side)
Source: https://context7.com/better-auth/examples/llms.txt
Fetches all active sessions for the current user on the server.
```typescript
// Astro page
---
import { auth } from "@/auth";
const activeSessions = await auth.api
.listSessions({
headers: Astro.request.headers,
})
.catch((e) => {
return [];
});
---
```
--------------------------------
### Passkey Authentication
Source: https://context7.com/better-auth/examples/llms.txt
Initiates passwordless authentication using WebAuthn passkeys.
```typescript
import { signIn } from "@/libs/auth-client";
// Sign in with passkey
await signIn.passkey({
fetchOptions: {
onError: (context) => {
alert(context.error.message);
},
onSuccess: (context) => {
window.location.href = "/dashboard";
},
},
});
```
--------------------------------
### Social Sign In
Source: https://context7.com/better-auth/examples/llms.txt
Authenticates users via OAuth providers like GitHub, Google, or Discord.
```typescript
import { signIn } from "@/libs/auth-client";
// Sign in with GitHub
await signIn.social({
provider: "github",
callbackURL: "/dashboard",
});
// Sign in with Google
await signIn.social({
provider: "google",
callbackURL: "/dashboard",
});
// Sign in with Discord
await signIn.social({
provider: "discord",
callbackURL: "/dashboard",
});
```
--------------------------------
### Mount Next.js Auth Handlers
Source: https://github.com/better-auth/examples/blob/main/nextjs-mcp/README.md
Expose the authentication handlers by mounting them to a Next.js route.
```ts
// api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);
```
--------------------------------
### Use Session (Client-side)
Source: https://context7.com/better-auth/examples/llms.txt
Accesses session data reactively within React or Solid.js components.
```typescript
// React component
import { useSession } from "@/libs/auth-client";
function Dashboard() {
const { data: session, isPending } = useSession();
if (isPending) return Loading...
;
if (!session) return Not authenticated
;
return (
Welcome, {session.user.name}
Email: {session.user.email}
);
}
```
```typescript
// Solid.js component
import { useSession } from "@/libs/auth-client";
import { Show, createEffect, createSignal } from "solid-js";
function Dashboard() {
const sessionResource = useSession();
const [session, setSession] = createSignal(null);
createEffect(() => {
setSession(sessionResource().data);
});
return (
Loading...}>
Welcome, {session()?.user.name}
Email: {session()?.user.email}
);
}
```
--------------------------------
### Send and Verify Email OTP
Source: https://context7.com/better-auth/examples/llms.txt
Implements a two-step process to send an OTP to an email and verify it.
```typescript
import { twoFactorActions } from "@/libs/auth-client";
// Send OTP to user's email
await twoFactorActions.sendOtp({
fetchOptions: {
onSuccess: () => {
// Show OTP input field
},
onError: (context) => {
alert(context.error.message);
},
},
});
// Verify the email OTP
await twoFactorActions.verifyOtp({
code: "123456",
fetchOptions: {
onError: (context) => {
alert(context.error.message);
},
onSuccess: () => {
window.location.href = "/dashboard";
},
},
});
```
--------------------------------
### Create Authenticated MCP Route Handler
Source: https://context7.com/better-auth/examples/llms.txt
Wraps MCP handlers with authentication checks and defines server tools.
```typescript
// api/[transport]/route.ts
import { auth } from "@/lib/auth";
import { createMcpHandler } from "@vercel/mcp-adapter";
import { withMcpAuth } from "better-auth/plugins";
import { z } from "zod";
const handler = withMcpAuth(auth, (req, session) => {
// session contains access token, scopes, and user ID
return createMcpHandler(
(server) => {
server.tool(
"echo",
"Echo a message",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `Tool echo: ${message}` }],
};
}
);
},
{
capabilities: {
tools: {
echo: {
description: "Echo a message",
},
},
},
},
{
redisUrl: process.env.REDIS_URL,
basePath: "/api",
verboseLogs: true,
maxDuration: 60,
}
)(req);
});
export { handler as GET, handler as POST, handler as DELETE };
```
--------------------------------
### Implement Authenticated MCP Handler
Source: https://github.com/better-auth/examples/blob/main/nextjs-mcp/README.md
Use withMcpAuth to protect MCP tools and handle session validation automatically.
```ts
import { auth } from "@/lib/auth";
import { createMcpHandler } from "@vercel/mcp-adapter";
import { withMcpAuth } from "better-auth/plugins";
import { z } from "zod";
const handler = withMcpAuth(auth, (req, session) => {
//session => This isn’t a typical Better Auth session - instead, it returns the access token record along with the scopes and user ID.
return createMcpHandler(
(server) => {
server.tool(
"echo",
"Echo a message",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `Tool echo: ${message}` }],
};
},
);
},
{
capabilities: {
tools: {
echo: {
description: "Echo a message",
},
},
},
},
{
redisUrl: process.env.REDIS_URL,
basePath: "/api",
verboseLogs: true,
maxDuration: 60,
},
)(req);
});
export { handler as GET, handler as POST, handler as DELETE };
```
--------------------------------
### Enable Two-Factor Authentication
Source: https://context7.com/better-auth/examples/llms.txt
Enables TOTP-based 2FA for a user account, requiring password verification.
```typescript
import { twoFactorActions } from "@/libs/auth-client";
// Enable 2FA with password verification
await twoFactorActions.enable({
password: "userpassword",
fetchOptions: {
onResponse: (context) => {
// Hide loading state
},
onError: (context) => {
alert(context.error.message);
},
onSuccess: () => {
alert("Two factor successfully enabled!");
},
},
});
```
--------------------------------
### Add a New Passkey
Source: https://context7.com/better-auth/examples/llms.txt
Registers a new WebAuthn passkey with an optional display name.
```typescript
import { passkeyActions } from "@/libs/auth-client";
// Add passkey with optional name
const res = await passkeyActions.addPasskey({
name: "My Laptop Passkey",
fetchOptions: {
onSuccess: () => {
alert("Successfully added passkey");
},
},
});
if (res?.error) {
alert(res.error.message);
}
```
--------------------------------
### Integrate SvelteKit Hooks Handler
Source: https://context7.com/better-auth/examples/llms.txt
Handles authentication requests within SvelteKit server hooks, including protected route validation.
```typescript
// hooks.server.ts
import { auth } from "$lib/auth";
import { redirect, type Handle } from "@sveltejs/kit";
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from "$app/environment";
export const handle: Handle = async ({ event, resolve }) => {
if (event.route.id?.startsWith("/(protected)/")) {
const session = await auth.api.getSession({
headers: event.request.headers,
});
if (session) {
event.locals.session = session?.session;
event.locals.user = session?.user;
return svelteKitHandler({ event, resolve, auth, building });
} else {
redirect(307, "/sign-in");
}
} else {
return svelteKitHandler({ event, resolve, auth, building });
}
};
```
--------------------------------
### Update User Profile
Source: https://context7.com/better-auth/examples/llms.txt
Updates user profile details, including converting image files to base64 strings.
```typescript
import { updateUser } from "@/libs/auth-client";
const convertImageToBase64 = (file: File): Promise => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
});
};
await updateUser({
name: "New Name",
image: imageFile ? await convertImageToBase64(imageFile) : undefined,
fetchOptions: {
onResponse: (context) => {
// Hide loading state
},
onError: (context) => {
alert(context.error.message);
},
onSuccess: () => {
alert("User Updated Successfully");
},
},
});
```
--------------------------------
### Create Nuxt Global Middleware
Source: https://context7.com/better-auth/examples/llms.txt
Implements global route middleware in Nuxt to check session status.
```typescript
// middleware/auth.global.ts
import { authClient } from "~/lib/auth-client";
export default defineNuxtRouteMiddleware(async (to, from) => {
const { data: session } = await authClient.useSession(useFetch);
if (!session.value) {
if (to.path === "/dashboard") {
return navigateTo("/");
}
}
});
```
--------------------------------
### Protect Astro Routes with Middleware
Source: https://context7.com/better-auth/examples/llms.txt
Uses Astro middleware to validate sessions and redirect unauthenticated users.
```typescript
// middleware.ts
import { auth } from "@/auth";
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware(async (context, next) => {
const isAuthed = await auth.api
.getSession({
headers: context.request.headers,
})
.catch((e) => {
return null;
});
if (context.url.pathname === "/dashboard" && !isAuthed) {
return context.redirect("/");
}
return next();
});
```
--------------------------------
### Password Reset Flow
Source: https://context7.com/better-auth/examples/llms.txt
Handles the two-step password reset process: requesting a reset email and applying the new password.
```typescript
import { requestPasswordReset, resetPassword } from "@/libs/auth-client";
// Request password reset email
await requestPasswordReset({
email: "user@example.com",
});
// Reset password with token from email
await resetPassword({
token: "reset-token-from-email",
newPassword: "newsecurepassword",
});
```
--------------------------------
### Sign Out
Source: https://context7.com/better-auth/examples/llms.txt
Terminates the current user session, with options for simple or error-handled sign-out.
```typescript
import { authClient, signOut } from "@/libs/auth-client";
// Simple sign out
await signOut();
window.location.reload();
// Sign out with error handling
authClient.signOut().then(({ data, error }) => {
if (error) {
toast.error(error.message);
} else {
toast.success("You've been signed out");
}
});
```
--------------------------------
### Verify TOTP Code
Source: https://context7.com/better-auth/examples/llms.txt
Handles TOTP verification with specific error handling for rate limiting.
```typescript
import { twoFactorActions } from "@/libs/auth-client";
// Verify 6-digit TOTP code
await twoFactorActions.verifyTotp({
code: "123456",
fetchOptions: {
onError: (context) => {
if (context.error.status === 429) {
const retryAfter = context.response.headers.get("X-Retry-After");
alert(`Too many requests. Please try again after ${retryAfter} seconds`);
} else {
alert(context.error.message);
}
},
onSuccess: () => {
window.location.href = "/dashboard";
},
},
});
```
--------------------------------
### Disable Two-Factor Authentication
Source: https://context7.com/better-auth/examples/llms.txt
Requires the user's password to confirm the action.
```typescript
import { twoFactorActions } from "@/libs/auth-client";
await twoFactorActions.disable({
password: "userpassword",
fetchOptions: {
onError: (context) => {
alert(context.error.message);
},
onSuccess: () => {
alert("Two factor is disabled!");
},
},
});
```
--------------------------------
### Delete a Passkey
Source: https://context7.com/better-auth/examples/llms.txt
Removes a specific passkey by its ID.
```typescript
import { passkeyActions } from "@/libs/auth-client";
await passkeyActions.deletePasskey({
id: passkey.id,
fetchOptions: {
onRequest: () => {
// Show loading state
},
onSuccess: () => {
alert("Passkey deleted successfully");
},
onError: (error) => {
alert(error.error.message);
},
},
});
```
--------------------------------
### Revoke Session
Source: https://context7.com/better-auth/examples/llms.txt
Terminates a specific user session using its token.
```typescript
import { revokeSession } from "@/libs/auth-client";
// Revoke a specific session
const res = await revokeSession({
token: session.token,
});
if (res.error) {
alert(res.error.message);
} else {
alert("Session terminated");
window.location.reload();
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.