Better Auth is a authentication framework for TypeScript. It is designed to be simple and easy to use, while also being powerful and flexible. It does so by providing a set of basic building blocks that can be used to create your authentication flow, and a large collection of plugins that can be used to extend the framework.
Concepts
To understand how Better Auth works, it is important to understand the concepts which it is built on. I will only cover the most important ones here, but if you want to learn more, you can check out the documentation.
API
The API is the core of Better Auth, you can access it by creating a BetterAuth
instance. In a Create TNT Stack app this step is done for you. The API can be
accessed by importing the auth
object from @/server/auth
.
The API exposes a set of methods that can be used to create your authentication flow. Below you can see an example of how to use the API to get the current user's session.
import { headers } from "next/headers"
import { auth } from "@/server/auth"
await auth.api.getSession({
headers: await headers(),
})
You can use the API to create Next.js server actions. Simply export a function
that uses the auth.api
object. Ensure the file includes the "use server"
directive.
Client
The client library is similar to the API, but it is designed to be used with frontend frameworks like React. It includes a set of methods that can be used to create your authentication flow. Below you can see an example of how to use the client library to get the current user's session.
import { useSession } from "@/src/lib/auth/client"
const {
data: session,
isPending, // loading state
error, // error object
refetch, // refetch the session
} = useSession()
CLI
The CLI is a powerful, built-in tool to help you manage your database schemas, and more.
Generate
The generate
command is used to generate the schema required for Better Auth.
When using Prisma or Drizzle, this command will generate the appropriate schema
for your ORM.
pnpm dlx @better-auth/cli@latest generate
For more information on the generate
command, check out the
CLI documentation.
Migrate
The migrate
command is used to apply the generated schema to your database.
This command is NOT available when you are using an ORM. If you are using Prisma
or Drizzle, you must apply the generated schema manually using the provided
migration commands.
pnpm dlx @better-auth/cli@latest migrate
For more information on the migrate
command, check out the
CLI documentation.
Secret
Create TNT Stack will automatically generate a secret for you. However, if you
want to generate a new secret, you can use the secret
command.
pnpm dlx @better-auth/cli@latest secret
Useful Resources
Resource | Description |
---|---|
Better Auth Docs | The official documentation for Better Auth. |
Better Auth Community | Join the Better Auth community |
Better Auth GitHub | Better Auth GitHub repository |