Logo Better Auth

Better Auth

Cộng đồng
einverne
better-auth

Guide for implementing Better Auth - a framework-agnostic authentication and authorization framework for TypeScript. Use when adding authentication features like email/password, OAuth, 2FA, passkeys, or advanced auth functionality to applications.

Tổng quan

Nhà phát hànheinverne
Kho mãdotfiles
Tên kỹ năngbetter-auth
Sao
121
Bản fork
24
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được einverne công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Better Auth trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/einverne/dotfiles/tree/master/claude/skills/better-auth
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/einverne/dotfiles.git /tmp/dotfiles
mkdir -p .claude/skills
cp -r /tmp/dotfiles/claude/skills/better-auth .claude/skills/better-auth
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Better Auth trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Better Auth ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Better Auth với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Better Auth Skill

Better Auth is a comprehensive, framework-agnostic authentication and authorization framework for TypeScript that provides built-in support for email/password authentication, social sign-on, and a powerful plugin ecosystem for advanced features.

When to Use This Skill

Use this skill when:

  • Implementing authentication in TypeScript/JavaScript applications
  • Adding email/password or social OAuth authentication
  • Setting up 2FA, passkeys, magic links, or other advanced auth features
  • Building multi-tenant applications with organization support
  • Implementing session management and user management
  • Working with any framework (Next.js, Nuxt, SvelteKit, Remix, Astro, Hono, Express, etc.)

Core Concepts

Key Features

  • Framework Agnostic: Works with any framework (Next.js, Nuxt, Svelte, Remix, Hono, Express, etc.)
  • Built-in Auth Methods: Email/password and OAuth 2.0 social providers
  • Plugin Ecosystem: Easy-to-add advanced features (2FA, passkeys, magic link, username, email OTP, organization, etc.)
  • Database Flexibility: Supports SQLite, PostgreSQL, MySQL, MongoDB, and more
  • ORM Support: Built-in adapters for Drizzle, Prisma, Kysely, and MongoDB
  • Type Safety: Full TypeScript support with excellent type inference
  • Session Management: Built-in session handling for both client and server

Architecture

Better Auth follows a client-server architecture:

  1. Server Instance (better-auth): Handles auth logic, database operations, and API routes
  2. Client Instance (better-auth/client): Provides hooks and methods for authentication
  3. Plugins: Extend both server and client functionality

Installation & Setup

Step 1: Install Package

bash
npm install better-auth
# or
pnpm add better-auth
# or
yarn add better-auth
# or
bun add better-auth

Step 2: Environment Variables

Create .env file:

env
BETTER_AUTH_SECRET=<generated-secret-key>
BETTER_AUTH_URL=http://localhost:3000

Generate secret: Use openssl or a random string generator (min 32 characters).

Step 3: Create Auth Server Instance

Create auth.ts in project root, lib/, utils/, or nested under src/, app/, or server/:

ts
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  database: {
    // Database configuration
  },
  emailAndPassword: {
    enabled: true,
    autoSignIn: true // Users auto sign-in after signup
  },
  socialProviders: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    },
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }
  }
});

Step 4: Database Configuration

Choose your database setup:

Direct Database Connection:

ts
import { betterAuth } from "better-auth";
import Database from "better-sqlite3";
// or import { Pool } from "pg";
// or import { createPool } from "mysql2/promise";

export const auth = betterAuth({
  database: new Database("./sqlite.db"),
  // or: new Pool({ connectionString: process.env.DATABASE_URL })
  // or: createPool({ host: "localhost", user: "root", ... })
});

ORM Adapter:

ts
// Drizzle
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg", // or "mysql", "sqlite"
  }),
});

// Prisma
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: "postgresql",
  }),
});

// MongoDB
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client } from "@/db";

export const auth = betterAuth({
  database: mongodbAdapter(client),
});

Step 5: Create Database Schema

Use Better Auth CLI:

bash
# Generate schema/migration files
npx @better-auth/cli generate

# Or migrate directly (Kysely adapter only)
npx @better-auth/cli migrate

Step 6: Mount API Handler

Create catch-all route for /api/auth/*:

Next.js (App Router):

ts
// app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { POST, GET } = toNextJsHandler(auth);

Nuxt:

ts
// server/api/auth/[...all].ts
import { auth } from "~/utils/auth";

export default defineEventHandler((event) => {
  return auth.handler(toWebRequest(event));
});

SvelteKit:

ts
// hooks.server.ts
import { auth } from "$lib/auth";
import { svelteKitHandler } from "better-auth/svelte-kit";

export async function handle({ event, resolve }) {
  return svelteKitHandler({ event, resolve, auth });
}

Hono:

ts
import { Hono } from "hono";
import { auth } from "./auth";

const app = new Hono();
app.on(["POST", "GET"], "/api/auth/*", (c) => auth.handler(c.req.raw));

Express:

ts
import express from "express";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./auth";

const app = express();
app.all("/api/auth/*", toNodeHandler(auth));

Step 7: Create Client Instance

Create auth-client.ts:

ts
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL || "http://localhost:3000"
});

Authentication Methods

Email & Password

Server Configuration:

ts
export const auth = betterAuth({
  emailAndPassword: {
    enabled: true,
    autoSignIn: true, // default: true
  }
});

Client Usage:

ts
// Sign Up
const { data, error } = await authClient.signUp.email({
  email: "user@example.com",
  password: "securePassword123",
  name: "John Doe",
  image: "https://example.com/avatar.jpg", // optional
  callbackURL: "/dashboard" // optional
}, {
  onSuccess: (ctx) => {
    // redirect or show success
  },
  onError: (ctx) => {
    alert(ctx.error.message);
  }
});

// Sign In
const { data, error } = await authClient.signIn.email({
  email: "user@example.com",
  password: "securePassword123",
  callbackURL: "/dashboard",
  rememberMe: true // default: true
});

Social OAuth

Server Configuration:

ts
export const auth = betterAuth({
  socialProviders: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    },
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
    // Other providers: apple, discord, facebook, etc.
  }
});

Client Usage:

ts
await authClient.signIn.social({
  provider: "github",
  callbackURL: "/dashboard",
  errorCallbackURL: "/error",
  newUserCallbackURL: "/welcome",
});

Sign Out

ts
await authClient.signOut({
  fetchOptions: {
    onSuccess: () => {
      router.push("/login");
    }
  }
});

Session Management

Client-Side Session

Using Hooks (React/Vue/Svelte/Solid):

tsx
// React
import { authClient } from "@/lib/auth-client";

export function UserProfile() {
  const { data: session, isPending, error } = authClient.useSession();

  if (isPending) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Welcome, {session?.user.name}!</div>;
}

// Vue
<script setup>
import { authClient } from "~/lib/auth-client";
const session = authClient.useSession();
</script>

<template>
  <div v-if="session.data">{{ session.data.user.email }}</div>
</template>

// Svelte
<script>
import { authClient } from "$lib/auth-client";
const session = authClient.useSession();
</script>

<p>{$session.data?.user.email}</p>

Using getSession:

ts
const { data: session, error } = await authClient.getSession();

Server-Side Session

ts
// Next.js
import { auth } from "./auth";
import { headers } from "next/headers";

const session = await auth.api.getSession({
  headers: await headers()
});

// Hono
app.get("/protected", async (c) => {
  const session = await auth.api.getSession({
    headers: c.req.raw.headers
  });

  if (!session) {
    return c.json({ error: "Unauthorized" }, 401);
  }

  return c.json({ user: session.user });
});

Plugin System

Better Auth's plugin system allows adding advanced features easily.

Using Plugins

Server-Side:

ts
import { betterAuth } from "better-auth";
import { twoFactor, organization, username } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [
    twoFactor(),
    organization(),
    username(),
  ]
});

Client-Side:

ts
import { createAuthClient } from "better-auth/client";
import {
  twoFactorClient,
  organizationClient,
  usernameClient
} from "better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [
    twoFactorClient({
      twoFactorPage: "/two-factor"
    }),
    organizationClient(),
    usernameClient()
  ]
});

After Adding Plugins:

bash
# Regenerate schema
npx @better-auth/cli generate

# Apply migration
npx @better-auth/cli migrate

Popular Plugins

Two-Factor Authentication (2FA)
ts
// Server
import { twoFactor } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [twoFactor()]
});

// Client
import { twoFactorClient } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [
    twoFactorClient({ twoFactorPage: "/two-factor" })
  ]
});

// Usage
await authClient.twoFactor.enable({ password: "userPassword" });
await authClient.twoFactor.verifyTOTP({
  code: "123456",
  trustDevice: true
});
Username Authentication
ts
// Server
import { username } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [username()]
});

// Client
import { usernameClient } from "better-auth/client/plugins";

// Sign up with username
await authClient.signUp.username({
  username: "johndoe",
  password: "securePassword123",
  name: "John Doe"
});
Magic Link
ts
import { magicLink } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [
    magicLink({
      sendMagicLink: async ({ email, url }) => {
        // Send email with magic link
        await sendEmail(email, url);
      }
    })
  ]
});
Passkey (WebAuthn)
ts
import { passkey } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [passkey()]
});

// Client
await authClient.passkey.register();
await authClient.passkey.signIn();
Organization/Multi-Tenancy
ts
import { organization } from "better-auth/plugins";

export const auth = betterAuth({
  plugins: [organization()]
});

// Client
await authClient.organization.create({
  name: "Acme Corp",
  slug: "acme"
});

await authClient.organization.inviteMember({
  organizationId: "org-id",
  email: "user@example.com",
  role: "member"
});

Advanced Configuration

Email Verification

ts
export const auth = betterAuth({
  emailVerification: {
    sendVerificationEmail: async ({ user, url }) => {
      await sendEmail(user.email, url);
    },
    sendOnSignUp: true
  }
});

Rate Limiting

ts
export const auth = betterAuth({
  rateLimit: {
    enabled: true,
    window: 60, // seconds
    max: 10 // requests
  }
});

Custom Session Expiration

ts
export const auth = betterAuth({
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days in seconds
    updateAge: 60 * 60 * 24 // Update every 24 hours
  }
});

CORS Configuration

ts
export const auth = betterAuth({
  advanced: {
    corsOptions: {
      origin: ["https://example.com"],
      credentials: true
    }
  }
});

Database Schema

Core Tables

Better Auth requires these core tables:

  • user: User accounts
  • session: Active sessions
  • account: OAuth provider connections
  • verification: Email verification tokens

Auto-generate with CLI:

bash
npx @better-auth/cli generate

Manual schema available in docs: Check /docs/concepts/database#core-schema

Best Practices

  1. Environment Variables: Always use environment variables for secrets
  2. HTTPS in Production: Set BETTER_AUTH_URL to HTTPS URL
  3. Session Security: Use secure cookies in production
  4. Error Handling: Implement proper error handling on client and server
  5. Type Safety: Leverage TypeScript types for better DX
  6. Plugin Order: Some plugins depend on others, check documentation
  7. Database Migrations: Always run migrations after adding plugins
  8. Rate Limiting: Enable rate limiting for production
  9. Email Verification: Implement email verification for security
  10. Password Requirements: Customize password validation as needed

Common Patterns

Protected Routes (Server-Side)

ts
// Next.js middleware
import { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

export async function middleware(request: NextRequest) {
  const session = await auth.api.getSession({
    headers: request.headers
  });

  if (!session) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"]
};

User Profile Updates

ts
await authClient.updateUser({
  name: "New Name",
  image: "https://example.com/new-avatar.jpg"
});

Password Management

ts
// Change password
await authClient.changePassword({
  currentPassword: "oldPassword",
  newPassword: "newPassword"
});

// Reset password (forgot password)
await authClient.forgetPassword({
  email: "user@example.com",
  redirectTo: "/reset-password"
});

await authClient.resetPassword({
  token: "reset-token",
  password: "newPassword"
});

Troubleshooting

Common Issues

  1. "Unable to find auth instance"

    • Ensure auth.ts is in correct location (root, lib/, utils/)
    • Export auth instance as auth or default export
  2. Database connection errors

    • Verify database credentials
    • Check if database server is running
    • Ensure correct adapter for your database
  3. CORS errors

    • Configure corsOptions in advanced settings
    • Ensure client and server URLs match
  4. Plugin not working

    • Run migrations after adding plugins
    • Check plugin is added to both server and client
    • Verify plugin configuration

Framework-Specific Guides

  • Next.js: Use Next.js plugin for server actions
  • Nuxt: Configure server middleware
  • SvelteKit: Use hooks.server.ts
  • Astro: Set up API routes properly
  • Hono/Express: Use appropriate node handlers

Resources

Implementation Checklist

When implementing Better Auth:

  • Install better-auth package
  • Set up environment variables (SECRET, URL)
  • Create auth server instance
  • Configure database/adapter
  • Run schema migration
  • Configure authentication methods
  • Mount API handler
  • Create client instance
  • Implement sign-up/sign-in UI
  • Add session management
  • Set up protected routes
  • Add plugins as needed
  • Test authentication flow
  • Configure email sending (if needed)
  • Set up error handling
  • Enable rate limiting for production

Câu hỏi thường gặp

Kỹ năng AI Better Auth làm được gì?

Guide for implementing Better Auth - a framework-agnostic authentication and authorization framework for TypeScript. Use when adding authentication features like email/password, OAuth, 2FA, passkeys, or advanced auth functionality to applications.

Vì sao nên dùng Better Auth trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Better Auth là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Better Auth trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/einverne/dotfiles/tree/master/claude/skills/better-auth. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Better Auth?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Better Auth với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Better Auth với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Better Auth có miễn phí không?

Có. Kỹ năng này được einverne phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇