better-auth by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill better-authBetter Auth 是一个类型安全的 TypeScript 身份验证框架,支持多种提供商、双因素认证、单点登录、组织和通行密钥。本技能涵盖了使用 Drizzle ORM + PostgreSQL 的 NestJS 后端与 Next.js App Router 前端的集成模式。
# Backend (NestJS)
npm install better-auth @auth/drizzle-adapter drizzle-orm pg
npm install -D drizzle-kit
# Frontend (Next.js)
npm install better-auth
完整后端设置请参阅 references/nestjs-setup.md,插件配置请参阅 references/plugins.md。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
安装依赖项
npm install drizzle-orm pg @auth/drizzle-adapter better-auth
npm install -D drizzle-kit
创建 Drizzle 配置 (drizzle.config.ts)
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/auth/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: { url: process.env.DATABASE_URL! },
});
生成并运行迁移
npx drizzle-kit generate
npx drizzle-kit migrate
检查点:验证表是否创建:psql $DATABASE_URL -c "\dt" 应显示 user、account、session、verification_token 表。
创建数据库模块 - 设置 Drizzle 连接服务
配置 Better Auth 实例
// src/auth/auth.instance.ts
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@auth/drizzle-adapter';
import * as schema from './schema';
export const auth = betterAuth({
database: drizzleAdapter(schema, { provider: 'postgresql' }),
emailAndPassword: { enabled: true },
socialProviders: {
github: {
clientId: process.env.AUTH_GITHUB_CLIENT_ID!,
clientSecret: process.env.AUTH_GITHUB_CLIENT_SECRET!,
}
}
});
创建身份验证控制器
@Controller('auth')
export class AuthController {
@All('*')
async handleAuth(@Req() req: Request, @Res() res: Response) {
return auth.handler(req);
}
}
检查点:测试端点 GET /auth/get-session 在未认证时应返回 { session: null }(无错误)。
配置身份验证客户端 (lib/auth.ts)
import { createAuthClient } from 'better-auth/client';
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_APP_URL!
});
添加中间件 (middleware.ts)
import { auth } from '@/lib/auth';
export default auth((req) => {
if (!req.auth && req.nextUrl.pathname.startsWith('/dashboard')) {
return Response.redirect(new URL('/sign-in', req.nextUrl.origin));
}
});
export const config = { matcher: ['/dashboard/:path*'] };
创建登录页面,包含表单或社交登录按钮
检查点:当未登录时,导航到 /dashboard 应重定向到 /sign-in。
从 references/plugins.md 添加插件:
twoFactor({ issuer: 'AppName', otpOptions: { sendOTP } })passkey({ rpID: 'domain.com', rpName: 'App' })organization({ avatar: { enabled: true } })magicLink({ sendMagicLink })sso({ saml: { enabled: true } })检查点:添加插件后,重新运行迁移并验证新表是否存在。
输入:在 Next.js 服务器组件中显示用户数据。
// app/dashboard/page.tsx
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await auth();
if (!session) {
redirect('/sign-in');
}
return (
<div>
<h1>Welcome, {session.user.name}</h1>
<p>Email: {session.user.email}</p>
</div>
);
}
输出:为已认证用户渲染用户信息;将未认证用户重定向到登录页面。
输入:用户已启用双因素认证并希望登录,将设备标记为可信。
// Server: Configure 2FA with OTP sending
export const auth = betterAuth({
plugins: [
twoFactor({
issuer: 'MyApp',
otpOptions: {
async sendOTP({ user, otp }, ctx) {
await sendEmail({
to: user.email,
subject: 'Your verification code',
body: `Code: ${otp}`
});
}
}
})
]
});
// Client: Verify TOTP and trust device
const verify2FA = async (code: string) => {
const { data } = await authClient.twoFactor.verifyTotp({
code,
trustDevice: true // Device trusted for 30 days
});
if (data) {
router.push('/dashboard');
}
};
输出:用户已认证;设备可信 30 天,期间无需双因素认证提示。
输入:启用通行密钥(WebAuthn)认证以实现无密码登录。
// Server
import { passkey } from '@better-auth/passkey';
export const auth = betterAuth({
plugins: [
passkey({
rpID: 'example.com',
rpName: 'My App',
})
]
});
// Client: Register passkey
const registerPasskey = async () => {
const { data } = await authClient.passkey.register({
name: 'My Device'
});
};
// Client: Sign in with autofill
const signInWithPasskey = async () => {
await authClient.signIn.passkey({
autoFill: true, // Browser suggests passkey
});
};
输出:用户可以使用生物识别、PIN 码或安全密钥进行注册和认证。
更多示例(备份代码、组织、魔法链接、条件 UI)请参阅 references/plugins.md 和 references/passkey.md。
.env 中,并添加到 .gitignoreopenssl rand -base64 32 生成 BETTER_AUTH_SECRETngrok)email、userId 添加索引以提高性能npx better-auth typegen 获得完整的 TypeScript 覆盖.env 添加到 .gitignore;切勿提交 OAuth 密钥或数据库凭据references/nestjs-setup.md - 完整的 NestJS 后端设置references/nextjs-setup.md - 完整的 Next.js 前端设置references/plugins.md - 插件配置(双因素认证、通行密钥、组织、单点登录、魔法链接)references/mfa-2fa.md - 详细的多因素认证/双因素认证指南references/passkey.md - 详细的通行密钥实现references/schema.md - Drizzle 模式参考references/social-providers.md - 社交提供商配置每周安装量
220
代码仓库
GitHub 星标数
176
首次出现
2026年2月20日
安全审计
已安装于
codex196
gemini-cli194
github-copilot192
cursor189
kimi-cli189
opencode189
Better Auth is a type-safe authentication framework for TypeScript supporting multiple providers, 2FA, SSO, organizations, and passkeys. This skill covers integration patterns for NestJS backend with Drizzle ORM + PostgreSQL and Next.js App Router frontend.
# Backend (NestJS)
npm install better-auth @auth/drizzle-adapter drizzle-orm pg
npm install -D drizzle-kit
# Frontend (Next.js)
npm install better-auth
See references/nestjs-setup.md for complete backend setup, references/plugins.md for plugin configuration.
Install dependencies
npm install drizzle-orm pg @auth/drizzle-adapter better-auth
npm install -D drizzle-kit
Create Drizzle config (drizzle.config.ts)
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/auth/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: { url: process.env.DATABASE_URL! },
});
Generate and run migrations
npx drizzle-kit generate
npx drizzle-kit migrate
Checkpoint : Verify tables created: psql $DATABASE_URL -c "\dt" should show user, account, session, verification_token tables.
Create database module - Set up Drizzle connection service
Configure Better Auth instance
// src/auth/auth.instance.ts
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@auth/drizzle-adapter';
import * as schema from './schema';
export const auth = betterAuth({
database: drizzleAdapter(schema, { provider: 'postgresql' }),
emailAndPassword: { enabled: true },
socialProviders: {
github: {
clientId: process.env.AUTH_GITHUB_CLIENT_ID!,
clientSecret: process.env.AUTH_GITHUB_CLIENT_SECRET!,
}
}
});
Create auth controller
@Controller('auth')
export class AuthController {
@All('*')
async handleAuth(@Req() req: Request, @Res() res: Response) {
return auth.handler(req);
}
}
Checkpoint : Test endpoint GET /auth/get-session returns { session: null } when unauthenticated (no error).
Configure auth client (lib/auth.ts)
import { createAuthClient } from 'better-auth/client';
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_APP_URL!
});
Add middleware (middleware.ts)
import { auth } from '@/lib/auth';
export default auth((req) => {
if (!req.auth && req.nextUrl.pathname.startsWith('/dashboard')) {
return Response.redirect(new URL('/sign-in', req.nextUrl.origin));
}
});
export const config = { matcher: ['/dashboard/:path*'] };
Create sign-in page with form or social buttons
Checkpoint : Navigating to /dashboard when logged out should redirect to /sign-in.
Add plugins from references/plugins.md:
2FA : twoFactor({ issuer: 'AppName', otpOptions: { sendOTP } })
Passkey : passkey({ rpID: 'domain.com', rpName: 'App' })
Organizations : organization({ avatar: { enabled: true } })
Magic Link : magicLink({ sendMagicLink })
SSO : sso({ saml: { enabled: true } })
Checkpoint : After adding plugins, re-run migrations and verify new tables exist.
Input : Display user data in a Next.js Server Component.
// app/dashboard/page.tsx
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await auth();
if (!session) {
redirect('/sign-in');
}
return (
<div>
<h1>Welcome, {session.user.name}</h1>
<p>Email: {session.user.email}</p>
</div>
);
}
Output : Renders user info for authenticated users; redirects unauthenticated to sign-in.
Input : User has 2FA enabled and wants to sign in, marking device as trusted.
// Server: Configure 2FA with OTP sending
export const auth = betterAuth({
plugins: [
twoFactor({
issuer: 'MyApp',
otpOptions: {
async sendOTP({ user, otp }, ctx) {
await sendEmail({
to: user.email,
subject: 'Your verification code',
body: `Code: ${otp}`
});
}
}
})
]
});
// Client: Verify TOTP and trust device
const verify2FA = async (code: string) => {
const { data } = await authClient.twoFactor.verifyTotp({
code,
trustDevice: true // Device trusted for 30 days
});
if (data) {
router.push('/dashboard');
}
};
Output : User authenticated; device trusted for 30 days without 2FA prompt.
Input : Enable passkey (WebAuthn) authentication for passwordless login.
// Server
import { passkey } from '@better-auth/passkey';
export const auth = betterAuth({
plugins: [
passkey({
rpID: 'example.com',
rpName: 'My App',
})
]
});
// Client: Register passkey
const registerPasskey = async () => {
const { data } = await authClient.passkey.register({
name: 'My Device'
});
};
// Client: Sign in with autofill
const signInWithPasskey = async () => {
await authClient.signIn.passkey({
autoFill: true, // Browser suggests passkey
});
};
Output : Users can register and authenticate with biometrics, PIN, or security keys.
For more examples (backup codes, organizations, magic link, conditional UI), see references/plugins.md and references/passkey.md.
.env, add to .gitignoreopenssl rand -base64 32 for BETTER_AUTH_SECRETngrok for local testing)email, userId for performance.env to .gitignore; never commit OAuth secrets or DB credentialsreferences/nestjs-setup.md - Complete NestJS backend setupreferences/nextjs-setup.md - Complete Next.js frontend setupreferences/plugins.md - Plugin configuration (2FA, passkey, organizations, SSO, magic link)references/mfa-2fa.md - Detailed MFA/2FA guidereferences/passkey.md - Detailed passkey implementationreferences/schema.md - Drizzle schema referencereferences/social-providers.md - Social provider configurationWeekly Installs
220
Repository
GitHub Stars
176
First Seen
Feb 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex196
gemini-cli194
github-copilot192
cursor189
kimi-cli189
opencode189
xdrop 文件传输脚本:Bun 环境下安全上传下载工具,支持加密分享
28,800 周安装
npx better-auth typegen