========================
CODE SNIPPETS
========================
TITLE: SvelteKit Example Setup
DESCRIPTION: Instructions on how to set up and run the Better Auth SvelteKit example. This includes cloning the repository, configuring environment variables, installing dependencies, and starting the development server.
SOURCE: https://www.better-auth.com/docs/examples/svelte-kit
LANGUAGE: bash
CODE:
```
pnpm install
pnpm dev
```
----------------------------------------
TITLE: Next.js Example Setup
DESCRIPTION: Instructions for setting up and running the Better Auth Next.js example. This includes cloning the repository, configuring environment variables, installing dependencies, and starting the development server.
SOURCE: https://www.better-auth.com/docs/examples/next-js
LANGUAGE: bash
CODE:
```
pnpm install
pnpm dev
```
----------------------------------------
TITLE: Nuxt.js Example Setup and Run
DESCRIPTION: This snippet demonstrates how to set up and run a Nuxt.js project integrated with Better Auth. It covers cloning the project, configuring environment variables, installing dependencies, and starting the development server. The example features email/password and Google social sign-in.
SOURCE: https://www.better-auth.com/docs/examples/nuxt
LANGUAGE: bash
CODE:
```
pnpm install
pnpm dev
```
----------------------------------------
TITLE: Astro Example Setup
DESCRIPTION: Instructions on how to set up and run the Astro example for Better Auth. This includes cloning the repository, configuring environment variables, and installing dependencies.
SOURCE: https://www.better-auth.com/docs/examples/astro
LANGUAGE: bash
CODE:
```
pnpm install
pnpm run dev
```
----------------------------------------
TITLE: Run Remix Example with Better Auth
DESCRIPTION: Instructions on how to set up and run the Better Auth Remix example. This includes cloning the repository, configuring environment variables, and installing dependencies.
SOURCE: https://www.better-auth.com/docs/examples/remix
LANGUAGE: bash
CODE:
```
pnpm install
pnpm run dev
```
----------------------------------------
TITLE: TanStack Start Server Setup
DESCRIPTION: This snippet demonstrates the basic server setup for TanStack Start, which is necessary for integrating custom handlers like Better Auth.
SOURCE: https://www.better-auth.com/docs/integrations/tanstack
LANGUAGE: javascript
CODE:
```
import {
createStartHandler,
defaultStreamHandler,
} from '@tanstack/react-start/server'
import { createRouter } from './router'
export default createStartHandler({
createRouter,
})(defaultStreamHandler)
```
----------------------------------------
TITLE: Install Prisma Client and Prisma CLI
DESCRIPTION: Installs the Prisma client for database interactions and the Prisma CLI for database management.
SOURCE: https://www.better-auth.com/docs/integrations/nitro
LANGUAGE: bash
CODE:
```
npm install @prisma/client
npm install -D prisma
```
----------------------------------------
TITLE: Initialize Plasmo Project and Install Better Auth
DESCRIPTION: Commands to create a new Plasmo project with TailwindCSS and install the Better Auth package.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: bash
CODE:
```
pnpm create plasmo --with-tailwindcss --with-src
pnpm add better-auth
pnpm dev
```
----------------------------------------
TITLE: Create and Install Nitro Application
DESCRIPTION: Scaffolds a new Nitro application and installs its dependencies using Giget.
SOURCE: https://www.better-auth.com/docs/integrations/nitro
LANGUAGE: bash
CODE:
```
npx giget@latest nitro nitro-app --install
```
----------------------------------------
TITLE: Setup Social Providers (GitHub Example)
DESCRIPTION: Sets up social login providers for Better Auth, using GitHub as an example with client ID and secret configuration.
SOURCE: https://www.better-auth.com/docs/guides/supabase-migration-guide
LANGUAGE: typescript
CODE:
```
import { admin, anonymous } from "better-auth/plugins";
export const auth = betterAuth({
database: new Pool({
connectionString: process.env.DATABASE_URL
}),
emailAndPassword: {
enabled: true,
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}
}
})
```
----------------------------------------
TITLE: Start Development Server
DESCRIPTION: Commands to start the local development server for BetterAuth. One command starts the main application, and the other specifically starts the documentation server.
SOURCE: https://www.better-auth.com/docs/reference/contributing
LANGUAGE: shell
CODE:
```
pnpm dev
pnpm -F docs dev
```
----------------------------------------
TITLE: Initialize Prisma and Configure Schema
DESCRIPTION: Initializes Prisma in the project and sets up the schema.prisma file for a SQLite database and Prisma client generation. Includes an example model and database URL configuration.
SOURCE: https://www.better-auth.com/docs/integrations/nitro
LANGUAGE: bash
CODE:
```
npx prisma init
```
LANGUAGE: prisma
CODE:
```
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
// Will be deleted. Just need it to generate the prisma client
model Test {
id Int @id @default(autoincrement())
name String
}
```
LANGUAGE: dotenv
CODE:
```
DATABASE_URL="file:./dev.db"
```
LANGUAGE: bash
CODE:
```
npx prisma db push
```
----------------------------------------
TITLE: Install Better Auth
DESCRIPTION: Installs the Better Auth package using npm. This is the initial step before using the client library.
SOURCE: https://www.better-auth.com/docs/concepts/client
LANGUAGE: bash
CODE:
```
npm i better-auth
```
----------------------------------------
TITLE: Configure Dub Plugin
DESCRIPTION: Example of how to configure the Dub plugin within the Better Auth setup, including initializing the Dub client.
SOURCE: https://www.better-auth.com/docs/plugins/dub
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { dubAnalytics } from "@dub/better-auth"
import { dub } from "dub"
export const auth = betterAuth({
plugins: [
dubAnalytics({
dubClient: new Dub()
})
]
})
```
----------------------------------------
TITLE: Setup Social Providers (GitHub Example)
DESCRIPTION: Configures Better Auth to use social providers for authentication, using GitHub as an example. Requires client ID and secret from the provider.
SOURCE: https://www.better-auth.com/docs/guides/clerk-migration-guide
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: new Pool({
connectionString: process.env.DATABASE_URL
}),
emailAndPassword: {
enabled: true,
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}
}
})
```
----------------------------------------
TITLE: Install Dub Plugin and SDK
DESCRIPTION: Instructions for installing the Better Auth Dub plugin and the Dub SDK using npm, yarn, or bun.
SOURCE: https://www.better-auth.com/docs/plugins/dub
LANGUAGE: npm
CODE:
```
npm install @dub/better-auth
```
LANGUAGE: npm
CODE:
```
npm install dub
```
LANGUAGE: yarn
CODE:
```
yarn add @dub/better-auth
```
LANGUAGE: yarn
CODE:
```
yarn add dub
```
LANGUAGE: bun
CODE:
```
bun add @dub/better-auth
```
LANGUAGE: bun
CODE:
```
bun add dub
```
----------------------------------------
TITLE: Client-side Sign In with Better Auth
DESCRIPTION: Example of performing a client-side sign-in using the Better Auth SDK within a TanStack Start application, leveraging the configured auth instance.
SOURCE: https://www.better-auth.com/docs/integrations/tanstack
LANGUAGE: javascript
CODE:
```
import { auth } from "@/lib/auth"
const signIn = async () => {
await auth.api.signInEmail({
body: {
email: "user@email.com",
password: "password",
}
})
}
```
----------------------------------------
TITLE: Install Bearer Plugin
DESCRIPTION: Demonstrates how to install and configure the Bearer plugin within the Better Auth setup. This plugin enables authentication using Bearer tokens.
SOURCE: https://www.better-auth.com/docs/plugins/bearer
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { bearer } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [bearer()]
});
```
----------------------------------------
TITLE: Install Fastify and CORS Dependencies
DESCRIPTION: Installs the necessary Fastify and CORS packages for integration. Ensure Node.js v16+ and ES Module support are enabled.
SOURCE: https://www.better-auth.com/docs/integrations/fastify
LANGUAGE: bash
CODE:
```
npm install fastify @fastify/cors
```
----------------------------------------
TITLE: Install SSO Plugin
DESCRIPTION: Installs the SSO plugin for Better Auth using npm. This is the first step in integrating SSO capabilities.
SOURCE: https://www.better-auth.com/docs/plugins/sso
LANGUAGE: bash
CODE:
```
npm install @better-auth/sso
```
----------------------------------------
TITLE: SQLite Example Usage
DESCRIPTION: Demonstrates how to connect Better Auth to a SQLite database using the `better-sqlite3` library. Ensure SQLite is installed and configured before use.
SOURCE: https://www.better-auth.com/docs/adapters/sqlite
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import Database from "better-sqlite3";
export const auth = betterAuth({
database: new Database("database.sqlite"),
});
```
----------------------------------------
TITLE: Stripe Plugin Configuration
DESCRIPTION: Example of how to configure the Stripe plugin within the Better Auth setup. This includes initializing the Stripe client and providing necessary secrets and options.
SOURCE: https://www.better-auth.com/docs/plugins/stripe
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { stripe } from "@better-auth/stripe"
import Stripe from "stripe"
const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2025-02-24.acacia",
})
export const auth = betterAuth({
// ... your existing config
plugins: [
stripe({
stripeClient,
stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
createCustomerOnSignUp: true,
})
]
})
```
----------------------------------------
TITLE: Debug Logs Configuration Examples
DESCRIPTION: Examples demonstrating how to configure debug logs for a Better Auth database adapter. This includes enabling logs for all methods or selectively enabling them for specific methods.
SOURCE: https://www.better-auth.com/docs/guides/create-a-db-adapter
LANGUAGE: javascript
CODE:
```
// Will log debug logs for all methods.
const adapter = myAdapter({
debugLogs: true,
});
```
LANGUAGE: javascript
CODE:
```
// Will only log debug logs for the `create` and `update` methods.
const adapter = myAdapter({
debugLogs: {
create: true,
update: true,
},
});
```
----------------------------------------
TITLE: SSO Client-Side Sign-In Example
DESCRIPTION: Provides a JavaScript example of using the `authClient.signIn.sso` method to initiate an SSO login. It shows how to pass various parameters like email, organization slug, provider details, and callback URLs.
SOURCE: https://www.better-auth.com/docs/plugins/sso
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.signIn.sso({
email: "john@example.com",
organizationSlug: "example-org",
providerId: "example-provider",
domain: "example.com",
callbackURL: "https://example.com/callback", // required
errorCallbackURL: "https://example.com/callback",
newUserCallbackURL: "https://example.com/new-user",
scopes: ["openid", "email", "profile", "offline_access"],
requestSignUp: true,
});
```
----------------------------------------
TITLE: List User Sessions Example
DESCRIPTION: Example of how to list all sessions for a specific user.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.admin.listUserSessions({
userId: "user-id", // required
});
```
----------------------------------------
TITLE: MCP Plugin Installation
DESCRIPTION: Demonstrates how to install and configure the MCP plugin for Better Auth, including setting the login page path.
SOURCE: https://www.better-auth.com/docs/plugins/mcp
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { mcp } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
mcp({
loginPage: "/sign-in" // path to your login page
})
]
});
```
----------------------------------------
TITLE: Install Better Auth
DESCRIPTION: Installs the Better Auth package using npm or yarn. It's recommended to install it in both client and server parts of a project if they are separate.
SOURCE: https://www.better-auth.com/docs/installation
LANGUAGE: bash
CODE:
```
npm install better-auth
```
LANGUAGE: bash
CODE:
```
yarn add better-auth
```
----------------------------------------
TITLE: Username Plugin Installation (Client)
DESCRIPTION: This snippet demonstrates how to install the username plugin for the Better Auth client. It involves creating an auth client and including the client-side username plugin.
SOURCE: https://www.better-auth.com/docs/plugins/username
LANGUAGE: typescript
CODE:
```
import { createAuthClient } from "better-auth/client"
import { usernameClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
usernameClient()
]
})
```
----------------------------------------
TITLE: Install DodoPayments Better Auth Dependencies
DESCRIPTION: Installs the necessary npm packages for integrating DodoPayments with Better Auth.
SOURCE: https://www.better-auth.com/docs/plugins/dodopayments
LANGUAGE: bash
CODE:
```
npm install @dodopayments/better-auth dodopayments better-auth zod
```
----------------------------------------
TITLE: Google Provider Setup and Usage
DESCRIPTION: Instructions for setting up and using the Google authentication provider with Better Auth.
SOURCE: https://www.better-auth.com/docs/authentication/github
LANGUAGE: en
CODE:
```
Refer to the documentation for Google provider setup and usage.
```
----------------------------------------
TITLE: Pluralization Configuration Example
DESCRIPTION: An example showing how to configure the `usePlural` option when creating a database adapter, which affects how table names are handled.
SOURCE: https://www.better-auth.com/docs/guides/create-a-db-adapter
LANGUAGE: javascript
CODE:
```
const adapter = myAdapter({
// This value then gets passed into the `usePlural`
// option in the createAdapter `config` object.
usePlural: true,
});
```
----------------------------------------
TITLE: Stripe Plugin Installation
DESCRIPTION: Instructions for installing the Stripe plugin for Better Auth and the Stripe SDK. It covers both npm and yarn package managers.
SOURCE: https://www.better-auth.com/docs/plugins/stripe
LANGUAGE: bash
CODE:
```
npm install @better-auth/stripe
yarn add @better-auth/stripe
bun add @better-auth/stripe
```
LANGUAGE: bash
CODE:
```
npm install stripe@^18.0.0
yarn add stripe@^18.0.0
bun add stripe@^18.0.0
```
----------------------------------------
TITLE: Sign In with GitHub
DESCRIPTION: Provides an example of how to initiate the sign-in process with GitHub using the Better Auth client. This function requires specifying 'github' as the provider.
SOURCE: https://www.better-auth.com/docs/authentication/github
LANGUAGE: javascript
CODE:
```
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient()
const signIn = async () => {
const data = await authClient.signIn.social({
provider: "github"
})
}
```
----------------------------------------
TITLE: Migrating from NextAuth.js to Better Auth
DESCRIPTION: A step-by-step guide to help users transition their authentication setup from NextAuth.js to Better Auth. This guide aims to simplify the migration process.
SOURCE: https://www.better-auth.com/docs/plugins/community-plugins
LANGUAGE: APIDOC
CODE:
```
### Migrating from NextAuth.js to Better Auth
A step-by-step guide to transitioning from NextAuth.js to Better Auth.
https://www.better-auth.com/docs/guides/next-auth-migration-guide
```
----------------------------------------
TITLE: Configure Manifest for Better Auth Host Permissions
DESCRIPTION: Example of how to add host permissions to the package.json manifest file for Better Auth integration in a browser extension.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: json
CODE:
```
{
//...
"manifest": {
"host_permissions": [
"https://URL_TO_YOUR_BACKEND" // localhost works too (e.g. http://localhost:3000)
]
}
}
```
----------------------------------------
TITLE: Better Auth Initialization with SSO Plugin
DESCRIPTION: Demonstrates the basic setup of the Better Auth library, including the integration of the SSO plugin. It shows how to configure the `provisionUser` function for custom user provisioning logic.
SOURCE: https://www.better-auth.com/docs/plugins/sso
LANGUAGE: javascript
CODE:
```
const auth = betterAuth({
plugins: [
sso({
provisionUser: async (user) => {
// provision user
},
organizationProvisioning: {
disabled: false,
defaultRole: "member",
getRole: async (user) => {
// get role if needed
},
},
}),
],
});
```
----------------------------------------
TITLE: Configure Server Auth Instance
DESCRIPTION: Configuration for the server-side authentication instance, specifying trusted origins for browser extensions. Includes examples for specific extension IDs and wildcard patterns.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { auth } from "@/auth/auth"
export const auth = betterAuth({
trustedOrigins: ["chrome-extension://YOUR_EXTENSION_ID"],
})
```
LANGUAGE: typescript
CODE:
```
export const auth = betterAuth({
trustedOrigins: [
// Support a specific extension ID
"chrome-extension://YOUR_EXTENSION_ID",
// Or support multiple extensions with wildcard (less secure)
"chrome-extension://*"
],
})
```
----------------------------------------
TITLE: Install Dependencies with pnpm
DESCRIPTION: Command to install all necessary project dependencies using the pnpm package manager. Ensure pnpm is installed globally before running this command.
SOURCE: https://www.better-auth.com/docs/reference/contributing
LANGUAGE: shell
CODE:
```
pnpm install
```
----------------------------------------
TITLE: MS SQL Example Usage
DESCRIPTION: Demonstrates how to configure and connect Better Auth to a Microsoft SQL Server database using Kysely and Tedious. It includes setup for connection pooling with Tarn.
SOURCE: https://www.better-auth.com/docs/adapters/mssql
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { MssqlDialect } from "kysely";
import * as Tedious from 'tedious'
import * as Tarn from 'tarn'
const dialect = new MssqlDialect({
tarn: {
...Tarn,
options: {
min: 0,
max: 10,
},
},
tedious: {
...Tedious,
connectionFactory: () => new Tedious.Connection({
authentication: {
options: {
password: 'password',
userName: 'username',
},
type: 'default',
},
options: {
database: 'some_db',
port: 1433,
trustServerCertificate: true,
},
server: 'localhost',
}),
},
})
export const auth = betterAuth({
database: {
dialect,
type: "mssql"
}
});
```
----------------------------------------
TITLE: Better Auth Example Usage (SvelteKit)
DESCRIPTION: Provides an example of using the Better Auth client within a Svelte component to manage user sessions. It shows how to display user information, handle sign-out, and initiate sign-in with providers like GitHub.
SOURCE: https://www.better-auth.com/docs/integrations/svelte-kit
LANGUAGE: svelte
CODE:
```
{#if $session.data}
{$session?.data?.user.name}
{:else}
{/if}
```
----------------------------------------
TITLE: Redis Secondary Storage Implementation
DESCRIPTION: An example implementation of the `SecondaryStorage` interface using the 'redis' package. This code connects to a Redis instance and provides the necessary `get`, `set`, and `delete` methods for Better Auth to use.
SOURCE: https://www.better-auth.com/docs/concepts/database
LANGUAGE: javascript
CODE:
```
import { createClient } from "redis";
import { betterAuth } from "better-auth";
const redis = createClient();
await redis.connect();
export const auth = betterAuth({
// ... other options
secondaryStorage: {
get: async (key) => {
const value = await redis.get(key);
return value ? value : null;
},
set: async (key, value, ttl) => {
if (ttl) await redis.set(key, value, { EX: ttl });
// or for ioredis:
// if (ttl) await redis.set(key, value, 'EX', ttl)
else await redis.set(key, value);
},
delete: async (key) => {
await redis.del(key);
}
}
});
```
----------------------------------------
TITLE: Install Admin Plugin
DESCRIPTION: This snippet shows how to install the Admin plugin for Better Auth by adding it to the auth configuration and migrating the database.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { admin } from "better-auth/plugins"
export const auth = betterAuth({
// ... other config options
plugins: [
admin()
]
})
```
LANGUAGE: bash
CODE:
```
npx @better-auth/cli migrate
```
LANGUAGE: typescript
CODE:
```
import { createAuthClient } from "better-auth/client"
import { adminClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
adminClient()
]
})
```
----------------------------------------
TITLE: Create Better Auth Client Instance
DESCRIPTION: TypeScript code to create a client instance for Better Auth, specifying the backend baseURL and an empty array of plugins.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: typescript
CODE:
```
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" /* Base URL of your Better Auth backend. */,
plugins: [],
});
```
----------------------------------------
TITLE: Prepare Environment Files
DESCRIPTION: Copies the example environment file to create a new .env file for local development. This is crucial for configuring the application's environment variables.
SOURCE: https://www.better-auth.com/docs/reference/contributing
LANGUAGE: shell
CODE:
```
cp -n ./docs/.env.example ./docs/.env
```
----------------------------------------
TITLE: Username Plugin Installation (Server)
DESCRIPTION: This snippet shows how to install the username plugin for the Better Auth server. It requires importing the plugin and adding it to the auth configuration.
SOURCE: https://www.better-auth.com/docs/plugins/username
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
username()
]
})
```
----------------------------------------
TITLE: Install pg package
DESCRIPTION: Installs the 'pg' package, which is required to connect to a PostgreSQL database using Node.js.
SOURCE: https://www.better-auth.com/docs/guides/supabase-migration-guide
LANGUAGE: bash
CODE:
```
npm install pg
```
----------------------------------------
TITLE: Accept Invitation Example
DESCRIPTION: Example of using the `acceptInvitation` function from the Better Auth client to accept an organization invitation.
SOURCE: https://www.better-auth.com/docs/plugins/organization
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.organization.acceptInvitation({
invitationId: "invitation-id", // required
});
```
----------------------------------------
TITLE: Implement Custom Rate Limit Storage
DESCRIPTION: Provides an example of implementing a custom storage solution for rate limit data by defining `get` and `set` asynchronous functions.
SOURCE: https://www.better-auth.com/docs/concepts/rate-limit
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
export const auth = betterAuth({
//...other options
rateLimit: {
customStorage: {
get: async (key) => {
// get rate limit data
},
set: async (key, value) => {
// set rate limit data
},
},
},
})
```
----------------------------------------
TITLE: Configure tsconfig.json for Better Auth
DESCRIPTION: Example tsconfig.json configuration for a Plasmo project using Better Auth, enabling strict mode and setting import aliases.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: json
CODE:
```
{
"compilerOptions": {
"paths": {
"@/_": [
"./src/_"
]
},
"strict": true,
"baseUrl": "."
}
}
```
----------------------------------------
TITLE: Facebook Provider Setup and Usage
DESCRIPTION: Instructions for setting up and using the Facebook authentication provider with Better Auth.
SOURCE: https://www.better-auth.com/docs/authentication/github
LANGUAGE: en
CODE:
```
Refer to the documentation for Facebook provider setup and usage.
```
----------------------------------------
TITLE: Better Auth Instance with TanStack Cookies
DESCRIPTION: This snippet shows how to initialize a Better Auth instance and include the `reactStartCookies` plugin for seamless cookie handling within TanStack Start applications.
SOURCE: https://www.better-auth.com/docs/integrations/tanstack
LANGUAGE: javascript
CODE:
```
import { betterAuth } from "better-auth";
import { reactStartCookies } from "better-auth/react-start";
export const auth = betterAuth({
//...your config
plugins: [reactStartCookies()] // make sure this is the last plugin in the array
})
```
----------------------------------------
TITLE: Set User Password Example
DESCRIPTION: Example of how to change a user's password using the Better Auth client.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.admin.setUserPassword({
newPassword: 'new-password', // required
userId: 'user-id', // required
});
```
----------------------------------------
TITLE: Invite Member Example
DESCRIPTION: Example of using the `inviteMember` function from the Better Auth client to invite a user to an organization.
SOURCE: https://www.better-auth.com/docs/plugins/organization
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.organization.inviteMember({
email: "example@gmail.com", // required
role: "member", // required
organizationId: "org-id",
resend: true,
teamId: "team-id",
});
```
----------------------------------------
TITLE: Fastify Authentication Handler Setup
DESCRIPTION: Configures a catch-all route in Fastify to handle authentication requests using Better Auth. It constructs a Fetch API-compatible request from Fastify's request object and forwards it to the Better Auth handler.
SOURCE: https://www.better-auth.com/docs/integrations/fastify
LANGUAGE: typescript
CODE:
```
import Fastify from "fastify";
import { auth } from "./auth"; // Your configured Better Auth instance
const fastify = Fastify({ logger: true });
// Register authentication endpoint
fastify.route({
method: ["GET", "POST"],
url: "/api/auth/*",
async handler(request, reply) {
try {
// Construct request URL
const url = new URL(request.url, `http://${request.headers.host}`);
// Convert Fastify headers to standard Headers object
const headers = new Headers();
Object.entries(request.headers).forEach(([key, value]) => {
if (value) headers.append(key, value.toString());
});
// Create Fetch API-compatible request
const req = new Request(url.toString(), {
method: request.method,
headers,
body: request.body ? JSON.stringify(request.body) : undefined,
});
// Process authentication request
const response = await auth.handler(req);
// Forward response to client
reply.status(response.status);
response.headers.forEach((value, key) => reply.header(key, value));
reply.send(response.body ? await response.text() : null);
} catch (error) {
fastify.log.error("Authentication Error:", error);
reply.status(500).send({
error: "Internal authentication error",
code: "AUTH_FAILURE"
});
}
}
});
// Initialize server
fastify.listen({ port: 4000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log("Server running on port 4000");
});
```
----------------------------------------
TITLE: Extend Client with Plugins (Magic Link Example)
DESCRIPTION: Demonstrates how to extend the Better Auth client's functionality by importing and using plugins, such as the 'magicLinkClient'.
SOURCE: https://www.better-auth.com/docs/concepts/client
LANGUAGE: typescript
CODE:
```
import { createAuthClient } from "better-auth/client"
import { magicLinkClient } from "better-auth/client/plugins"
const authClient = createAuthClient({
plugins: [
magicLinkClient()
]
})
await authClient.signIn.magicLink({
email: "test@email.com"
})
```
----------------------------------------
TITLE: Trust Device Client-Side Example
DESCRIPTION: Client-side JavaScript code demonstrating how to mark a device as trusted during 2FA verification.
SOURCE: https://www.better-auth.com/docs/plugins/2fa
LANGUAGE: javascript
CODE:
```
const verify2FA = async (code: string) => {
const { data, error } = await authClient.twoFactor.verifyTotp({
code,
callbackURL: "/dashboard",
trustDevice: true // Mark this device as trusted
})
if (data) {
// 2FA verified and device trusted
}
}
```
----------------------------------------
TITLE: Install Multi Session Plugin
DESCRIPTION: This snippet shows how to install the multi-session plugin by adding it to your auth configuration in auth.ts.
SOURCE: https://www.better-auth.com/docs/plugins/multi-session
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { multiSession } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
multiSession()
]
})
```
----------------------------------------
TITLE: Install Phone Number Plugin (Client)
DESCRIPTION: Shows how to integrate the phone number client plugin into the Better Auth client setup. This allows the client-side application to interact with the phone number authentication features.
SOURCE: https://www.better-auth.com/docs/plugins/phone-number
LANGUAGE: typescript
CODE:
```
import { createAuthClient } from "better-auth/client"
import { phoneNumberClient } from "better-auth/client/plugins"
const authClient = createAuthClient({
plugins: [
phoneNumberClient()
]
})
```
----------------------------------------
TITLE: Ban User Example
DESCRIPTION: Example of how to ban a user, including an optional reason and expiration.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
await authClient.admin.banUser({
userId: "user-id", // required
banReason: "Spamming",
banExpiresIn: 60 * 60 * 24 * 7, // Ban for 7 days
});
```
----------------------------------------
TITLE: Unban User Example
DESCRIPTION: Example of how to unban a user using the Better Auth client.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
await authClient.admin.unbanUser({
userId: "user-id", // required
});
```
----------------------------------------
TITLE: Build Browser Extension
DESCRIPTION: Command to generate a production build for the browser extension. This is typically run using a package manager like pnpm.
SOURCE: https://www.better-auth.com/docs/guides/browser-extension-guide
LANGUAGE: bash
CODE:
```
pnpm build
```
----------------------------------------
TITLE: Mount TanStack Start Handler
DESCRIPTION: This snippet shows how to mount the Better Auth handler to a TanStack API endpoint in a TanStack Start application. It handles both GET and POST requests.
SOURCE: https://www.better-auth.com/docs/integrations/tanstack
LANGUAGE: typescript
CODE:
```
import { auth } from '@/lib/auth' // import your auth instance
import { createServerFileRoute } from '@tanstack/react-start/server'
export const ServerRoute = createServerFileRoute('/api/auth/$').methods({
GET: ({ request }) => {
return auth.handler(request)
},
POST: ({ request }) => {
return auth.handler(request)
},
})
```
----------------------------------------
TITLE: Remove User Example
DESCRIPTION: Example of how to permanently delete a user from the system.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
const { data: deletedUser, error } = await authClient.admin.removeUser({
userId: "user-id", // required
});
```
----------------------------------------
TITLE: Prisma Adapter Example Usage
DESCRIPTION: Demonstrates how to integrate the Prisma adapter with Better Auth in a TypeScript application. It shows the necessary imports and configuration for connecting to a database using Prisma.
SOURCE: https://www.better-auth.com/docs/adapters/prisma
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "sqlite",
}),
});
```
----------------------------------------
TITLE: Better Auth Initialization with Secondary Storage
DESCRIPTION: Demonstrates how to initialize Better Auth by providing a custom secondary storage implementation. This example shows the structure for passing the implementation to the `betterAuth` function.
SOURCE: https://www.better-auth.com/docs/concepts/database
LANGUAGE: javascript
CODE:
```
betterAuth({
// ... other options
secondaryStorage: {
// Your implementation here
},
});
```
----------------------------------------
TITLE: Email and Password Sign Up API
DESCRIPTION: Details the API endpoint and parameters for signing up a new user using email and password with Better Auth. Includes client-side usage example and parameter descriptions.
SOURCE: https://www.better-auth.com/docs/authentication/email-password
LANGUAGE: APIDOC
CODE:
```
POST /sign-up/email
Parameters:
name: The name of the user. (string, required)
email: The email address of the user. (string, required)
password: The password of the user. It should be at least 8 characters long and max 128 by default. (string, required)
image?: An optional profile image of the user. (string)
callbackURL?: An optional URL to redirect to after the user signs up. (string)
Returns:
Data and error information from the sign-up process.
Usage Example:
const { data, error } = await authClient.signUp.email({
name: "John Doe", // required
email: "john.doe@example.com", // required
password: "password1234", // required
image: "https://example.com/image.png",
callbackURL: "https://example.com/callback",
});
Note: Additional fields or plugins may allow passing more properties.
```
----------------------------------------
TITLE: Impersonate User Example
DESCRIPTION: Example of how an admin can impersonate a user to act on their behalf.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.admin.impersonateUser({
userId: "user-id", // required
});
```
----------------------------------------
TITLE: Verify Backup Code Client-Side Example
DESCRIPTION: Client-side JavaScript code to call the verify backup code API endpoint.
SOURCE: https://www.better-auth.com/docs/plugins/2fa
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.twoFactor.verifyBackupCode({
code: "123456", // required
disableSession: false,
trustDevice: true,
});
```
----------------------------------------
TITLE: Polar Plugin Installation
DESCRIPTION: Installs the Better Auth Polar plugin and the Polar SDK using pnpm. This is the first step to integrate Polar payments with Better Auth for a seamless auth + payments flow.
SOURCE: https://www.better-auth.com/docs/plugins/polar
LANGUAGE: bash
CODE:
```
pnpm add better-auth @polar-sh/better-auth @polar-sh/sdk
```
----------------------------------------
TITLE: Advanced User Provisioning with SSO
DESCRIPTION: Illustrates a more advanced implementation of the `provisionUser` function within the SSO plugin. This example shows how to update user profiles, create resources, sync with external systems, and log SSO sign-ins using data from the SSO provider.
SOURCE: https://www.better-auth.com/docs/plugins/sso
LANGUAGE: javascript
CODE:
```
const auth = betterAuth({
plugins: [
sso({
provisionUser: async ({ user, userInfo, token, provider }) => {
// Update user profile with SSO data
await updateUserProfile(user.id, {
department: userInfo.attributes?.department,
jobTitle: userInfo.attributes?.jobTitle,
manager: userInfo.attributes?.manager,
lastSSOLogin: new Date(),
});
// Create user-specific resources
await createUserWorkspace(user.id);
// Sync with external systems
await syncUserWithCRM(user.id, userInfo);
// Log the SSO sign-in
await auditLog.create({
userId: user.id,
action: 'sso_signin',
provider: provider.providerId,
metadata: {
email: userInfo.email,
ssoProvider: provider.issuer,
},
});
},
}),
],
});
```
----------------------------------------
TITLE: MongoDB Adapter Example Usage
DESCRIPTION: Demonstrates how to initialize Better Auth with the MongoDB adapter. It requires a running MongoDB instance and the 'mongodb' package. The adapter takes a MongoDB database instance as input.
SOURCE: https://www.better-auth.com/docs/adapters/mongo
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { MongoClient } from "mongodb";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
const client = new MongoClient("mongodb://localhost:27017/database");
const db = client.db();
export const auth = betterAuth({
database: mongodbAdapter(db),
});
```
----------------------------------------
TITLE: Stripe Subscription Plan Definitions
DESCRIPTION: Examples of defining subscription plans, both statically with plan details and dynamically by fetching from a database or API.
SOURCE: https://www.better-auth.com/docs/plugins/stripe
LANGUAGE: typescript
CODE:
```
// Static plans
subscription: {
enabled: true,
plans: [
{
name: "basic", // the name of the plan, it'll be automatically lower cased when stored in the database
priceId: "price_1234567890", // the price ID from stripe
annualDiscountPriceId: "price_1234567890", // (optional) the price ID for annual billing with a discount
limits: {
projects: 5,
storage: 10
}
},
{
name: "pro",
priceId: "price_0987654321",
limits: {
projects: 20,
storage: 50
},
freeTrial: {
days: 14,
}
}
]
}
// Dynamic plans (fetched from database or API)
subscription: {
enabled: true,
plans: async () => {
const plans = await db.query("SELECT * FROM plans");
return plans.map(plan => ({
name: plan.name,
priceId: plan.stripe_priceId,
limits: JSON.parse(plan.limits)
}));
}
}
```
----------------------------------------
TITLE: Reject Invitation Example
DESCRIPTION: Example of using the `rejectInvitation` function from the Better Auth client to reject an organization invitation.
SOURCE: https://www.better-auth.com/docs/plugins/organization
LANGUAGE: javascript
CODE:
```
await authClient.organization.rejectInvitation({
invitationId: "invitation-id", // required
});
```
----------------------------------------
TITLE: OAuth Proxy Plugin Installation
DESCRIPTION: Demonstrates how to install and configure the OAuth Proxy plugin for Better Auth. This plugin is useful for development and preview deployments where the redirect URL might not be known in advance.
SOURCE: https://www.better-auth.com/docs/plugins/oauth-proxy
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { oAuthProxy } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
oAuthProxy({
productionURL: "https://my-main-app.com", // Optional - if the URL isn't inferred correctly
currentURL: "http://localhost:3000", // Optional - if the URL isn't inferred correctly
}),
]
})
```
----------------------------------------
TITLE: Sign In with Linear
DESCRIPTION: This example demonstrates how to initiate a sign-in process with the Linear provider using the Better Auth client. It utilizes the `signIn.social` function, specifying 'linear' as the provider.
SOURCE: https://www.better-auth.com/docs/authentication/linear
LANGUAGE: javascript
CODE:
```
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient()
const signIn = async () => {
const data = await authClient.signIn.social({
provider: "linear"
})
}
```
----------------------------------------
TITLE: View Backup Codes Client-Side Example
DESCRIPTION: Client-side JavaScript code to call the view backup codes API endpoint.
SOURCE: https://www.better-auth.com/docs/plugins/2fa
LANGUAGE: javascript
CODE:
```
const data = await auth.api.viewBackupCodes({
body: {
userId: "user-id",
},
});
```
----------------------------------------
TITLE: Stop Impersonating User Example
DESCRIPTION: Example of how to stop impersonating a user and return to the admin account.
SOURCE: https://www.better-auth.com/docs/plugins/admin
LANGUAGE: javascript
CODE:
```
await authClient.admin.stopImpersonating();
```
----------------------------------------
TITLE: Sign In with Google using Client
DESCRIPTION: This example demonstrates how to initiate a sign-in flow with Google using the Better Auth client library. It calls the `signIn.social` function with the 'google' provider.
SOURCE: https://www.better-auth.com/docs/authentication/google
LANGUAGE: javascript
CODE:
```
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient()
const signIn = async () => {
const data = await authClient.signIn.social({
provider: "google"
})
}
```
----------------------------------------
TITLE: Initialize Better Auth Client with DodoPayments Client Plugin
DESCRIPTION: Sets up the client-side Better Auth instance, including the DodoPayments client plugin for making API requests.
SOURCE: https://www.better-auth.com/docs/plugins/dodopayments
LANGUAGE: typescript
CODE:
```
import { dodopaymentsClient } from "@dodopayments/better-auth";
export const authClient = createAuthClient({
baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000",
plugins: [dodopaymentsClient()],
});
```
----------------------------------------
TITLE: Install NestJS Better Auth Package
DESCRIPTION: Installs the community-maintained NestJS integration library for Better Auth using npm.
SOURCE: https://www.better-auth.com/docs/integrations/nestjs
LANGUAGE: bash
CODE:
```
npm install @thallesp/nestjs-better-auth
```
----------------------------------------
TITLE: Astro Example Environment Variables
DESCRIPTION: Required environment variables for the Astro example of Better Auth. These include Google API credentials and a Better Auth secret.
SOURCE: https://www.better-auth.com/docs/examples/astro
LANGUAGE: env
CODE:
```
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
BETTER_AUTH_SECRET=
```
----------------------------------------
TITLE: Configure CORS with Nitro Plugin
DESCRIPTION: Configure Cross-Origin Resource Sharing (CORS) for your Nitro application by creating a plugin and installing the 'cors' package.
SOURCE: https://www.better-auth.com/docs/integrations/nitro
LANGUAGE: bash
CODE:
```
npm install cors
```
LANGUAGE: typescript
CODE:
```
import cors from "cors";
import { defineNitroPlugin } from "#imports";
import { fromNodeMiddleware } from "h3";
export default defineNitroPlugin((plugin) => {
plugin.h3App.use(
fromNodeMiddleware(
cors({
origin: "*",
}),
),
);
});
```
----------------------------------------
TITLE: Basic Client Plugin
DESCRIPTION: A minimal example of a client plugin for Better Auth. This plugin serves as a placeholder and can be extended to infer server-side endpoints.
SOURCE: https://www.better-auth.com/docs/concepts/plugins
LANGUAGE: typescript
CODE:
```
import type { BetterAuthClientPlugin } from "better-auth";
export const myPluginClient = () => {
return {
id: "my-plugin",
} satisfies BetterAuthClientPlugin
}
```
----------------------------------------
TITLE: Install Have I Been Pwned Plugin
DESCRIPTION: Demonstrates how to install and configure the Have I Been Pwned plugin within the Better Auth configuration. This plugin checks for compromised passwords against the Have I Been Pwned API.
SOURCE: https://www.better-auth.com/docs/plugins/have-i-been-pwned
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth"
import { haveIBeenPwned } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
haveIBeenPwned()
]
})
```
----------------------------------------
TITLE: Vitest Testing Example
DESCRIPTION: This snippet demonstrates how to write tests using Vitest, a fast unit test framework. It shows the basic structure for describing tests, defining individual test cases, and using assertions.
SOURCE: https://www.better-auth.com/docs/reference/contributing
LANGUAGE: javascript
CODE:
```
import { describe, it, expect } from "vitest";
import { getTestInstance } from "./test-utils/test-instance";
describe("Feature", () => {
it("should work as expected", async () => {
const { client } = getTestInstance();
// Test code here
expect(result).toBeDefined();
});
});
```
----------------------------------------
TITLE: PostgreSQL Connection Example
DESCRIPTION: Demonstrates how to establish a connection to a PostgreSQL database using Better Auth and the 'pg' library. This involves creating a Pool instance with the connection string.
SOURCE: https://www.better-auth.com/docs/adapters/postgresql
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { Pool } from "pg";
export const auth = betterAuth({
database: new Pool({
connectionString: "postgres://user:password@localhost:5432/database",
}),
});
```
----------------------------------------
TITLE: Create a Simple GET Endpoint
DESCRIPTION: Demonstrates how to create a basic GET endpoint for a Better Auth plugin. It imports `createAuthEndpoint` and defines a handler that returns a JSON response.
SOURCE: https://www.better-auth.com/docs/concepts/plugins
LANGUAGE: typescript
CODE:
```
import { createAuthEndpoint } from "better-auth/api";
const myPlugin = ()=> {
return {
id: "my-plugin",
endpoints: {
getHelloWorld: createAuthEndpoint("/my-plugin/hello-world", {
method: "GET",
}, async(ctx) => {
return ctx.json({
message: "Hello World"
})
})
}
} satisfies BetterAuthPlugin
}
```
----------------------------------------
TITLE: Create or Switch Subscription (JavaScript)
DESCRIPTION: Example of using the `subscription.upgrade` method in JavaScript to create a new subscription or switch to a different plan. It demonstrates providing required parameters like `plan`, `successUrl`, and `cancelUrl`, along with optional parameters.
SOURCE: https://www.better-auth.com/docs/plugins/stripe
LANGUAGE: javascript
CODE:
```
const { data, error } = await authClient.subscription.upgrade({
plan: "pro", // required
annual: true,
referenceId: "123",
subscriptionId: "sub_123",
metadata,
seats: 1,
successUrl: "/dashboard", // required
cancelUrl: "/pricing", // required
returnUrl: "/account",
disableRedirect: true, // required
});
// Simple Example:
await client.subscription.upgrade({
plan: "pro",
successUrl: "/dashboard",
cancelUrl: "/pricing",
annual: true, // Optional: upgrade to an annual plan
referenceId: "org_123" // Optional: defaults to the current logged in user ID
seats: 5 // Optional: for team plans
});
// Handling errors:
const { error } = await client.subscription.upgrade({
plan: "pro",
successUrl: "/dashboard",
cancelUrl: "/pricing",
});
if(error) {
alert(error.message);
}
```
----------------------------------------
TITLE: One-Time Token Plugin Installation
DESCRIPTION: Demonstrates how to install and configure the One-Time Token (OTT) plugin within the Better Auth framework. This plugin is used for generating and verifying secure, single-use session tokens.
SOURCE: https://www.better-auth.com/docs/plugins/one-time-token
LANGUAGE: typescript
CODE:
```
import { betterAuth } from "better-auth";
import { oneTimeToken } from "better-auth/plugins/one-time-token";
export const auth = betterAuth({
plugins: [
oneTimeToken()
]
// ... other auth config
});
```