docs: imporvements

This commit is contained in:
Bereket Engida
2024-09-26 12:40:08 +03:00
parent 74a3e9a311
commit 560909307b
10 changed files with 118 additions and 225 deletions

View File

@@ -225,8 +225,8 @@ export const contents: Content[] = [
),
},
{
title: "User & Accounts",
href: "/docs/concepts/user-accounts",
title: "Users & Accounts",
href: "/docs/concepts/users-accounts",
icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -263,45 +263,7 @@ export const contents: Content[] = [
),
},
{
title: "Email & Password",
Icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1.4em"
height="1.4em"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
fillRule="evenodd"
d="M3.172 5.172C2 6.343 2 8.229 2 12c0 3.771 0 5.657 1.172 6.828C4.343 20 6.229 20 10 20h4c3.771 0 5.657 0 6.828-1.172C22 17.657 22 15.771 22 12c0-3.771 0-5.657-1.172-6.828C19.657 4 17.771 4 14 4h-4C6.229 4 4.343 4 3.172 5.172M8 13a1 1 0 1 0 0-2a1 1 0 0 0 0 2m5-1a1 1 0 1 1-2 0a1 1 0 0 1 2 0m3 1a1 1 0 1 0 0-2a1 1 0 0 0 0 2"
clipRule="evenodd"
/>
</svg>
),
href: "/docs/authentication/email-password",
list: [
{
title: "Introduction",
href: "/docs/authentication/email-password",
icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1.2em"
height="1.2em"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="M5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h4.2q.35-.9 1.1-1.45T12 1t1.7.55T14.8 3H19q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm7-16.75q.325 0 .538-.213t.212-.537t-.213-.537T12 2.75t-.537.213t-.213.537t.213.538t.537.212M12 13q1.45 0 2.475-1.025T15.5 9.5t-1.025-2.475T12 6T9.525 7.025T8.5 9.5t1.025 2.475T12 13m-7 6h14v-1.15q-1.35-1.325-3.137-2.087T12 15t-3.863.763T5 17.85z"
></path>
</svg>
),
},
],
},
{
title: "Social Sign-On",
title: "Authentication",
Icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -318,25 +280,31 @@ export const contents: Content[] = [
</svg>
),
list: [
// {
// title: "Email & Password",
// href: "/docs/authentication/email-password",
// icon: () => (
// <svg
// xmlns="http://www.w3.org/2000/svg"
// width="1.2em"
// height="1.2em"
// viewBox="0 0 24 24"
// >
// <path
// fill="currentColor"
// fillRule="evenodd"
// d="M3.172 5.172C2 6.343 2 8.229 2 12c0 3.771 0 5.657 1.172 6.828C4.343 20 6.229 20 10 20h4c3.771 0 5.657 0 6.828-1.172C22 17.657 22 15.771 22 12c0-3.771 0-5.657-1.172-6.828C19.657 4 17.771 4 14 4h-4C6.229 4 4.343 4 3.172 5.172M8 13a1 1 0 1 0 0-2a1 1 0 0 0 0 2m5-1a1 1 0 1 1-2 0a1 1 0 0 1 2 0m3 1a1 1 0 1 0 0-2a1 1 0 0 0 0 2"
// clipRule="evenodd"
// />
// </svg>
// ),
// },
{
title: "Email & Password",
href: "/docs/authentication/email-password",
icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1.2em"
height="1.2em"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
fillRule="evenodd"
d="M3.172 5.172C2 6.343 2 8.229 2 12c0 3.771 0 5.657 1.172 6.828C4.343 20 6.229 20 10 20h4c3.771 0 5.657 0 6.828-1.172C22 17.657 22 15.771 22 12c0-3.771 0-5.657-1.172-6.828C19.657 4 17.771 4 14 4h-4C6.229 4 4.343 4 3.172 5.172M8 13a1 1 0 1 0 0-2a1 1 0 0 0 0 2m5-1a1 1 0 1 1-2 0a1 1 0 0 1 2 0m3 1a1 1 0 1 0 0-2a1 1 0 0 0 0 2"
clipRule="evenodd"
/>
</svg>
),
},
{
title: "Social Sign-On",
group: true,
icon: LucideAArrowDown,
href: "/",
},
{
title: "Apple",
href: "/docs/authentication/apple",

View File

@@ -9,9 +9,9 @@ Email and password authentication is a common method used by many applications.
If you prefer username-based authentication, check out the <Link href="/docs/plugins/username">username plugin</Link>. It extends the email and password authenticator with username support.
</Callout>
## Setup
## Emable Email and Password
To enable email and password authentication, add the following configuration to your Better Auth instance:
To enable email and password authentication, you need to set the `emailAndPassword.enabled` option to `true` in the `auth` configuration.
```ts title="auth.ts"
import { betterAuth } from "better-auth"
@@ -43,16 +43,9 @@ To signup a user, you can use the `signUp.email` function provided by the client
- `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)
- `dontRememberMe`: If true, the user will be signed out when the browser is closed. (optional)
```ts title="client.ts" /
/**
* Make sure to import the client for your framework
*/
import { createAuthClient } from "better-auth/client"
const client = createAuthClient()
- `dontRememberMe`: If true, the user will be signed out when the browser session is closed. (optional)
```ts title="client.ts"
const signup = async () => {
const data = await client.signUp.email({
email: "test@example.com",
@@ -64,12 +57,6 @@ const signup = async () => {
}
```
The function returns a promise that resolves an object with `data` and `error` properties. The `data` property contains the user object that was created, and the `error` property contains any error that occurred during the signup process.
<Callout type="info">
Hover over the `data` object to see the shape of the response.
</Callout>
### Signin
To signin a user, you can use the `signIn.email` function provided by the client. The `signIn` function takes an object with the following properties:
@@ -95,10 +82,12 @@ const signin = async () => {
### Email Verification
To enable email verification, you need to configure the email and password authenticator. You can do this by adding the following code to your better auth instance:
To enable email verification, you need to provider `sendVerificationEmail` function to the email and password authenticator. The `sendVerificationEmail` function takes an object with the following properties:
- `email`: The email address of the user.
- `url`: The url to send to the user which contains the token.
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = await betterAuth({
@@ -111,7 +100,7 @@ export const auth = await betterAuth({
})
```
on the client side you can use `sendVerificationEmail` function to send verification link to user.
on the client side you can use `sendVerificationEmail` function to send verification link to user. This will trigger the `sendVerificationEmail` function you provided in the `auth` configuration.
```ts title="client.ts"
const verifyEmail = async () => {
@@ -122,6 +111,10 @@ const verifyEmail = async () => {
}
```
Once the user clicks on the link in the email, if the token is valid, the user will be redirected to the URL provided in the `callbackURL` parameter. If the token is invalid, the user will be redirected to the URL provided in the `callbackURL` parameter with an error message in the query string `?error=invalid_token`.
```ts title="client.ts"
### Forget Password
to allow users to reset a password first you need to provider `sendResetPassword` function to the email and password authenticator. The `sendResetPassword` function takes an object with the following properties:
@@ -165,18 +158,12 @@ const forgetPassword = async () => {
When user click on the link in the email he will be redirected to the reset password page. You can add the reset password page to your app. Then you can use `resetPassword` function to reset the password. It takes an object with the following properties:
- `token`: The token that was generated.
- `newPassword`: The new password of the user.
```ts title="client.ts"
const token = useSearchParams().get("token") // get token from url
const resetPassword = async () => {
if(!token) return
const data = await client.resetPassword({
token: token,
newPassword: "password1234",
})
}
const data = await client.resetPassword({
newPassword: "password1234",
})
```
### Configuration
@@ -228,6 +215,7 @@ export const auth = betterAuth({
},
sendVerificationEmail: {
description: 'send verification email. It takes a functions that takes two parameters: email and url.',
type: 'function',
},
password: {
description: 'password configuration',

View File

@@ -33,7 +33,7 @@ await auth.api.signInEmail({
})
```
**Example: Getting the current Session**
**Example: Getting the current Session In Next JS**
```ts title="server.ts"
import { headers } from "next/server";
@@ -44,24 +44,5 @@ await auth.api.getSession({
})
```
Unlike the client, the server needs the values to be passed as an object with the key `body` for the body, `headers` for the headers, and `query` for the query.
## Handling Errors
Unlike the client, the server doesn't return error as a value, instead it throws an error. You can use a try/catch block to handle errors.
```ts title="server.ts"
try {
await auth.api.signInEmail({
body: {
email: "",
password: ""
}
})
} catch (error) {
console.error(error)
}
```
<Callout>
On some cases, the server will return an error object or just a value that indicates non successful value. Mostly, the server will throw an error.
</Callout>

View File

@@ -3,7 +3,7 @@ title: Client
description: Better Auth client library for authentication
---
Better auth provides a client library that you can use with different popular frontend frameworks such as React, Vue, Svelte, and more. The client library provides a set of functions to interact with the Better Auth server.
Better Auth offers a client library compatible with popular frontend frameworks like React, Vue, Svelte, and more. This client library includes a set of functions for interacting with the Better Auth server. Each framework's client library is built on top of a core client library that is framework-agnostic, so that all methods and hooks are consistently available across all client libraries.
## Installation
@@ -68,7 +68,7 @@ If you're using a different base path other than `/api/auth`, make sure to pass
## Usage
Once you've created your client instance, you can use the client to interact with the Better Auth server. The client provides a set of functions by default and they can be extended with plugins.
Once you've created your client instance, you can use the client to interact with the Better Auth server. The client provides a set of functions by default and they can be extended with plugins.
**Example: Sign In**
@@ -82,12 +82,13 @@ await client.signIn.email({
})
```
### Session
### Hooks
The client provides a `useSession` hook to access the current user session. The `useSession` hook returns the current user session and updates automatically when the session changes.
on top of normal methods, the client provides hooks to easily access differnt reactive data. Every hook is avaliable in the root object of the client and they all start with `use`.
Better Auth provides a `useSession` hook to easily access session data on the client side. This hook is implemented in a reactive way for each supported framework, ensuring that any changes to the session (such as signing out) are immediately reflected in your UI.
**Example: useSession**
<Tabs items={["React", "Vue","Svelte", "Solid"]} defaultValue="React">
<Tab value="React">
@@ -198,7 +199,7 @@ The client uses a libray called [better fetch](https://better-fetch.vercel.app)
Better fetch is a wrapper around the native fetch API that provides a more convenient way to make requests. It's created by the same team behind Better Auth and is designed to work seamlessly with it.
You can pass any defualt fetch options to the client by passing `fetchOptions` object to the `createAuthClient` function.
You can pass any defualt fetch options to the client by passing `fetchOptions` object to the `createAuthClient`.
```ts title="client.ts"
import { createAuthClient } from "better-auth/client"
@@ -210,9 +211,20 @@ const client = createAuthClient({
})
```
You can also pass fetch options to most of the client functions. For example, you can pass `fetchOptions` to the `signIn` function to customize the request.
You can also pass fetch options to most of the client functions. Either as the second argument or as a property in the object.
```ts title="client.ts"
await client.signIn.email({
email: "email@email.com",
password: "password1234",
}, {
onSuccess(ctx){
//
}
})
//or
await client.signIn.email({
email: "email@email.com",
password: "password1234",
@@ -249,6 +261,17 @@ if(error){
If the functions accepte a `fetchOptions` object, you can pass an `onError` function to handle errors.
```ts title="client.ts"
await client.signIn.email({
email: "email@email.com",
password: "password1234",
}, {
onError(ctx){
//handle error
}
})
//or
await client.signIn.email({
email: "email@email.com",
password: "password1234",
@@ -283,4 +306,12 @@ const client = createAuthClient({
magicLinkClient()
]
})
```
once you've added the plugin, you can use the new functions provided by the plugin.
```ts title="client.ts"
await client.signIn.magicLink({
email: "test@email.com"
})
```

View File

@@ -68,33 +68,35 @@ The cli checks your database and prompts you to add missing tables or update exi
npx better-auth migrate
```
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.
## Core Schema
Better auth requires the following tables to be present in the database:
**user**:
- `id`: The unique identifier of the user.
- `email`: The email address of the user.
- `name`: The name of the user.
- `image`: The image of the user.
- `id`: (string) - The unique identifier of the user.
- `email`: (string) - The email address of the user.
- `name`: (string) - The name of the user.
- `image`: (string) - The image of the user. (optional)
**session**:
- `id`: The unique identifier of the session. Also used as the session token.
- `userId`: The id of the user.
- `expiresAt`: The time when the session expires.
- `ipAddress`: The IP address of the user.
- `userAgent`: The user agent of the user.
- `id`: (string) - The unique identifier of the session. Also used as the session token.
- `userId`: (foregin-key: `user.id`) - The id of the user.
- `expiresAt`: (Date) - The time when the session expires.
- `ipAddress`: (string) - The IP address of the device. (optional)
- `userAgent`: (string) - The user agent information of the device. (optional)
**account**:
- `id`: The unique identifier of the account.
- `userId`: The id of the user.
- `accountId`: The id of the account. (optional)
- `providerId`: The id of the provider. (optional)
- `accessToken`: The access token of the account. Returned by the provider. (optional)
- `refreshToken`: The refresh token of the account. Returned by the provider. (optional)
- `expiresAt`: The time when the access token expires. (optional)
- `password`: The password of the account. Mainly used for email and password authentication. (optional)
- `id`: (string) - The unique identifier of the account.
- `userId`: (foregin-key: `user.id`) - The id of the user.
- `accountId`: (string) - The id of the account. (optional)
- `providerId`: (string) - The id of the provider. (optional)
- `accessToken`: (string) - The access token of the account. Returned by the provider. (optional)
- `refreshToken`: (string) - The refresh token of the account. Returned by the provider. (optional)
- `expiresAt`: (Date) - The time when the access token expires. (optional)
- `password`: (string) - The password of the account. Mainly used for email and password authentication. (optional)
## Plugins Schema

View File

@@ -43,7 +43,7 @@ const client = createAuthClient({
To create a plugin you need to pass an object that satsfies the `BetterAuthPlugin` interface.
The only required key is `id`, which is a unique identifier for the plugin.
The only required property is `id`, which is a unique identifier for the plugin.
```ts title="plugin.ts"
const myPlugin = {
@@ -87,14 +87,14 @@ Create Auth endpoints wraps around `createEndpoint` from Better Call. Inside the
- `authCookie`: The defualt cookie configuration for core auth cookies.
- `logger`: The logger instance used by Better Auth.
- `db`: The kysely instance used by Better Auth to interact with the database.
- `password`: The password configuration. Includes `hash` and `verify` values for hashing and verifying passwords.
- `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
For other properties, you can check the <Link href="https://github.com/bekacru/better-call">Better Call</Link> documentation.
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**
**Rules for Endpoints**
- Makes sure you use kebab-case for the endpoint path.
- Make sure to only use `POST` or `GET` methods for the endpoints.

View File

@@ -1,5 +1,5 @@
---
title: User & Account
title: User & Accounts
description: user and account management
---

View File

@@ -1,29 +0,0 @@
---
title: Email & Password
decription: Learn how to use email and password authentication with Better Auth
---
Email and password authentication is a common method used by many applications. Better Auth provides a robust and secure way to authenticate users using email and password with minimal effort.
<Callout>
If you want to add username-based authentication, check out the username plugin. It extends the email and password authenticator with username support.
</Callout>
## Getting Started
Email and password authentication is disabled by default. To enable it, you need to enable the email and password authenticator in the Better Auth configuration.
```ts title="auth.ts"
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
//...other configurations
emailAndPassword: {
enabled: true,
},
})
```
<Callout>
Unless you explicitly enable the email and password authenticator, it will not allow users to sign up or sign in using email and password.
</Callout>

View File

@@ -1,55 +0,0 @@
---
title: Sign In & Sign Up
description: Learn how to sign in and sign up users using email and password with Better Auth
---
Once you have enabled the email and password authenticator, you can start signing in and signing up users using email and password.
## Sign Up
Before a user can sign in, they need to sign up. To sign up a user using email and password, you need to call the client method `signUp.email` with the user's information.
**Example: Using React**
```tsx title="SignUp.tsx"
import { authClient } from '@/auth'; //import the auth client
export default function SignUp() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [image, setImage] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(false);
const signUp = async () => {
const res = await authClient.signUp.email({
email,
password,
name,
image: image ? convertImageToBase64(image) : undefined,
}, {
onRequest: (ctx) => {
setLoading(true);
},
onsSuccess: (ctx) => {
setLoading(false);
//redirect to the dashboard
},
onError: (ctx) => {
setLoading(false);
alert(ctx.error.message);
},
});
};
return (
<div>
<input type="name" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="file" onChange={(e) => setImage(e.target.files?.[0])} />
<button onClick={signUp}>Sign Up</button>
</div>
);
}
```

View File

@@ -10,6 +10,7 @@ function checkHasPath(url: string): boolean {
);
}
}
a;
function withPath(url: string, path = "/api/auth") {
const hasPath = checkHasPath(url);
@@ -24,13 +25,19 @@ export function getBaseURL(url?: string, path?: string) {
if (url) {
return withPath(url, path);
}
const env: any = typeof process !== "undefined" ? process.env : {};
const env: any =
typeof process !== "undefined"
? process.env
: (import.meta as any)?.env
? (import.meta as any).env
: {};
const fromEnv =
env.BETTER_AUTH_URL ||
env.NEXT_PUBLIC_BETTER_AUTH_URL ||
env.PUBLIC_BETTER_AUTH_URL ||
env.NUXT_PUBLIC_BETTER_AUTH_URL ||
env.NUXT_PUBLIC_AUTH_URL;
env.NUXT_PUBLIC_AUTH_URL ||
env.BASE_URL;
if (fromEnv) {
return withPath(fromEnv, path);
}