Docs

Gettig Started with Better Auth

Install the Package

Let's start by adding Better Auth to your project:

npm install better-auth

If you're using a separate client and server setup, make sure to install Better Auth in both parts of your project. (currnelty better auth only supports web platforms more clients will be added soon)

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.

.env
BETTER_AUTH_SECRET=
  1. Set Base URL (optional)
.env
BETTER_AUTH_URL=http://localhost:3000 #Base URL of your app

Create A Better Auth Instance

Create a file named auth.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.

Make sure to export the auth instance with the variable name auth or as a default export.

auth.ts
import { betterAuth } from "better-auth"
 
export const auth = betterAuth({
    //...
})

Configure Database

Better Auth requires a database to store user data. It uses Kysely under the hood to connect to your database. postgresql, mysql, and sqlite are supported out of the box.

auth.ts
import { betterAuth } from "better-auth"
 
export const auth = betterAuth({
    database: { 
        provider: "sqlite", // or "mysql", "postgresql"
        url: "./db.sqlite", // path to your database or connection string
    } 
})

You can also pass any dialect that is supported by Kysely to the database configration.

Example with LibsqlDialect:

auth.ts
import { betterAuth } from "better-auth";
import { LibsqlDialect } from "@libsql/kysely-libsql";
 
export const auth = betterAuth({
	database: new LibsqlDialect({
		url: process.env.TURSO_DATABASE_URL || "",
		authToken: process.env.TURSO_AUTH_TOKEN || "",
	}),
});

Currently, Better Auth only support databases that are supported by Kysely. vote this issue if you like to see non sql db support

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:

Terminal
npx better-auth migrate

Better Auth automatically sets up the following tables in your database if they don't already exist:

  • user
  • session
  • account

For more details head over to schema section.

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.

import { betterAuth } from "better-auth"
import { github } from "better-auth/social-providers"
 
export const auth = betterAuth({
    database: {
        provider: "sqlite",
        url: "./db.sqlite",
    },
    emailAndPassword: {  
        enabled: true
    }
    socialProviders: { 
       github: { 
        clientId: process.env.GITHUB_CLIENT_ID, 
        clientSecret: process.env.GITHUB_CLIENT_SECRET, 
       } 
    }, 
}); 

You can use even more authentication methods like passkey, username, magic link and more through plugins.

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).

Better auth supports any backend framework with standard Request and Response objects and offers helper functions for popular frameworks.

/app/api/auth/[...all]/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);

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.

  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. (If the auth server is running on the same domain as your client, you can skip this step.)

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)

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
})

Tip: You can also export specific methods if you prefer:

export const { signIn, signUp, useSession } = createAuthClient()

🎉 That's it!

That's it! You're now ready to use better-auth in your application. Continue to basic usage to learn how to use the auth instance to sign in users.

On this page

Edit on GitHub