docs: correct casing to "Better Auth" (#111)

This commit is contained in:
NekoChan
2024-10-07 12:49:25 +03:00
committed by GitHub
parent fc4684790e
commit e537df2c85
26 changed files with 199 additions and 199 deletions
@@ -1,5 +1,5 @@
---
title: Email & Password
title: Email & Password
description: Implementing email and password authentication with Better Auth
---
@@ -13,10 +13,10 @@ Email and password authentication is a common method used by many applications.
To enable email and password authentication, you need to set the `emailAndPassword.enabled` option to `true` in the `auth` configuration.
```ts title="auth.ts"
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = await betterAuth({
export const auth = await betterAuth({
emailAndPassword: { // [!code highlight]
enabled: true // [!code highlight]
} // [!code highlight]
@@ -35,7 +35,7 @@ If it's not enabled, it'll not allow you to sign in or sign up with email and pa
To signup a user, you can use the `signUp.email` function provided by the client. The `signUp` function takes an object with the following properties:
- `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.
- `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)
@@ -62,7 +62,7 @@ To signin a user, you can use the `signIn.email` function provided by the client
- `callbackURL`: The url to redirect to after the user has signed in. (optional)
- `dontRememberMe`: If true, the user will be signed out when the browser is closed. (optional)
```ts title="client.ts"
```ts title="client.ts"
import { createAuthClient } from "better-auth/client"
const client = createAuthClient()
@@ -83,12 +83,12 @@ To enable email verification, you need to provider `sendVerificationEmail` funct
- `email`: The email address of the user.
- `url`: The url to send to the user which contains the token.
```ts title="auth.ts"
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = await betterAuth({
emailAndPassword: {
enabled: true,
emailAndPassword: {
enabled: true,
async sendVerificationEmail(email, url){
// send email to user.
}
@@ -108,7 +108,7 @@ to allow users to reset a password first you need to provider `sendResetPassword
- `user`: The user object.
- `url`: The url to send to the user which contains the token.
```ts title="auth.ts"
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = await betterAuth({
@@ -129,7 +129,7 @@ It takes an object with the following properties:
- `email`: The email address of the user.
- `redirectTo`: The URL to redirect to after the user clicks on the link in the email. If the token is valid, the user will be redirected to this URL with the token in the query string. If the token is invalid, the user will be redirected to this URL with an error message in the query string `?error=invalid_token`.
```ts title="client.ts"
```ts title="client.ts"
const forgetPassword = async () => {
const data = await client.forgetPassword({
email: "test@example.com",
@@ -142,7 +142,7 @@ When user click on the link in the email he will be redirected to the reset pass
- `newPassword`: The new password of the user.
```ts title="client.ts"
```ts title="client.ts"
const data = await client.resetPassword({
newPassword: "password1234",
})
@@ -152,9 +152,9 @@ const data = await client.resetPassword({
**Password**
Better auth stores passwords inside the `account` table with `providerId` set to `credential`.
Better Auth stores passwords inside the `account` table with `providerId` set to `credential`.
**Password Hashing**: Better Auth uses `scrypt` to hash passwords. The `scrypt` algorithm is designed to be slow and memory-intensive to make it difficult for attackers to brute force passwords. OWSAP recommends using `scrypt if `argon2id` is not available. We decided to use `scrypt` because it's natively supported by Node.js.
**Password Hashing**: Better Auth uses `scrypt` to hash passwords. The `scrypt` algorithm is designed to be slow and memory-intensive to make it difficult for attackers to brute force passwords. OWSAP recommends using `scrypt if `argon2id` is not available. We decided to use `scrypt` because it's natively supported by Node.js.
You can pass custom password hashing algothim by setting `passwordHasher` option in the `auth` configuration.
+18 -18
View File
@@ -46,14 +46,14 @@ export default function SignUp() {
const [image, setImage] = useState<File | null>(null);
const signUp = async () => {
const res = await authClient.signUp.email({
email,
password,
name,
const res = await authClient.signUp.email({
email,
password,
name,
image: image ? convertImageToBase64(image) : undefined,
}, {
onRequest: (ctx) => {
//show loading
//show loading
},
onSuccess: (ctx) => {
//redirect to the dashboard
@@ -130,7 +130,7 @@ export const auth = betterAuth({
socialProviders: { // [!code highlight]
github: { // [!code highlight]
clientId: GITHUB_CLIENT_ID, // [!code highlight]
clientSecret: GITHUB_CLIENT_SECRET, // [!code highlight]
clientSecret: GITHUB_CLIENT_SECRET, // [!code highlight]
} // [!code highlight]
}, // [!code highlight]
})
@@ -171,7 +171,7 @@ export default {
## Session Management
Once a user is signed in, you'll want to access their session. Better auth allows you easily to access the session data from the server and client side.
Once a user is signed in, you'll want to access their session. Better Auth allows you easily to access the session data from the server and client side.
### Client Side
@@ -188,12 +188,12 @@ It has the following properties:
//make sure you're using the react client
import { createAuthClient } from "better-auth/react"
const { useSession } = createAuthClient() // [!code highlight]
export function User(){
const {
data: session,
isPending, //loading state
error //error object
error //error object
} = useSession()
returns (
//...
@@ -292,7 +292,7 @@ It has the following properties:
>
<button onClick={toggle}>Log out</button>
</Show>
);
);
}
```
</Tab>
@@ -315,13 +315,13 @@ The server provides a `session` object that you can use to access the session da
import { headers } from "next/headers";
const session = await auth.api.getSession({
headers: headers() // you need to pass the headers object.
headers: headers() // you need to pass the headers object.
})
```
</Tab>
<Tab value="Remix">
```ts title="route.ts"
import { auth } from "lib/auth"; // path to your better auth server instance
import { auth } from "lib/auth"; // path to your Better Auth server instance
export async function loader({ request }: LoaderFunctionArgs) {
const session = await auth.api.getSession({
@@ -389,7 +389,7 @@ The server provides a `session` object that you can use to access the session da
## Using Plugins
One of the unique features of better auth is a plugins ecosystem. It allows you to add complex auth realted functionilty with small lines of code.
One of the unique features of Better Auth is a plugins ecosystem. It allows you to add complex auth realted functionilty with small lines of code.
Below is an example of how to add two factor authentication using two factor plugin.
@@ -400,7 +400,7 @@ Below is an example of how to add two factor authentication using two factor plu
To add a plugin, you need to import the plugin and pass it to the `plugins` option of the auth instance. For example, to add two facor authentication, you can use the following code:
```ts title="auth.ts"
```ts title="auth.ts"
import { betterAuth } from "better-auth"
import { twoFactor } from "better-auth/plugins"
@@ -438,7 +438,7 @@ import { twoFactorClient } from "better-auth/client/plugins";
const client = createAuthClient({
plugins: [ // [!code highlight]
twoFactorClient({ // [!code highlight]
twoFactorPage: "/two-factor" // [!code highlight]
twoFactorPage: "/two-factor" // [!code highlight]
}) // [!code highlight]
] // [!code highlight]
})
@@ -446,7 +446,7 @@ const client = createAuthClient({
now two factor related methods will be available on the client.
```ts title="profile.ts"
```ts title="profile.ts"
import { client } from "./client"
const enableTwoFactor = async() => {
@@ -457,7 +457,7 @@ const enableTwoFactor = async() => {
const disableTwoFactor = async() => {
const data = await client.twoFactor.disable({
password // the user password is required
password // the user password is required
}) // this will disable two factor
}
@@ -472,7 +472,7 @@ const verifyTOTP = async() => {
const data = await client.twoFactor.verifyTOTP({
code: "123456", // the code entered by the user
/**
* If the device is trusted, the user won't
* If the device is trusted, the user won't
* need to pass 2FA again on the same device
*/
trustDevice: true
+2 -2
View File
@@ -9,7 +9,7 @@ Any endpoint added on the server will be available on the `api` object.
## Calling API on the Server
Better auth uses a library called [better-call](https://github.com/bekacru/better-call) to make API endpoints. It's a library made by the same team behind Better Auth and is designed to work seamlessly with it.Better call endpoints allow you to call `rest` api handlers as if they were normal functions.
Better Auth uses a library called [better-call](https://github.com/bekacru/better-call) to make API endpoints. It's a library made by the same team behind Better Auth and is designed to work seamlessly with it.Better call endpoints allow you to call `rest` api handlers as if they were normal functions.
```ts title="server.ts"
import { betterAuth } from "better-auth";
@@ -60,7 +60,7 @@ const response = await auth.api.signInEmail({
## Error Handling
When you call an API endpoint in the server, it will throw an error if the request fails. You can catch the error and handle it as you see fit. The error instance is an instance of `APIError`.
```ts title="server.ts"
import { APIError } from "better-auth/api";
+2 -2
View File
@@ -5,9 +5,9 @@ description: Learn how cookies are used in BetterAuth
Cookies are used to store data such as session tokens, CSRF tokens, and more. All cookies are signed using the `secret` key provided in the auth options.
Core better auth cookies like `session` and `csrf` will follow `betterauth.${cookie_name}` format.
Core Better Auth cookies like `session` and `csrf` will follow `betterauth.${cookie_name}` format.
All cookies are `httpOnly` and `secure` if the server is running in production mode.
All cookies are `httpOnly` and `secure` if the server is running in production mode.
### Cross Subdomain Cookies (🧪 Expiremental)
+72 -72
View File
@@ -3,9 +3,9 @@ title: Database
description: Learn how to use a database with BetterAuth
---
Better auth requires a database connection to store data. It comes with a query builder called <Link href="https://kysely.dev/"> Kysley </Link> to manage and query your database. The database will be used to store data such as users, sessions, and more. Plugins can also define their own database tables to store data.
Better Auth requires a database connection to store data. It comes with a query builder called <Link href="https://kysely.dev/"> Kysley </Link> to manage and query your database. The database will be used to store data such as users, sessions, and more. Plugins can also define their own database tables to store data.
You can pass a database connection to better auth by passing a `database` object auth options. The `database` object takes `provider` key that specifies the database provider to use. By default, better auth support `postgres`, `mysql` and `sqlite` and a `url` key that specifies the database connection to use. If you're using `sqlite`, you can pass a file path in the `url` key.
You can pass a database connection to Better Auth by passing a `database` object auth options. The `database` object takes `provider` key that specifies the database provider to use. By default, Better Auth support `postgres`, `mysql` and `sqlite` and a `url` key that specifies the database connection to use. If you're using `sqlite`, you can pass a file path in the `url` key.
You can also pass a kysley dialect directly to use other databases supported by kysley.
@@ -66,7 +66,7 @@ See <Link href="https://kysely.dev/docs/dialects" target="_blank"> Kysley Dialec
## Using Adapters
If your database is managed by an ORM like Prisma or Drizzle, you can use the corresponding adapter to connect to the database. Better auth comes with built-in adapters for Prisma and Drizzle. You can pass the adapter to the `database` object in the auth options.
If your database is managed by an ORM like Prisma or Drizzle, you can use the corresponding adapter to connect to the database. Better Auth comes with built-in adapters for Prisma and Drizzle. You can pass the adapter to the `database` object in the auth options.
### Prisma Adapter
@@ -98,7 +98,7 @@ import { drizzleAdapter } from "better-auth/adapters/drizzle";
export const auth = await betterAuth({
database: drizzleAdapter(db, {
provider: "sqlite", // or "pg" or "mysql"
provider: "sqlite", // or "pg" or "mysql"
})
})
```
@@ -115,7 +115,7 @@ import { schema } from "./schema";
export const auth = await betterAuth({
database: drizzleAdapter(db, {
provider: "sqlite", // or "pg" or "mysql"
provider: "sqlite", // or "pg" or "mysql"
schema: {
...schema,
user: schema.users,
@@ -130,7 +130,7 @@ export const auth = await betterAuth({
## Running Migrations
Better auth comes with a CLI tool to manage database migrations. Use the `migrate` command to create or update tables as needed.
Better Auth comes with a CLI tool to manage database migrations. Use the `migrate` command to create or update tables as needed.
The cli checks your database and prompts you to add missing tables or update existing ones with new columns.
@@ -140,7 +140,7 @@ npx better-auth migrate
## Running Migrations Manually and Generting Schema
Better auth also provides a `generate` command to generate the schema required by better auth. The `generate` command creates the schema required by Better Auth. If you're using a database adapter like Prisma or Drizzle, this command will generate the right schema for your ORM. If you're using the built-in Kysely adapter, it will generate an SQL file you can run directly on your database.
Better Auth also provides a `generate` command to generate the schema required by Better Auth. The `generate` command creates the schema required by Better Auth. If you're using a database adapter like Prisma or Drizzle, this command will generate the right schema for your ORM. If you're using the built-in Kysely adapter, it will generate an SQL file you can run directly on your database.
```bash
npx better-auth generate
@@ -149,12 +149,12 @@ npx better-auth generate
See the [CLI](/docs/concepts/cli) documentation for more information on the CLI.
<Callout>
If you prefer adding tables manually, you can do that as well. The core schema required by better auth is described below and you can find additional schema required by plugins in the plugin documentation.
If you prefer adding tables manually, you can do that as well. The core schema required by Better Auth is described below and you can find additional schema required by plugins in the plugin documentation.
</Callout>
## Core Schema
Better auth requires the following tables to be present in the database. The types are in `typescript` format. You can use corresponding types in your database.
Better Auth requires the following tables to be present in the database. The types are in `typescript` format. You can use corresponding types in your database.
### User
@@ -162,31 +162,31 @@ Table Name: `user`
<DatabaseTable
fields={[
{
name: "id",
type: "string",
{
name: "id",
type: "string",
description: "Unique identifier for each user",
isPrimaryKey: true
},
{
name: "name",
type: "string",
description: "User's chosen display name"
{
name: "name",
type: "string",
description: "User's chosen display name"
},
{
name: "email",
type: "string",
description: "User's email address for communication and login"
{
name: "email",
type: "string",
description: "User's email address for communication and login"
},
{
name: "createdAt",
type: "Date",
description: "Timestamp of when the user account was created"
},
{
name: "updatedAt",
{
name: "createdAt",
type: "Date",
description: "Timestamp of the last update to the user's information"
description: "Timestamp of when the user account was created"
},
{
name: "updatedAt",
type: "Date",
description: "Timestamp of the last update to the user's information"
},
]}
/>
@@ -197,31 +197,31 @@ Table Name: `session`
<DatabaseTable
fields={[
{
name: "id",
type: "string",
{
name: "id",
type: "string",
description: "Unique identifier for each session",
isPrimaryKey: true
},
{
name: "userId",
type: "string",
{
name: "userId",
type: "string",
description: "The id of the user",
isForeignKey: true
},
{
name: "expiresAt",
type: "Date",
{
name: "expiresAt",
type: "Date",
description: "The time when the session expires"
},
{
name: "ipAddress",
type: "string",
{
name: "ipAddress",
type: "string",
description: "The IP address of the device"
},
{
name: "userAgent",
type: "string",
{
name: "userAgent",
type: "string",
description: "The user agent information of the device"
},
]}
@@ -233,61 +233,61 @@ Table Name: `account`
<DatabaseTable
fields={[
{
name: "id",
type: "string",
{
name: "id",
type: "string",
description: "Unique identifier for each account",
isPrimaryKey: true
},
{
name: "userId",
type: "string",
{
name: "userId",
type: "string",
description: "The id of the user",
isForeignKey: true
},
{
name: "accountId",
type: "string",
{
name: "accountId",
type: "string",
description: "The id of the account",
},
{
name: "providerId",
type: "string",
{
name: "providerId",
type: "string",
description: "The id of the provider",
},
{
name: "accessToken",
type: "string",
{
name: "accessToken",
type: "string",
description: "The access token of the account. Returned by the provider",
},
{
name: "refreshToken",
type: "string",
{
name: "refreshToken",
type: "string",
description: "The refresh token of the account. Returned by the provider",
},
{
name: "expiresAt",
type: "Date",
{
name: "expiresAt",
type: "Date",
description: "The time when the access token expires",
},
{
name: "password",
type: "string",
{
name: "password",
type: "string",
description: "The password of the account. Mainly used for email and password authentication",
},
]}
/>
### Verification
### Verification
Table Name: `verification`
<DatabaseTable
fields={[
{
name: "id",
type: "string",
{
name: "id",
type: "string",
description: "Unique identifier for each verification",
isPrimaryKey: true
},
@@ -326,7 +326,7 @@ Both methods ensure your database schema stays up-to-date with your plugins' req
## Extending the Schema
Better auth doesn't allow you to directly extend any of the core schema. But you can always add new columns in your table and use database hooks to add or modify data during the lifecycle of core database operations.
Better Auth doesn't allow you to directly extend any of the core schema. But you can always add new columns in your table and use database hooks to add or modify data during the lifecycle of core database operations.
## Database Hooks
+14 -14
View File
@@ -49,11 +49,11 @@ const myPlugin = {
### Endpoints
To add endpoints to the server, you can pass `endpoints` that requires an object with the key being any `string` and teh value being `AuthEndpoint`.
To add endpoints to the server, you can pass `endpoints` that requires an object with the key being any `string` and teh value being `AuthEndpoint`.
To create an Auth Endpoint you'll need to import `createAuthEndpoint` from `better-auth`.
Better auth uses a library called <Link href="https://github.com/bekacru/better-call"> Better Call </Link> to create endpoints. Better call is a simple web framework made by the same author of Better Auth.
Better Auth uses a library called <Link href="https://github.com/bekacru/better-call"> Better Call </Link> to create endpoints. Better call is a simple web framework made by the same author of Better Auth.
```ts title="plugin.ts"
import { createAuthEndpoint } from "better-auth";
@@ -84,12 +84,12 @@ Create Auth endpoints wraps around `createEndpoint` from Better Call. Inside the
- `logger`: The logger instance used by Better Auth.
- `db`: The kysely instance used by Better Auth to interact with the database.
- `adapter`: This is the same as db but it give you `orm` like functions to interact with the database. (we recommend using this over `db` unless you need raw sql queries or for peroframnce reasons)
- `intenralAdapter`: this are intenral db calls that are used by better auth. You can use this calls for example to create session instead of using `adapter` directly. `intenralAdapter.createSession(userId)`
- `createAuthCookie`: This is a helper function that let's you get a cookie `name` and `options` for either to `set` or `get` cookies. It implements things like `__secure` prefix and `__host` prefix for cookies based on
- `intenralAdapter`: this are intenral db calls that are used by Better Auth. You can use this calls for example to create session instead of using `adapter` directly. `intenralAdapter.createSession(userId)`
- `createAuthCookie`: This is a helper function that let's you get a cookie `name` and `options` for either to `set` or `get` cookies. It implements things like `__secure` prefix and `__host` prefix for cookies based on
For other properties, you can check the <Link href="https://github.com/bekacru/better-call">Better Call</Link> documentation and the <Link href="https://github.com/better-auth/better-auth/blob/main/packages/better-auth/src/init.ts">source code </Link>.
**Rules for Endpoints**
- Makes sure you use kebab-case for the endpoint path.
@@ -124,7 +124,7 @@ By default better-auth will create an `id` field for each table. You can add add
The key is the column name and the value is the column definition. The column definition can have the following properties:
`type`: The type of the filed. It can be `string`, `number`, `boolean`, `date`.
`type`: The type of the filed. It can be `string`, `number`, `boolean`, `date`.
`required`: if the field should be required on a new record. (default: `false`)
@@ -164,7 +164,7 @@ const myPlugin = (opts: PluginOptions)=>{
### Middleware
You can add middleware to the server by passing a `middleware` array. The middleware array should contain an array of middleware functions created by `createAuthMiddelware`.
You can add middleware to the server by passing a `middleware` array. The middleware array should contain an array of middleware functions created by `createAuthMiddelware`.
`createAuthMiddelware` wraps around `createMiddleware` from Better Call. It takes a function that returns a middleware function. The function will be called with the context object.
@@ -188,7 +188,7 @@ Additional to middlewares you can also hook into right before a request is made
#### On Request
The `onRequest` function is called right before the request is made. It takes two parameters: the `request` and the `context` object.
The `onRequest` function is called right before the request is made. It takes two parameters: the `request` and the `context` object.
Here’s how it works:
@@ -200,7 +200,7 @@ Here’s how it works:
const myPlugin = {
id: "my-plugin",
onRequest: async (requset, context) => {
//do something
//do something
},
}
```
@@ -260,7 +260,7 @@ const myPlugin = {
#### When to use Middelware, Hooks, On Request, On Response
- **Middlewares**: You should use middlewares when you want to use a route matcher to target a group of routes.
- **Middlewares**: You should use middlewares when you want to use a route matcher to target a group of routes.
- **Hooks**: You should use hooks when you want to target a specific route or request.
- **On Request & On Response**: You should use on request and on response when you want to do something that affects all requests or responses.
@@ -286,11 +286,11 @@ const myPlugin = {
### Client
If your endpoints needs to be called from the client, you'll need to also create a client plugin. Better auth clients can infer the endpoints from the server plugins. You can also add additional client side logic.
If your endpoints needs to be called from the client, you'll need to also create a client plugin. Better Auth clients can infer the endpoints from the server plugins. You can also add additional client side logic.
**Endpoint Inference**
Endpoints are inferred from the server plugin by adding a `$InferServerPlugin` key to the client plugin.
Endpoints are inferred from the server plugin by adding a `$InferServerPlugin` key to the client plugin.
The client infers the `path` as an object and converts kebab-case to camelCase. For example, `/my-plugin/hello-world` becomes `myPlugin.helloWorld`.
@@ -308,7 +308,7 @@ const myPluginClient = {
If you need to add additional methods or what not to the client you can use the `getActions` function. This function is called with the `fetch` function from the client.
Better auth uses <Link href="https://bette-fetch.vercel.app"> Better fetch </Link> to make requests. Better fetch is a simple fetch wrapper made by the same author of Better Auth.
Better Auth uses <Link href="https://bette-fetch.vercel.app"> Better fetch </Link> to make requests. Better fetch is a simple fetch wrapper made by the same author of Better Auth.
```ts title="client-plugin.ts"
import type { BetterAuthClientPlugin } from "better-auth/client";
@@ -344,7 +344,7 @@ const myPluginClient = {
**getAtoms**
This is only useful if you want to provide `hooks` like `useSession`.
This is only useful if you want to provide `hooks` like `useSession`.
Get atoms is called with the `fetch` function from better fetch and it should return an object with the atoms. This atoms should be created using <Link href="https://github.com/nanostores/nanostores">nanostore</Link>. The atoms will be resolved by each framework `useStore` hook provided by nanostore.
@@ -3,7 +3,7 @@ title: Session Management
description: Better Auth Session Management
---
Better auth manages session using a traditional cookie-based session management. The session is stored in a cookie and is sent to the server on every request. The server then verifies the session and returns the user data if the session is valid.
Better Auth manages session using a traditional cookie-based session management. The session is stored in a cookie and is sent to the server on every request. The server then verifies the session and returns the user data if the session is valid.
## Session table
@@ -17,7 +17,7 @@ The session table stores the session data. The session table has the following f
## Session Expiration
The session expires after 7 days by default. But whenever the session is used, and the `updateAge` is reached the session expiration is updated to the current time plus the `expiresIn` value.
The session expires after 7 days by default. But whenever the session is used, and the `updateAge` is reached the session expiration is updated to the current time plus the `expiresIn` value.
You can change both the `expiresIn` and `updateAge` values by passing the `session` object to the `auth` configuration.
@@ -35,7 +35,7 @@ export const auth = await betterAuth({
## Session Management
Better Auth provides a set of functions to manage sessions.
Better Auth provides a set of functions to manage sessions.
### List Sessions
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: Typescript
description: Better auth typescript integration
description: Better Auth typescript integration
---
Better Auth is designed to be type-safe. Both the client and server are built with TypeScript, allowing you to easily infer types.
@@ -3,7 +3,7 @@ title: User & Accounts
description: user and account management
---
Beyond authenticating users, better auth also provides a set of methods to manage users. This includes, updating user information, changing passwords, and more.
Beyond authenticating users, Better Auth also provides a set of methods to manage users. This includes, updating user information, changing passwords, and more.
## User table
@@ -77,7 +77,7 @@ The account table stores the authentication data of the user. The account table
Account linking allows users to link multiple authentication methods to the same account. This is useful when users want to sign in using different methods.
By default better auth allows account linking for all providers. You can disable account linking by setting `accountLinking.enabled` to `false`.
By default Better Auth allows account linking for all providers. You can disable account linking by setting `accountLinking.enabled` to `false`.
```ts
const auth = new BetterAuth({
account: {
@@ -88,7 +88,7 @@ const auth = new BetterAuth({
});
```
You can also specify, the list of providers that should be trusted. When a user signs in using a trusted provider, if the provider returns a verfied email, the user is automatically signed in.
You can also specify, the list of providers that should be trusted. When a user signs in using a trusted provider, if the provider returns a verfied email, the user is automatically signed in.
```ts
const auth = new BetterAuth({
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: Astro example
descirption: Better auth astro example
descirption: Better Auth astro example
---
This is an example of how to use Better Auth with Astro. It uses Solid for building the components.
+2 -2
View File
@@ -1,9 +1,9 @@
---
title: Next js example
descirption: Better auth next js example
descirption: Better Auth next js example
---
This is an example of how to use Better Auth with Next.
This is an example of how to use Better Auth with Next.
**Implements the following features:**
Email & Password . Social Sign-in . Passkeys . Email Verification . Password Reset . Two Factor Authentication . Profile Update . Session Management . Organizaition, Members and Roles
+2 -2
View File
@@ -1,12 +1,12 @@
---
title: Nuxt js example
descirption: better auth nuxt js example
descirption: Better Auth nuxt js example
---
This is an example of how to use Better Auth with Nuxt
**Implements the following features:**
Email & Password . Social Sign-in with Google
Email & Password . Social Sign-in with Google
<ForkButton url="better-auth/better-auth/tree/main/examples/nuxt-example" />
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: Astro example
descirption: Better auth astro example
descirption: Better Auth astro example
---
This is an example of how to use Better Auth with Remix.
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: Svelte Kit
descirption: Better auth Svelte Kit example
descirption: Better Auth Svelte Kit example
---
This is an example of how to use Better Auth with Svelte Kit.
+22 -22
View File
@@ -10,7 +10,7 @@ description: Learn how to configure Better Auth in your project.
Let's start by adding Better Auth to your project:
```package-install
```package-install
better-auth
```
@@ -140,7 +140,7 @@ If your database isn’t supported by Kysely, you can use an adapter to connect.
}),
});
```
</Tab>
</Tab>
<Tab value="drizzle">
```ts title="auth.ts"
@@ -155,7 +155,7 @@ If your database isn’t supported by Kysely, you can use an adapter to connect.
});
```
</Tab>
<Tab value="mongodb">
```ts title="auth.ts"
import { betterAuth } from "better-auth";
@@ -175,7 +175,7 @@ If your database isn’t supported by Kysely, you can use an adapter to connect.
<Step>
### Create Database Tables
Better Auth’s CLI helps manage your tables. You can either migrate tables directly or generate ORM schema/SQL migration files.
**Migrate**: Creates the required tables in the database.
@@ -187,7 +187,7 @@ If your database isn’t supported by Kysely, you can use an adapter to connect.
**Generate**: Creates an ORM schema or SQL migration file.
```bash title="Terminal"
npx better-auth generate
npx better-auth generate
```
see the [CLI documentation](/docs/concepts/cli) for more information.
@@ -199,7 +199,7 @@ If your database isn’t supported by Kysely, you can use an adapter to connect.
<Step>
### Authentication Methods
Configure the authentication methods you want to use. Better auth comes with built-in support for email/password, and social sign-on providers.
Configure the authentication methods you want to use. Better Auth comes with built-in support for email/password, and social sign-on providers.
```ts title="auth.ts"
import { betterAuth } from "better-auth"
@@ -213,10 +213,10 @@ export const auth = betterAuth({
socialProviders: { // [!code highlight]
github: { // [!code highlight]
clientId: process.env.GITHUB_CLIENT_ID, // [!code highlight]
clientSecret: process.env.GITHUB_CLIENT_SECRET, // [!code highlight]
clientSecret: process.env.GITHUB_CLIENT_SECRET, // [!code highlight]
} // [!code highlight]
}, // [!code highlight]
});
});
```
<Callout type="info">
@@ -226,12 +226,12 @@ You can use even more authentication methods like passkey, username, magic link
<Step>
### Mount Handler
To handle api requests, you need to set up a route handler on your server.
Create a new file or route in your framework's designated catch-all route handler. This route should handle requests for the path `/api/auth/*` (unless you've configured a different base path).
To handle api requests, you need to set up a route handler on your server.
Create a new file or route in your framework's designated catch-all route handler. This route should handle requests for the path `/api/auth/*` (unless you've configured a different base path).
<Callout>
Better auth supports any backend framework with standard Request and Response objects and offers helper functions for popular frameworks.
Better Auth supports any backend framework with standard Request and Response objects and offers helper functions for popular frameworks.
</Callout>
<Tabs items={["next-js", "remix", "nuxt", "svelte-kit", "solid-start", "hono", "express"]} defaultValue="react">
@@ -314,7 +314,7 @@ Better auth supports any backend framework with standard Request and Response ob
app.listen(port, () => {
console.log(`Better Auth app listening on port ${port}`);
});
```
```
This also works for any other node server framework like express, fastify, hapi, etc.
</Tab>
<Tab value="astro">
@@ -329,7 +329,7 @@ Better auth supports any backend framework with standard Request and Response ob
export const POST: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};
```
```
</Tab>
</Tabs>
</Step>
@@ -337,7 +337,7 @@ Better auth supports any backend framework with standard Request and Response ob
<Step>
### Create Client Instance
The client-side library helps you interact with the auth server. Better Auth comes with a client for all the popular web frameworks inlcuding for vanilla javascript.
The client-side library helps you interact with the auth server. Better Auth comes with a client for all the popular web frameworks inlcuding for vanilla javascript.
1. Import `createAuthClient` from the package for your framework (e.g., "better-auth/react" for React).
2. Call the function to create your client.
@@ -347,10 +347,10 @@ The client-side library helps you interact with the auth server. Better Auth com
If you're using a differnt base path other than `/api/auth` make sure to pass the whole url inlcuding the path. (e.g. `http://localhost:3000/custom-path/auth`)
</Callout>
<Tabs items={["react", "vue", "svelte", "solid",
<Tabs items={["react", "vue", "svelte", "solid",
"vanilla"]} defaultValue="react">
<Tab value="vanilla">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/client"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
@@ -358,7 +358,7 @@ If you're using a differnt base path other than `/api/auth` make sure to pass th
```
</Tab>
<Tab value="react" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/react"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
@@ -366,15 +366,15 @@ If you're using a differnt base path other than `/api/auth` make sure to pass th
```
</Tab>
<Tab value="vue" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/vue"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
})
```
</Tab>
<Tab value="svelte" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
<Tab value="svelte" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/svelte"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
@@ -382,7 +382,7 @@ If you're using a differnt base path other than `/api/auth` make sure to pass th
```
</Tab>
<Tab value="solid" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/solid"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
+12 -12
View File
@@ -1,17 +1,17 @@
---
title: Astro Integration
title: Astro Integration
description: Integrate Better Auth with Astro
---
Better auth comes with first class support for Astro. This guide will show you how to integrate better auth with Astro.
Better Auth comes with first class support for Astro. This guide will show you how to integrate Better Auth with Astro.
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
To enable Better Auth to handle requests, we need to mount the handler to a catch all API route. Create a file inside `/page/api/auth` called `[...all].ts` and add the following code:
```ts title="page/api/auth/[...all].ts"
```ts title="page/api/auth/[...all].ts"
import { auth } from "~/auth";
import type { APIRoute } from "astro";
@@ -31,41 +31,41 @@ Astro supports multiple frontend frameworks, so you can easily import your clien
If you're not using a frontend framework, you can still import the vanilla client.
<Tabs items={[ "vanilla", "react", "vue", "svelte", "solid",
<Tabs items={[ "vanilla", "react", "vue", "svelte", "solid",
]} defaultValue="react">
<Tab value="vanilla">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/client"
export const client = createAuthClient()
```
</Tab>
<Tab value="react" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/react"
export const client = createAuthClient()
```
</Tab>
<Tab value="vue" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/vue"
export const client = createAuthClient()
```
</Tab>
<Tab value="svelte" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
<Tab value="svelte" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/svelte"
export const client = createAuthClient()
```
</Tab>
<Tab value="solid" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts"
```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/solid"
export const client = createAuthClient()
```
</Tab>
</Tabs>
## Auth Middleware
## Auth Middleware
To protect your routes, you can check if the user is authenticated using the `getSession` method in middleware. Start by creating a `middleware.ts` file in the root of your project and follow the example below:
+1 -1
View File
@@ -5,7 +5,7 @@ description: Hono Integration Guide
This integration guide is assuming you are using Hono with node server.
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
+3 -3
View File
@@ -5,7 +5,7 @@ description: Learn how to integrate Better Auth with Next.js
Better Auth can be easily integrated with Next.js. It'll also comes with utilities to make it easier to use Better Auth with Next.js.
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Create API Route
@@ -35,13 +35,13 @@ export const client = createAuthClient({
```
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.
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.
The client also uses [better-fetch](https://github.com/bekacru/better-fetch) to make the requests. You can pass the fetch configuration to the client.
## RSC and Server actions
The `api` object exported from the auth instance contains all the actions that you can perform on the server. Every endpoint made inside better auth is a invokable as a function. Including plugins endpoints.
The `api` object exported from the auth instance contains all the actions that you can perform on the server. Every endpoint made inside Better Auth is a invokable as a function. Including plugins endpoints.
**Example: Getting Session on a server action**
+2 -2
View File
@@ -3,9 +3,9 @@ title: Node Integration
description: Integrate Better Auth with Node backend
---
Better auth can be integrated with node based backed frameworks. The guide below will show you how to integrate better auth with express.
Better Auth can be integrated with node based backed frameworks. The guide below will show you how to integrate Better Auth with express.
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
+2 -2
View File
@@ -3,7 +3,7 @@ title: Nuxt.js Integration
description: Learn how to integrate Better Auth with Nuxt.js
---
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Create API Route
@@ -40,7 +40,7 @@ export const client = createAuthClient({
```
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.
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
+2 -2
View File
@@ -1,9 +1,9 @@
---
title: Remix Integration
title: Remix Integration
description: Integrate Better Auth with Remix
---
Better Auth can be easily integrated with Remix. This guide will show you how to integrate better auth with Remix.
Better Auth can be easily integrated with Remix. This guide will show you how to integrate Better Auth with Remix.
You can follow the steps from [installation](/docs/installation) to get started or you can follow this guide to make it the Remix-way.
@@ -3,7 +3,7 @@ title: Solid Start Integration
description: Solid Start integratons guide
---
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
@@ -2,7 +2,7 @@
title: Svelte Kit Integration
description: Learn how to integrate Better Auth with Svelte Kit
---
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
+2 -2
View File
@@ -3,7 +3,7 @@ title: Introduction
description: Introduction to Better Auth.
---
Better Auth is framework-agnostic authentication (and authorization) library for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities. Whether you need 2FA, multi-tenant support, or other complex features. It lets you focus on building your actual application instead of reinventing the wheel.
Better Auth is framework-agnostic authentication (and authorization) library for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities. Whether you need 2FA, multi-tenant support, or other complex features. It lets you focus on building your actual application instead of reinventing the wheel.
## Why Better Auth?
@@ -11,7 +11,7 @@ Authentication in the TypeScript ecosystem is a half-solved problem. Other open-
## Features
Better auth aims to be the most comprehensive auth library. It provides a wide range of features out of the box and allows you to extend it with plugins. Here are some of the features:
Better Auth aims to be the most comprehensive auth library. It provides a wide range of features out of the box and allows you to extend it with plugins. Here are some of the features:
<Features/>
+12 -12
View File
@@ -29,7 +29,7 @@ This plugin offers two main methods to do a second factor verification:
```ts title="auth.ts"
import { betterAuth } from "better-auth"
import { twoFactor } from "better-auth/plugins" // [!code highlight]
export const auth = await betterAuth({
// ... other config options
plugins: [
@@ -53,17 +53,17 @@ This plugin offers two main methods to do a second factor verification:
<Step>
### Add the client Plugin
Add the client plugin and Specify where the user should be redirected if they need to verify 2nd factor
```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]
twoFactorClient({
twoFactorPage: "/two-factor" //redirect for two factor verification if enabled // [!code highlight]
})
]
})
@@ -180,9 +180,9 @@ const verifyTotp = async (code: string) => {
OTP (One-Time Password) is similar to TOTP but the code is sent directly to the user, and the code is valid for 3 mins by default.
Before using OTP to verify the second factor, you need to configure `sendOTP` in your better auth instance. This function is responsible for sending the OTP to the user's email, phone, or any other method supported by your application.
Before using OTP to verify the second factor, you need to configure `sendOTP` in your Better Auth instance. This function is responsible for sending the OTP to the user's email, phone, or any other method supported by your application.
```ts title="auth.ts"
```ts title="auth.ts"
import { betterAuth } from "better-auth"
import { twoFactor } from "better-auth/plugins"
@@ -278,7 +278,7 @@ When `trustDevice` is set to `true`, the current device will be remembered for 6
## Schema
The plugin requires 3 additional fields in the `user` table.
The plugin requires 3 additional fields in the `user` table.
<DatabaseTable
fields={[
@@ -296,7 +296,7 @@ The plugin requires 3 additional fields in the `user` table.
**TOTP options**
these are options for TOTP.
these are options for TOTP.
<TypeTable
type={{
@@ -354,18 +354,18 @@ backup codes are generated and stored in the database when the user enabled two
}}
/>
### Client
### Client
To use the two factor plugin in the client, you need to add it on your plugins list.
```ts title="client.ts"
```ts title="client.ts"
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]
twoFactorPage: "/two-factor" // [!code highlight]
}) // [!code highlight]
] // [!code highlight]
})
+4 -4
View File
@@ -11,15 +11,15 @@ List of all the available options for configuring Better Auth.
### `baseURL`
`string` (default: `/`) - Base URL for the better auth. This is typically the root URL where your application server is hosted. If not explicitly set, better auth check the following environment variable: `BETTER_AUTH_URL`.
`string` (default: `/`) - Base URL for the Better Auth. This is typically the root URL where your application server is hosted. If not explicitly set, Better Auth check the following environment variable: `BETTER_AUTH_URL`.
### `basePath`
`string` (default: `/api/auth`) - Base path for the better auth API. This is the path where better auth API will be mounted.
`string` (default: `/api/auth`) - Base path for the Better Auth API. This is the path where Better Auth API will be mounted.
### `secret`
`string` - Random value used by the library for encryption and generating hashes.
`string` - Random value used by the library for encryption and generating hashes.
### `database`
@@ -106,7 +106,7 @@ const auth = await betterAuth({
### `plugins`
`Plugin[]` - List of plugins to use with better auth.
`Plugin[]` - List of plugins to use with Better Auth.
### `user`