Files
better-auth/docs/_content/docs/installation.mdx
T

269 lines
8.5 KiB
Plaintext

---
title: Getting Started with Better Auth
description: A friendly guide to installing and setting up Better Auth
---
<Steps>
<Step>
### Install the Package
Let's start by adding Better Auth to your project:
```package-install
better-auth
```
<Callout type="info">
If you're using a separate client and server setup, make sure to install Better Auth in both parts of your project.
</Callout>
</Step>
<Step>
### Set Environment Variables
Create a `.env` file in the root of your project and add the following environment variables:
1. **Secret Key**
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/>
2. **Set Base URL (optional)**
```txt title=".env"
BETTER_AUTH_URL=http://localhost:3000 #Base URL of your app
```
</Step>
<Step>
### Create A Better Auth Instance
Create a file named `auth.ts` or `auth.config.ts` in one of these locations:
- Project root
- `lib/` folder
- `utils/` folder
You can also nest any of these folders under `src/` folder. (e.g. `src/lib/auth.ts`)
And in this file, import Better Auth and create your instance.
<Callout type="warn">
Make sure to export the auth instance with the variable name `auth` or as a `default` export.
</Callout>
```ts title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = betterAuth({
//...
})
```
</Step>
<Step>
### Configure Database
Better Auth requires a database to store user data. It currently only supports `sqlite`, `postgresql` and `mysql`.
You can pass a database provider (sqlite, mysql, postgresql) and connection string directly to the auth instance.
```ts twoslash title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = betterAuth({
database: { // [!code highlight]
provider: "sqlite", // or "mysql", "postgresql" // [!code highlight]
url: "./db.sqlite", // path to your database or connection string // [!code highlight]
} // [!code highlight]
})
```
<Callout type="info">
Better auth uses <Link href="https://kysely.dev/">Kysely</Link> under the hood to connect to your database. You can also pass any dialect that is supported by Kysely to the database configration.
</Callout>
</Step>
<Step>
### Migrate Schema
Better Auth includes a CLI tool to migrate the required schema to your database. It introspects the database and creates the required tables. Run the following command to perform the migration:
```bash title="Terminal"
npx better-auth migrate
```
</Step>
<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.
```ts
import { betterAuth } from "better-auth"
import { github } from "better-auth/social-providers"
export const auth = betterAuth({
database: {
provider: "sqlite",
url: "./db.sqlite",
},
socialProvider: [ // [!code highlight]
github({ // [!code highlight]
clientId: process.env.GITHUB_CLIENT_ID as string, // [!code highlight]
clientSecret: process.env.GITHUB_CLIENT_SECRET as string, // [!code highlight]
}), // [!code highlight]
], // [!code highlight]
emailAndPassword: { // [!code highlight]
enabled: true // [!code highlight]
}// [!code highlight]
});
```
<Callout type="info">
You can use even more authentication methods like passkey, username, magic link and more through plugins.
</Callout>
</Step>
<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).
<Tabs items={["next-js", "nuxt", "svelte-kit", "solid-start", "hono"]} defaultValue="react">
<Tab value="next-js">
```ts title="/app/api/[...auth]/route.ts"
import { auth } from "@/lib/auth"; // path to your auth file
import { toNextJsHandler } from "better-auth/next-js";
export const { POST, GET } = toNextJsHandler(auth);
```
</Tab>
<Tab value="nuxt">
```ts title="/server/api/[...auth].ts"
import { Hono } from "hono";
import { auth } from "./auth"; // path to your auth file
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);
```
</Tab>
<Tab value="svelte-kit">
```ts title="hooks.server.ts"
import { auth } from "$lib/auth"; // path to your auth file
import { svelteKitHandler } from "better-auth/svelte-kit";
export async function handle({ event, resolve }) {
return svelteKitHandler({ event, resolve, auth });
}
```
</Tab>
<Tab value="solid-start">
```ts title="/routes/api/auth/*auth.ts"
import { auth } from "~/lib/auth"; // path to your auth file
import { toSolidStartHandler } from "better-auth/solid-start";
export const { GET, POST } = toSolidStartHandler(auth);
```
</Tab>
<Tab value="hono">
```ts title="src/index.ts"
import { Hono } from "hono";
import { auth } from "./auth"; // path to your auth file
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);
```
</Tab>
</Tabs>
</Step>
<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 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.
3. Pass the base url of your auth server to the client.
<Callout type="info">
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",
"vanilla"]} defaultValue="react">
<Tab value="vanilla">
```ts title="lib/auth-client.ts" twoslash
import { createAuthClient } from "better-auth/client"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
})
```
</Tab>
<Tab value="react" title="lib/auth-client.ts">
```ts twoslash 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]
})
```
</Tab>
<Tab value="vue" title="lib/auth-client.ts">
```ts twoslash 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 twoslash 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]
})
```
</Tab>
<Tab value="solid" title="lib/auth-client.ts">
```ts title="lib/auth-client.ts" twoslash
import { createAuthClient } from "better-auth/solid"
export const client = createAuthClient({
baseURL: "http://localhost:3000" // the base url of your auth server // [!code highlight]
})
```
</Tab>
</Tabs>
<Callout type="info">
Tip: You can also export specific methods if you prefer:
</Callout>
```ts
export const { signIn, signUp, useSession } = createAuthClient()
```
</Step>
<Step>
### 🎉 That's it!
That's it! You're now ready to use better-auth in your application. Continue to [basic usage](/docs/basic-usage) to learn how to use the auth instance to sign in users.
</Step>
</Steps>