mirror of
https://github.com/LukeHagar/better-auth.git
synced 2025-12-10 04:19:32 +00:00
feat: docs example trial
This commit is contained in:
20
docs/content/docs/examples/next-js.mdx
Normal file
20
docs/content/docs/examples/next-js.mdx
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Next js example
|
||||
descirption: Better auth next js example
|
||||
---
|
||||
|
||||
<iframe src="https://codesandbox.io/p/github/better-auth/better-auth/draft/dry-wind?workspaceId=f8670ba9-e253-4b60-91a6-369d03522afe&embed=1"
|
||||
style={
|
||||
{
|
||||
width: "100%",
|
||||
height: "500px",
|
||||
border: 0,
|
||||
borderRadius: "4px",
|
||||
overflow: "hidden"
|
||||
}
|
||||
}
|
||||
title="Bekacru/better-auth-demo/draft/awesome-chihiro"
|
||||
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
|
||||
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
|
||||
module="/demo/nextjs"
|
||||
></iframe>
|
||||
73
docs/content/docs/integrations/hono.mdx
Normal file
73
docs/content/docs/integrations/hono.mdx
Normal file
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Hono Integration
|
||||
description: Hono Integration Guide
|
||||
---
|
||||
|
||||
This integration guide is assuming you are using Hono with node server.
|
||||
|
||||
## Installation
|
||||
|
||||
First, install Better Auth
|
||||
|
||||
```package-install
|
||||
npm install better-auth
|
||||
```
|
||||
|
||||
## Set Environment Variables
|
||||
|
||||
Create a `.env` file in the root of your project and add the following environment variables:
|
||||
|
||||
**Set Base URL**
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your Next.js app
|
||||
```
|
||||
|
||||
**Set Secret**
|
||||
|
||||
Random value used by the library for encryption and generating hashes. You can generate one using the button below or you can use something like openssl.
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_SECRET=
|
||||
```
|
||||
<GenerateSecret/>
|
||||
|
||||
## Configure Server
|
||||
|
||||
### Create Better Auth instance
|
||||
|
||||
We recommend to create `auth.ts` file inside your `lib/` directory. This file will contain your Better Auth instance.
|
||||
|
||||
```ts twoslash title="auth.ts"
|
||||
import { betterAuth } from "better-auth"
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: {
|
||||
provider: "sqlite", //change this to your database provider
|
||||
url: "./db.sqlite", // path to your database or connection string
|
||||
}
|
||||
// Refer to the api documentation for more configuration options
|
||||
})
|
||||
```
|
||||
|
||||
<Callout type="warn">
|
||||
Better Auth currently supports only SQLite, MySQL, and PostgreSQL. It uses Kysely under the hood, so you can also pass any Kysely dialect directly to the database object.
|
||||
</Callout>
|
||||
|
||||
### Mount the handler
|
||||
|
||||
We need to mount the handler to hono endpoint.
|
||||
|
||||
```ts
|
||||
import { Hono } from "hono";
|
||||
import { auth } from "./auth";
|
||||
import { serve } from "@hono/node-server";
|
||||
import { cors } from "hono/cors";
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
app.on(["POST", "GET"], "/api/auth/**", (c) => {
|
||||
return auth.handler(c.req.raw);
|
||||
});
|
||||
|
||||
serve(app);
|
||||
```
|
||||
|
||||
111
docs/content/docs/integrations/nuxt.mdx
Normal file
111
docs/content/docs/integrations/nuxt.mdx
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
title: Nuxt.js Integration
|
||||
description: Learn how to integrate Better Auth with Nuxt.js
|
||||
---
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
First, install Better Auth
|
||||
|
||||
```package-install
|
||||
npm install better-auth
|
||||
```
|
||||
|
||||
## Set Environment Variables
|
||||
|
||||
Create a `.env` file in the root of your project and add the following environment variables:
|
||||
|
||||
**Set Base URL**
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your Next.js app
|
||||
```
|
||||
|
||||
**Set Secret**
|
||||
|
||||
Random value used by the library for encryption and generating hashes. You can generate one using the button below or you can use something like openssl.
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_SECRET=
|
||||
```
|
||||
|
||||
<GenerateSecret/>
|
||||
|
||||
## Configure Server
|
||||
|
||||
### Create Better Auth instance
|
||||
|
||||
We recommend to create `auth.ts` file inside your `lib/` directory. This file will contain your Better Auth instance.
|
||||
|
||||
```ts twoslash title="auth.ts"
|
||||
import { betterAuth } from "better-auth"
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: {
|
||||
provider: "sqlite", //change this to your database provider
|
||||
url: "./db.sqlite", // path to your database or connection string
|
||||
}
|
||||
// Refer to the api documentation for more configuration options
|
||||
})
|
||||
```
|
||||
|
||||
<Callout type="warn">
|
||||
Better Auth currently supports only SQLite, MySQL, and PostgreSQL. It uses Kysely under the hood, so you can also pass any Kysely dialect directly to the database object.
|
||||
</Callout>
|
||||
|
||||
### Create API Route
|
||||
|
||||
We need to mount the handler to an API route. Create a file inside `/server/api` called `[...auth].ts` and add the following code:
|
||||
|
||||
```ts title="server/api/[...auth].ts"
|
||||
import { auth } from "~/utils/auth.config";
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
return auth.handler(toWebRequest(event));
|
||||
});
|
||||
```
|
||||
<Callout type="info">
|
||||
You can change the path on your better-auth configuration but it's recommended to keep it as `/api/[...auth]`
|
||||
</Callout>
|
||||
|
||||
### Migrate the database
|
||||
Run the following command to create the necessary tables in your database:
|
||||
|
||||
```bash
|
||||
npx better-auth migrate
|
||||
```
|
||||
|
||||
## Create a client
|
||||
|
||||
Create a client instance. You can name the file anything you want. Here we are creating `client.ts` file inside the `lib/` directory.
|
||||
|
||||
```ts twoslash title="client.ts"
|
||||
import { createAuthClient } from "better-auth/vue" // make sure to import from better-auth/vue
|
||||
|
||||
export const client = createAuthClient({
|
||||
//you can pass client configuration here
|
||||
})
|
||||
```
|
||||
|
||||
Once you have created the client, you can use it to sign up, sign in, and perform other actions.
|
||||
Some of the actinos are reactive. The client use [nano-store](https://github.com/nanostores/nanostores) to store the state and re-render the components when the state changes.
|
||||
|
||||
### Example usage
|
||||
|
||||
```vue title="index.vue"
|
||||
<template>
|
||||
<div style="">
|
||||
<button v-if="!client.useSession().value" @click="() => client.signIn.social({
|
||||
provider: 'github'
|
||||
})">
|
||||
Continue with github
|
||||
</button>
|
||||
<div>
|
||||
<pre>{{ client.useSession().value }}</pre>
|
||||
<button v-if="client.useSession().value" @click="client.signOut()">
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
64
docs/content/docs/integrations/solid-start.mdx
Normal file
64
docs/content/docs/integrations/solid-start.mdx
Normal file
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: Solid Start Integration
|
||||
description: Solid Start integratons guide
|
||||
---
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
First, install Better Auth
|
||||
|
||||
```package-install
|
||||
npm install better-auth
|
||||
```
|
||||
|
||||
## Set Environment Variables
|
||||
|
||||
Create a `.env` file in the root of your project and add the following environment variables:
|
||||
|
||||
**Set Base URL**
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your Next.js app
|
||||
```
|
||||
|
||||
**Set Secret**
|
||||
|
||||
Random value used by the library for encryption and generating hashes. You can generate one using the button below or you can use something like openssl.
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_SECRET=
|
||||
```
|
||||
|
||||
<GenerateSecret/>
|
||||
|
||||
## Configure Server
|
||||
|
||||
### Create Better Auth instance
|
||||
|
||||
We recommend to create `auth.ts` file inside your `lib/` directory. This file will contain your Better Auth instance.
|
||||
|
||||
```ts twoslash title="auth.ts"
|
||||
import { betterAuth } from "better-auth"
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: {
|
||||
provider: "sqlite", //change this to your database provider
|
||||
url: "./db.sqlite", // path to your database or connection string
|
||||
}
|
||||
// Refer to the api documentation for more configuration options
|
||||
})
|
||||
```
|
||||
|
||||
<Callout type="warn">
|
||||
Better Auth currently supports only SQLite, MySQL, and PostgreSQL. It uses Kysely under the hood, so you can also pass any Kysely dialect directly to the database object.
|
||||
</Callout>
|
||||
|
||||
### Mount the handler
|
||||
|
||||
We need to mount the handler to Solid Start server. Put the following code in your `*auth.ts` file inside `/routes/api/auth` folder.
|
||||
|
||||
```ts title="*auth.ts"
|
||||
import { auth } from "~/lib/auth";
|
||||
import { toSolidStartHandler } from "better-auth/solid-start";
|
||||
|
||||
export const { GET, POST } = toSolidStartHandler(auth);
|
||||
```
|
||||
148
docs/content/docs/integrations/svelte-kit.mdx
Normal file
148
docs/content/docs/integrations/svelte-kit.mdx
Normal file
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: Svelte Kit Integration
|
||||
description: Learn how to integrate Better Auth with Svelte Kit
|
||||
---
|
||||
|
||||
Better Auth has first class support for Svelte Kit. It provides utilities to make it easier to use Better Auth with Svelte Kit.
|
||||
|
||||
## Installation
|
||||
|
||||
First, install Better Auth
|
||||
|
||||
```package-install
|
||||
npm install better-auth
|
||||
```
|
||||
|
||||
## Set Environment Variables
|
||||
|
||||
Create a `.env` file in the root of your project and add the following environment variables:
|
||||
|
||||
**Set Base URL**
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your Next.js app
|
||||
```
|
||||
|
||||
**Set Secret**
|
||||
|
||||
Random value used by the library for encryption and generating hashes. You can generate one using the button below or you can use something like openssl.
|
||||
```txt title=".env"
|
||||
BETTER_AUTH_SECRET=
|
||||
```
|
||||
|
||||
<GenerateSecret/>
|
||||
|
||||
## Configure Server
|
||||
|
||||
### Create Better Auth instance
|
||||
|
||||
We recommend to create `auth.ts` file inside your `lib/` directory. This file will contain your Better Auth instance.
|
||||
|
||||
```ts twoslash title="auth.ts"
|
||||
import { betterAuth } from "better-auth"
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: {
|
||||
provider: "sqlite", //change this to your database provider
|
||||
url: "./db.sqlite", // path to your database or connection string
|
||||
}
|
||||
// Refer to the api documentation for more configuration options
|
||||
})
|
||||
```
|
||||
|
||||
<Callout type="warn">
|
||||
Better Auth currently supports only SQLite, MySQL, and PostgreSQL. It uses Kysely under the hood, so you can also pass any Kysely dialect directly to the database object.
|
||||
</Callout>
|
||||
|
||||
### Mount the handler
|
||||
|
||||
We need to mount the handler to svelte kit server hook.
|
||||
|
||||
```ts
|
||||
import { auth } from "$lib/auth";
|
||||
import { svelteKitHandler } from "better-auth/svelte-kit";
|
||||
|
||||
export async function handle({ event, resolve }) {
|
||||
return svelteKitHandler({ event, resolve, auth });
|
||||
}
|
||||
```
|
||||
|
||||
### Migrate the database
|
||||
Run the following command to create the necessary tables in your database:
|
||||
|
||||
```bash
|
||||
npx better-auth migrate
|
||||
```
|
||||
|
||||
|
||||
## Create a client
|
||||
|
||||
Create a client instance. You can name the file anything you want. Here we are creating `client.ts` file inside the `lib/` directory.
|
||||
|
||||
```ts twoslash title="client.ts"
|
||||
import { createAuthClient } from "better-auth/svelte" // make sure to import from better-auth/svlete
|
||||
|
||||
export const client = createAuthClient({
|
||||
//you can pass client configuration here
|
||||
})
|
||||
```
|
||||
|
||||
Once you have created the client, you can use it to sign up, sign in, and perform other actions.
|
||||
Some of the actinos are reactive. The client use [nano-store](https://github.com/nanostores/nanostores) to store the state and refelct changes when there is a change like a user signing in or out affecting the session state.
|
||||
|
||||
### Example usage
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import { client } from "$lib/client";
|
||||
const session = client.$session;
|
||||
</script>
|
||||
<div>
|
||||
{#if $session}
|
||||
<div>
|
||||
<p>
|
||||
{$session?.user.name}
|
||||
</p>
|
||||
<button
|
||||
on:click={async () => {
|
||||
await client.signOut();
|
||||
}}
|
||||
>
|
||||
Signout
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
on:click={async () => {
|
||||
await client.signIn.social({
|
||||
provider: "github",
|
||||
});
|
||||
}}
|
||||
>
|
||||
Continue with github
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
```
|
||||
|
||||
### Example: Getting Session on a loader
|
||||
|
||||
```ts title="+page.ts"
|
||||
import { auth } from "$lib/auth";
|
||||
|
||||
export async function load(request: Request) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: request.headers,
|
||||
});
|
||||
if (!session) {
|
||||
return {
|
||||
status: 401,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
error: "Unauthorized",
|
||||
}),
|
||||
};
|
||||
}
|
||||
return session;
|
||||
}
|
||||
```
|
||||
387
docs/content/docs/plugins/2fa.mdx
Normal file
387
docs/content/docs/plugins/2fa.mdx
Normal file
@@ -0,0 +1,387 @@
|
||||
---
|
||||
title: Two-Factor Authentication (2FA)
|
||||
description: Enhance your app's security with two-factor authentication
|
||||
---
|
||||
|
||||
`OTP` `TOTP` `Backup Codes` `Trusted Devices`
|
||||
|
||||
## What is Two-Factor Authentication?
|
||||
|
||||
Two-Factor Authentication (2FA) adds an extra security step when users log in. Instead of just using a password, they'll need to provide a second form of verification. This makes it much harder for unauthorized people to access accounts, even if they've somehow gotten the password.
|
||||
|
||||
This plugin offers two main methods of 2FA:
|
||||
|
||||
1. **OTP (One-Time Password)**: A temporary code sent to the user's email or phone.
|
||||
2. **TOTP (Time-based One-Time Password)**: A code generated by an app on the user's device.
|
||||
|
||||
**Additional features include:**
|
||||
- Generating backup codes for account recovery
|
||||
- Enabling/disabling 2FA
|
||||
- Managing trusted devices
|
||||
|
||||
|
||||
## Initial Setup
|
||||
|
||||
To get started with Two-Factor Authentication, follow these steps:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
### Add the plugin to your auth config:
|
||||
|
||||
```ts title="auth.ts"
|
||||
import { betterAuth } from "better-auth"
|
||||
import { twoFactor } from "better-auth/plugins"
|
||||
|
||||
export const auth = await betterAuth({
|
||||
// ... other config options
|
||||
plugins: [
|
||||
twoFactor({
|
||||
issuer: "my-app"
|
||||
})
|
||||
]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
|
||||
### Migrate your database:
|
||||
|
||||
```bash
|
||||
npx better-auth migrate
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Add the client plugin:
|
||||
|
||||
```ts title="client.ts"
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { twoFactorClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [
|
||||
twoFactorClient({
|
||||
twoFactorPage: "/two-factor" //redirect for two factor verification if enabled // [!code highlight]
|
||||
})
|
||||
]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Usage
|
||||
|
||||
### Enabling 2FA
|
||||
|
||||
To enable two-factor authentication for a user:
|
||||
|
||||
```ts title="two-factor.ts"
|
||||
const enableTwoFactor = async() => {
|
||||
const { data, error } = await client.twoFactor.enable()
|
||||
if (data) {
|
||||
// 2FA has been enabled successfully
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Sign In with 2FA
|
||||
|
||||
When a user with 2FA enabled tries to sign in, you'll need to verify their 2FA code. If they have 2FA enabled, they'll be redirected to the `twoFactorPage` where they can enter their 2FA code.
|
||||
|
||||
```ts
|
||||
const signin = async () => {
|
||||
const { data, error } = await client.signIn.email({
|
||||
email: "user@example.com",
|
||||
password: "password123",
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
By default, the user will be redirected to the `twoFactorPage` if they have 2FA enabled. If you want to handle the 2FA verification in place, you can use the `options` parameter.
|
||||
|
||||
```ts
|
||||
const signin = async () => {
|
||||
const { data, error } = await client.signIn.email({
|
||||
email: "user@example.com",
|
||||
password: "password123",
|
||||
options: {
|
||||
async onSuccess(context) {
|
||||
if (context.data.twoFactorRedirect) {
|
||||
// Handle the 2FA verification in place
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### TOTP
|
||||
|
||||
TOTP is a time-based one-time password algorithm that generates a code based on the current time. It's a more secure method than OTP because it takes into account the time it takes to generate the code.
|
||||
|
||||
#### Getting TOTP URI
|
||||
|
||||
After enabling 2FA, you can get the TOTP URI to display to the user.
|
||||
|
||||
```ts
|
||||
const { data, error } = await client.twoFactor.getTotpUri()
|
||||
if (data) {
|
||||
// Use data.totpURI to generate a QR code or display to the user
|
||||
}
|
||||
```
|
||||
|
||||
#### Generating a QR Code
|
||||
|
||||
You can use a library like `qrcode` to generate a QR code from the TOTP URI.
|
||||
|
||||
```ts
|
||||
import { toCanvas } from "qrcode"
|
||||
|
||||
toCanvas(document.getElementById('canvas'), data.totpURI)
|
||||
```
|
||||
|
||||
#### Verifying TOTP
|
||||
|
||||
After the user has entered their 2FA code, you can verify it
|
||||
|
||||
```ts
|
||||
const verifyTotp = async (code: string) => {
|
||||
const { data, error } = await client.twoFactor.verifyTotp({ code })
|
||||
}
|
||||
```
|
||||
|
||||
### OTP
|
||||
|
||||
OTP is a one-time password algorithm that generates a code based on the current time. It's a more secure method than TOTP because it takes into account the time it takes to generate the code.
|
||||
|
||||
|
||||
Before using OTP, you need to setup `sendOTP` function.
|
||||
|
||||
```ts title="auth.ts" twoslash
|
||||
import { betterAuth } from "better-auth"
|
||||
import { twoFactor } from "better-auth/plugins"
|
||||
|
||||
export const auth = await betterAuth({
|
||||
database: {
|
||||
provider: "sqlite",
|
||||
url: "./db.sqlite",
|
||||
},
|
||||
plugins: [
|
||||
twoFactor({
|
||||
otpOptions: {
|
||||
async sendOTP(user, otp) {
|
||||
console.log({ user, otp });
|
||||
},
|
||||
},
|
||||
})
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
#### Sending OTP
|
||||
|
||||
sending otp is done by calling `sendOtp` function. This functino will call your `sendOTP` function that you provide in the `otpOptions` with the otp code and the user.
|
||||
|
||||
```ts
|
||||
const { data, error } = await client.twoFactor.sendOtp()
|
||||
if (data) {
|
||||
// Show the OTP to the user
|
||||
}
|
||||
```
|
||||
|
||||
#### Verifying OTP
|
||||
|
||||
After the user has entered their OTP code, you can verify it
|
||||
|
||||
```ts
|
||||
const verifyOtp = async (code: string) => {
|
||||
const { data, error } = await client.twoFactor.verifyOtp({ code })
|
||||
}
|
||||
```
|
||||
|
||||
### Backup Codes
|
||||
|
||||
|
||||
Backup codes are generated and stored in the database when the user enabled two factor authentication. This can be used to recover access to the account if the user loses access to their phone or email.
|
||||
|
||||
#### Generating Backup Codes
|
||||
Generate backup codes for account recovery:
|
||||
|
||||
```ts
|
||||
const { data, error } = await client.twoFactor.generateBackupCodes()
|
||||
if (data) {
|
||||
// Show the backup codes to the user
|
||||
}
|
||||
```
|
||||
|
||||
#### Using Backup Codes
|
||||
|
||||
Backup codes can be used to recover access to the account if the user loses access to their phone or email.
|
||||
|
||||
```ts
|
||||
const { data, error } = await client.twoFactor.verifyBackupCode({code: ""})
|
||||
if (data) {
|
||||
// 2FA verified and account recovered
|
||||
}
|
||||
```
|
||||
|
||||
### Trusted Devices
|
||||
|
||||
You can mark a device as trusted by passing `trustDevice` to `verifyTotp` or `verifyOtp`.
|
||||
|
||||
```ts
|
||||
const verify2FA = async (code: string) => {
|
||||
const { data, error } = await client.twoFactor.verifyTotp({
|
||||
code,
|
||||
callbackURL: "/dashboard",
|
||||
trustDevice: true // Mark this device as trusted
|
||||
})
|
||||
if (data) {
|
||||
// 2FA verified and device trusted
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When `trustDevice` is set to `true`, the current device will be remembered for 60 days. During this period, the user won't be prompted for 2FA on subsequent sign-ins from this device. The trust period is refreshed each time the user signs in successfully.
|
||||
|
||||
<Callout type="info">
|
||||
Trusted devices enhance user convenience but should be used carefully, as they slightly reduce security. Encourage users to only trust personal, secure devices.
|
||||
</Callout>
|
||||
|
||||
## Configuration
|
||||
|
||||
### Server
|
||||
|
||||
To configure the two factor plugin, you need to add the following code to your better auth instance.
|
||||
|
||||
```ts title="auth.ts" twoslash
|
||||
import { betterAuth } from "better-auth"
|
||||
import { twoFactor } from "better-auth/plugins"
|
||||
|
||||
export const auth = await betterAuth({
|
||||
database: {
|
||||
provider: "sqlite",
|
||||
url: "./db.sqlite",
|
||||
},
|
||||
plugins: [ // [!code highlight]
|
||||
twoFactor({ // [!code highlight]
|
||||
issuer: "my-app" // [!code highlight]
|
||||
}) // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
```
|
||||
|
||||
**Issuer**: The issuer is the name of your application. It's used to generate totp codes. It'll be displayed in the authenticator apps.
|
||||
|
||||
**TOTP options**
|
||||
|
||||
these are options for TOTP.
|
||||
|
||||
<TypeTable
|
||||
type={{
|
||||
digits:{
|
||||
description: 'The number of digits the otp to be',
|
||||
type: 'number',
|
||||
default: 6,
|
||||
},
|
||||
period: {
|
||||
description: 'The period for otp in seconds.',
|
||||
type: 'number',
|
||||
default: 30,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
**OTP options**
|
||||
|
||||
these are options for OTP.
|
||||
|
||||
<TypeTable
|
||||
type={{
|
||||
sendOTP: {
|
||||
description: "a function that sends the otp to the user's email or phone number. It takes two parameters: user and otp",
|
||||
type: "function",
|
||||
},
|
||||
period: {
|
||||
description: 'The period for otp in seconds.',
|
||||
type: 'number',
|
||||
default: 30,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
**Backup Code Options**
|
||||
|
||||
backup codes are generated and stored in the database when the user enabled two factor authentication. This can be used to recover access to the account if the user loses access to their phone or email.
|
||||
|
||||
<TypeTable
|
||||
type={{
|
||||
amount: {
|
||||
description: "The amount of backup codes to generate",
|
||||
type: "number",
|
||||
default: 10,
|
||||
},
|
||||
length: {
|
||||
description: "The length of the backup codes",
|
||||
type: "number",
|
||||
default: 10,
|
||||
},
|
||||
customBackupCodesGenerate: {
|
||||
description: "A function that generates custom backup codes. It takes no parameters and returns an array of strings.",
|
||||
type: "function",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
### Client
|
||||
|
||||
To use the two factor plugin in the client, you need to add it on your plugins list.
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { twoFactorClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [
|
||||
twoFactorClient({ // [!code highlight]
|
||||
twoFactorPage: "/two-factor" // [!code highlight]
|
||||
}) // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
```
|
||||
|
||||
**Options**
|
||||
|
||||
`twoFactorPage`: The page to redirect the user to after they have enabled 2-Factor. This is the page where the user will be redirected to verify their 2-Factor code.
|
||||
|
||||
`redirect`: If set to `false`, the user will not be redirected to the `twoFactorPage` after they have enabled 2-Factor.
|
||||
|
||||
|
||||
## Database Schema
|
||||
|
||||
Two factores requires additional fields on the user table. If you use better auth's migration system, it will automatically create this table for you.
|
||||
|
||||
```ts
|
||||
const schema = {
|
||||
user: {
|
||||
fields: {
|
||||
twoFactorEnabled: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
twoFactorSecret: {
|
||||
type: "string",
|
||||
required: false,
|
||||
},
|
||||
twoFactorBackupCodes: {
|
||||
type: "string",
|
||||
required: false,
|
||||
returned: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
4
docs/content/docs/plugins/organization.mdx
Normal file
4
docs/content/docs/plugins/organization.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: Organization
|
||||
descirption: The organization plugin allows you to manage your organization's members and teams.
|
||||
---
|
||||
158
docs/content/docs/plugins/passkey.mdx
Normal file
158
docs/content/docs/plugins/passkey.mdx
Normal file
@@ -0,0 +1,158 @@
|
||||
---
|
||||
title: Passkey
|
||||
description: Passkey
|
||||
---
|
||||
|
||||
Passkeys are a secure, passwordless authentication method using cryptographic key pairs, supported by WebAuthn and FIDO2 standards in web browsers. They replace passwords with unique key pairs: a private key stored on the user’s device and a public key shared with the website. Users can log in using biometrics, PINs, or security keys, providing strong, phishing-resistant authentication without traditional passwords.
|
||||
|
||||
The passkey plugin implementation is powered by [simple-web-authn](https://simplewebauthn.dev/) behind the scenes.
|
||||
|
||||
## Quick setup
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
### Add the plugin to your auth config
|
||||
To add the passkey plugin to your auth config, you need to import the plugin and pass it to the `plugins` option of the auth instance.
|
||||
|
||||
**Options**
|
||||
|
||||
`rpID`: A unique identifier for your website. 'localhost' is okay for local dev
|
||||
|
||||
`rpName`: Human-readable title for your website
|
||||
|
||||
`origin`: The URL at which registrations and authentications should occur. 'http://localhost' and 'http://localhost:PORT' are also valid.Do NOT include any trailing /
|
||||
|
||||
```ts title="auth.ts" twoslash
|
||||
import { betterAuth } from "better-auth"
|
||||
import { passkey } from "better-auth/plugins"
|
||||
|
||||
export const auth = await betterAuth({
|
||||
database: {
|
||||
provider: "sqlite",
|
||||
url: "./db.sqlite",
|
||||
},
|
||||
plugins: [ // [!code highlight]
|
||||
passkey({ // [!code highlight]
|
||||
rpID: "localhost", // [!code highlight]
|
||||
rpName: "BetterAuth", // [!code highlight]
|
||||
origin: "http://localhost:3000", // [!code highlight]
|
||||
}), // [!code highlight]
|
||||
], // [!code highlight]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
### Add the client plugin
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { passkeyClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
passkeyClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Add a passkey
|
||||
|
||||
To add a passkey make sure a user is authenticated and then call the `passkey.addPasskey` function provided by the client.
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { passkeyClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
passkeyClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
// ---cut---
|
||||
const data = await client.passkey.addPasskey()
|
||||
```
|
||||
This will prompt the user to register a passkey. And it'll add the passkey to the user's account.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Signin with a passkey
|
||||
|
||||
To signin with a passkey you can use the passkeySignIn method. This will prompt the user to sign in with their passkey.
|
||||
|
||||
Signin method accepts:
|
||||
|
||||
`autoFill`: Browser autofill, a.k.a. Conditional UI. [read more](https://simplewebauthn.dev/docs/packages/browser#browser-autofill-aka-conditional-ui)
|
||||
|
||||
`callbackURL`: The URL to redirect to after the user has signed in. (optional)
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { passkeyClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
passkeyClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
// ---cut---
|
||||
const data = await client.signIn.passkey()
|
||||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
## Passkey Configuration
|
||||
|
||||
**rpID**: A unique identifier for your website. 'localhost' is okay for local dev.
|
||||
|
||||
**rpName**: Human-readable title for your website.
|
||||
|
||||
**origin**: The URL at which registrations and authentications should occur. 'http://localhost' and 'http://localhost:PORT' are also valid. Do NOT include any trailing /.
|
||||
|
||||
|
||||
## Database Schema
|
||||
|
||||
Passkey requires a database table called `passkey` with the following fields. If you use better auth's migration system, it will automatically create this table for you.
|
||||
|
||||
```ts
|
||||
const schema = {
|
||||
passkey: {
|
||||
fields: {
|
||||
publicKey: {
|
||||
type: "string",
|
||||
},
|
||||
userId: {
|
||||
type: "string",
|
||||
references: {
|
||||
model: "user",
|
||||
field: "id",
|
||||
},
|
||||
},
|
||||
webauthnUserID: {
|
||||
type: "string",
|
||||
},
|
||||
counter: {
|
||||
type: "number",
|
||||
},
|
||||
deviceType: {
|
||||
type: "string",
|
||||
},
|
||||
backedUp: {
|
||||
type: "boolean",
|
||||
},
|
||||
transports: {
|
||||
type: "string",
|
||||
required: false,
|
||||
},
|
||||
createdAt: {
|
||||
type: "date",
|
||||
defaultValue: new Date(),
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
4
docs/content/docs/plugins/rate-limit.mdx
Normal file
4
docs/content/docs/plugins/rate-limit.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: Rate Limit
|
||||
description: The rate limit plugin allows you to limit the number of requests a user can make to your auth server.
|
||||
---
|
||||
119
docs/content/docs/plugins/username.mdx
Normal file
119
docs/content/docs/plugins/username.mdx
Normal file
@@ -0,0 +1,119 @@
|
||||
---
|
||||
title: Username
|
||||
description: Username plugin
|
||||
---
|
||||
|
||||
The username plugin wraps the email and password authenticator and adds username support. This allows users to sign in and sign up with their username instead of their email.
|
||||
|
||||
## Qiuck setup
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
### Add Plugin to the server
|
||||
|
||||
```ts title="auth.ts" twoslash
|
||||
import { betterAuth } from "better-auth"
|
||||
import { username } from "better-auth/plugins"
|
||||
|
||||
const auth = await betterAuth({
|
||||
database: {
|
||||
provider: "sqlite",
|
||||
url: "./db.sqlite",
|
||||
},
|
||||
plugins: [ // [!code highlight]
|
||||
username() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
### Add the client plugin
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { usernameClient } from "better-auth/client/plugins"
|
||||
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
usernameClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
### Signup with username
|
||||
|
||||
To signup a user with username, you can use the `signUp.username` function provided by the client. The `signUp` function takes an object with the following properties:
|
||||
|
||||
- `username`: The username of the user.
|
||||
- `email`: The email address of the user.
|
||||
- `password`: The password of the user. It should be at least 8 characters long and max 32 by default.
|
||||
- `name`: The name of the user.
|
||||
- `image`: The image of the user. (optional)
|
||||
- `callbackURL`: The url to redirect to after the user has signed up. (optional)
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { usernameClient } from "better-auth/client/plugins"
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
usernameClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
// ---cut---
|
||||
|
||||
const data = await client.signUp.username({
|
||||
username: "test",
|
||||
email: "test@email.com",
|
||||
password: "password1234",
|
||||
name: "test",
|
||||
image: "https://example.com/image.png",
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
### Signin with username
|
||||
|
||||
To signin a user with username, you can use the `signIn.username` function provided by the client. The `signIn` function takes an object with the following properties:
|
||||
|
||||
- `username`: The username of the user.
|
||||
- `password`: The password of the user.
|
||||
- `callbackURL`: The url to redirect to after the user has signed in. (optional)
|
||||
|
||||
```ts title="client.ts" twoslash
|
||||
import { createAuthClient } from "better-auth/client"
|
||||
import { usernameClient } from "better-auth/client/plugins"
|
||||
const client = createAuthClient({
|
||||
plugins: [ // [!code highlight]
|
||||
usernameClient() // [!code highlight]
|
||||
] // [!code highlight]
|
||||
})
|
||||
// ---cut---
|
||||
|
||||
const data = await client.signIn.username({
|
||||
username: "test",
|
||||
password: "password1234",
|
||||
})
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Configuration
|
||||
|
||||
The username plugin doesn't require any configuration. It just needs to be added to the server and client.
|
||||
|
||||
## Database Schema
|
||||
|
||||
The username plugin requires a `username` field in the user table. If you're using better auth migration tool it will automatically add the `username` field to the user table. If not you can add it manually.
|
||||
|
||||
```ts
|
||||
const shcmea = {
|
||||
user: {
|
||||
username: {
|
||||
type: "string",
|
||||
unique: true,
|
||||
required: false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user