docs: improve basic usage guide

This commit is contained in:
Bereket Engida
2025-02-07 17:55:55 +03:00
parent f4c89b8f5e
commit 93b26d4777

View File

@@ -8,9 +8,7 @@ Better Auth provides built-in authentication support for:
- **Email and password**
- **Social provider (Google, GitHub, Apple, and more)**
<Callout>
You can extend authentication options using plugins, such as: Username-based login, Passkeys, Email magic links, and more.
</Callout>
But also can easily be extended using plugins, such as: [username](/docs/plugins/username), [magic link](/docs/plugins/magic-link), [passkey](/docs/plugins/passkey), [email-otp](/docs/plugins/email-otp), and more.
## Email & Password
@@ -20,7 +18,6 @@ To enable email and password authentication:
import { betterAuth } from "better-auth"
export const auth = betterAuth({
//...rest of the options
emailAndPassword: { // [!code highlight]
enabled: true // [!code highlight]
} // [!code highlight]
@@ -29,67 +26,37 @@ export const auth = betterAuth({
### 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.
To sign up a user you need to call the client method `signUp.email` with the user's information.
You can pass the following properties to the `signUp.email` method:
- **email**: the user's email address
- **password**: the user's password
- **name**: the user's display name
- **image**: the user's image url (optional)
- **callbackURL**: a callbackURL if email verification is enabled.
**Example: Using React**
```tsx title="SignUp.tsx"
"use client"
```ts title="sign-up.ts"
import { authClient } from "@/lib/auth-client"; //import the auth client // [!code highlight]
import { useState } from 'react';
export default function SignUp() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [image, setImage] = useState<File | null>(null);
const signUp = async () => {
const { data, error } = await authClient.signUp.email({ // [!code highlight]
email, // [!code highlight]
password, // [!code highlight]
name, // [!code highlight]
image: image ? convertImageToBase64(image) : undefined, // [!code highlight]
}, { // [!code highlight]
onRequest: (ctx) => { // [!code highlight]
//show loading // [!code highlight]
}, // [!code highlight]
onSuccess: (ctx) => { // [!code highlight]
//redirect to the dashboard // [!code highlight]
}, // [!code highlight]
onError: (ctx) => { // [!code highlight]
alert(ctx.error.message); // [!code highlight]
}, // [!code highlight]
}); // [!code highlight]
};
return (
<div>
<input type="name" value={name} onChange={(e) => setName(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>
);
}
const { data, error } = await authClient.signUp.email({
email, // user email address
password, // user password -> min 8 characters by default
name, // user display name
image, // user image url (optional)
callbackURL: "/dashboard" // a url to redirect to after the user verifies their email (optional)
}, {
onRequest: (ctx) => {
//show loading
},
onSuccess: (ctx) => {
//redirect to the dashboard or sign in page
},
onError: (ctx) => {
// display the error message
alert(ctx.error.message);
},
});
```
By default, the user is automatically signed in after signing up. This behaviour can be changed by configuring your `auth-config`
By default, the users are automatically signed in after they successfully sign up. To disable this behavior you can set `autoSignIn` to `false`.
```js
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = betterAuth({
//...rest of the options
emailAndPassword: {
enabled: true,
autoSignIn: false //defaults to true // [!code highlight]
@@ -97,60 +64,67 @@ export const auth = betterAuth({
})
```
### Sign In
To sign a user in, you can use the `signIn.email` function provided by the client. The `signIn` function takes an object with the following properties:
To sign a user in, you can use the `signIn.email` function provided by the client.
- **email**: the user's email address
- **password**: the user's password
**Example: Using Svelte**
```svelte title="signin.svelte"
<script lang="ts">
import { authClient } from "$lib/auth-client"; //import the auth client // [!code highlight]
import { writable } from "svelte/store";
const email = writable("");
const password = writable("");
const handleSignIn = async () => {
await authClient.signIn.email({ // [!code highlight]
email: $email, // [!code highlight]
password: $password, // [!code highlight]
}, { // [!code highlight]
onRequest: () => { // [!code highlight]
//show loading // [!code highlight]
}, // [!code highlight]
onSuccess: () => { // [!code highlight]
//redirect to dashboard // [!code highlight]
}, // [!code highlight]
onError: (ctx) => { // [!code highlight]
alert(ctx.error.message) // [!code highlight]
} // [!code highlight]
}) // [!code highlight]
}
</script>
<div>
<input type="email" bind:value={$email} />
<input type="password" bind:value={$password} />
<button on:click={handleSignIn}>
Sign In
</button>
</div>
```ts title="sign-in"
const { data, error } = await authClient.signIn.email({
/**
* The user email
*/
email,
/**
* The user password
*/
password,
/**
* a url to redirect to after the user verifies their email (optional)
*/
callbackURL: "/dashboard",
/**
* remember the user session after the browser is closed.
* @default true
*/
rememberMe: false
}, {
//callbacks
})
```
<Callout type="warn">
Always invoke client methods from the client side. Don't call them from the server.
</Callout>
### Server-Side Authentication
To authenticate a user on the server, you can use the `auth.api` methods.
```ts title="server.ts"
import { auth } from "./auth"; // path to your Better Auth server instance
const response = await auth.api.signInEmail({
body: {
email,
password
},
asResponse: true // returns a response object instead of data
});
```
<Callout>
If the server cannot return a response object, you'll need to manually parse and set cookies. But for frameworks like Next.js we provide [a plugin](/docs/integrations/next#server-action-cookies) to handle this automatically
</Callout>
## Social Sign-On
Better Auth supports multiple social providers, including Google, GitHub, Apple, Discord, and more. To use a social provider, you need to configure the ones you need in the `socialProviders` option on your `auth` object.
```ts title="auth.ts"
import { betterAuth } from "better-auth"
import { github } from "better-auth/social-providers"
import { betterAuth } from "better-auth";
export const auth = betterAuth({
//...rest of the options
socialProviders: { // [!code highlight]
github: { // [!code highlight]
clientId: process.env.GITHUB_CLIENT_ID!, // [!code highlight]
@@ -164,41 +138,38 @@ export const auth = betterAuth({
To sign in using a social provider you need to call `signIn.social`. It takes an object with the following properties:
- **provider**: the social provider name (e.g. `github`, `google`, `apple`, etc.)
- **callbackURL**: the URL to redirect to after the user authenticates with the provider. (default to "/")
- **errorCallbackURL**: the URL to redirect to if an error occurs during the sign in process. (optional)
- **newUserCallbackURL**: the URL to redirect to if the user is newly registered. (optional)
- **disableRedirect**: a boolean to disable the automatic redirect to the provider. This is useful when you want to show for example a popup. (optional)
```ts title="sign-in.ts"
import { authClient } from "@/lib/auth-client"; //import the auth client // [!code highlight]
and more options to do `idToken` authentication.
**Example: Using Vue**
```vue title="signin.vue"
<script>
import { authClient } from "@/auth-client"; //import the auth client // [!code highlight]
export default {
name: "SignIn",
methods: {
async handleSignIn() {
await authClient.signIn.social({ // [!code highlight]
provider: "github", // [!code highlight]
callbackURL: "/dashboard", //redirect to dashboard after sign in // [!code highlight]
}); // [!code highlight]
}
}
};
</script>
<template>
<div>
<h2>Sign In</h2>
<button @click="handleSignIn">Sign In with GitHub</button>
</div>
</template>
await authClient.signIn.social({
/**
* The social provider id
* @example "github", "google", "apple"
*/
provider: "github",
/**
* a url to redirect after the user authenticates with the provider
* @default "/"
*/
callbackURL: "/dashboard",
/**
* a url to redirect if an error occurs during the sign in process
*/
errorCallbackURL: "/error",
/**
* a url to redirect if the user is newly registered
*/
newUserCallbackURL: "/welcome",
/**
* disable the automatic redirect to the provider.
* @default false
*/
disableRedirect: true,
});
```
You can also authenticate using `idToken` or `accessToken` from the social provider instead of redirecting the user to the provider's site. See social providers documentation for more details.
## Signout
To signout a user, you can use the `signOut` function provided by the client.
@@ -219,19 +190,15 @@ await authClient.signOut({
});
```
## Session Management
## Session
Once a user is signed in, you'll want to access the user session. Better Auth allows you easily to access the session data from the server and client side.
### Client Side
Better Auth provides a `useSession` hook to easily access session data on the client side. This hook is implemented using nanostore and has support for each supported framework and vanilla client, ensuring that any changes to the session (such as signing out) are immediately reflected in your UI.
#### Use Session
It has the following properties:
- **data**: the actual session data which includes `session` and `user` object.
- **isPending**: a boolean that indicates whether the session is being loaded.
- **refetch**: a function that re-fetches the session and updates the value for all `useSession` usages.
- **error**: an error object that contains any errors that occurred while loading the session.
Better Auth provides a `useSession` hook to easily access session data on the client side. This hook is implemented using nanostore and has support for each supported framework and vanilla client, ensuring that any changes to the session (such as signing out) are immediately reflected in your UI.
<Tabs items={["React", "Vue","Svelte", "Solid", "Vanilla"]} defaultValue="React">
<Tab value="React">
@@ -311,9 +278,17 @@ It has the following properties:
</Tab>
</Tabs>
<Callout>
For more details check [session-management](/docs/concepts/session-management) documentation.
</Callout>
#### Get Session
If you prefer not to use the hook, you can use the `getSession` method provided by the client.
```ts title="user.tsx"
import { authClient } from "@/lib/auth-client" // import the auth client // [!code highlight]
const { data: session, error } = await authClient.getSession()
```
You can also use it with client-side data-fetching libraries like [TanStack Query](https://tanstack.com/query/latest).
### Server Side
@@ -414,6 +389,10 @@ The server provides a `session` object that you can use to access the session da
</Tab>
</Tabs>
<Callout>
For more details check [session-management](/docs/concepts/session-management) documentation.
</Callout>
## Using Plugins
One of the unique features of Better Auth is a plugins ecosystem. It allows you to add complex auth related functionality with small lines of code.