Token导航 LogoToken导航TokenDH.com
开发敏感数据github未标认证来源可访问许可证需确认审计通过

api-auth-better-auth-drizzle-honoAPI auth better auth Drizzle hono 文档

Agent Skill

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

总安装

329

周安装

14

GitHub Stars

5

下载量

115
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:api-auth-better-auth-drizzle-hono(API auth better auth Drizzle hono 文档)
来源仓库:https://github.com/agents-inc/skills
仓库路径:skills/api-auth-better-auth-drizzle-hono
安装命令:
npx skills add https://github.com/agents-inc/skills --skill api-auth-better-auth-drizzle-hono
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/agents-inc/skills --skill api-auth-better-auth-drizzle-hono

简介

api-auth-better-auth-drizzle-hono 提供 Better Auth + Drizzle ORM + Hono 的全栈认证解决方案。

  • 适用于 Codex、Claude、Cursor、Gemini CLI 中快速搭建邮箱密码、OAuth、2FA 登录系统。
  • 支持插件化扩展,需先配置 CORS 再挂载 auth handler,确保跨域部署正常。
  • 使用前必须遵循项目 CLAUDE.md 规范,包括命名、导出与 import 顺序。
  • 禁止在未启用 session 的中间件后使用 auth 逻辑,防止状态不一致引发安全漏洞。

SKILL.md

Authentication with Better Auth

Quick Guide: Use Better Auth (v1.5+) for type-safe, self-hosted authentication in TypeScript apps. It provides email/password, OAuth, 2FA, sessions, stateless auth, and organization multi-tenancy. Plugin architecture enables progressive complexity. Mount auth handler before session-dependent middleware, configure CORS first for cross-origin deployments, and always run schema generation after adding plugins.

<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST mount Better Auth handler on the auth route BEFORE any other middleware that depends on session)

(You MUST configure CORS middleware BEFORE auth routes when client and server are on different origins)

(You MUST use environment variables for ALL secrets (clientId, clientSecret, BETTER_AUTH_SECRET) - NEVER hardcode)

(You MUST run npx auth@latest generate then your ORM migration tool after adding plugins)

(You MUST use auth.$Infer.Session types for type-safe session access in middleware)

</critical_requirements>


Auto-detection: Better Auth, betterAuth, createAuthClient, auth.handler, auth.api.getSession, socialProviders, twoFactor plugin, organization plugin, drizzleAdapter, session management, OAuth providers, stateless sessions, cookieCache, genericOAuth, oAuthProvider, passkey, SCIM

When to use:

  • Building self-hosted authentication (no vendor lock-in)
  • Need email/password + OAuth + 2FA in one solution
  • Multi-tenant SaaS with organization/team management
  • Type-safe session management
  • Projects requiring database-stored or stateless sessions

When NOT to use:

  • Need managed authentication with zero maintenance (consider hosted auth solutions)
  • Simple static sites without user accounts
  • Projects where serverless cold starts are critical (though stateless mode helps)

Key patterns covered:

  • Server configuration (auth.ts) with plugins
  • Session middleware and type-safe route protection
  • Email/password authentication flows
  • OAuth providers (GitHub, Google, Generic OAuth)
  • Two-factor authentication (TOTP)
  • Organization and multi-tenancy
  • Session strategies: database, cookie cache, stateless
  • Database adapter integration
  • Client-side useSession hook
  • Performance: experimental joins, cookie caching, stateless sessions

Detailed Resources:


Philosophy

Better Auth follows a TypeScript-first, self-hosted approach to authentication. Your user data stays in your database, with no vendor lock-in. The plugin architecture enables progressive complexity - start simple and add features as needed.

Core principles:

  1. Type safety throughout - Session types flow from server to client via auth.$Infer.Session
  2. Database as source of truth - Sessions stored in your DB (with optional stateless mode)
  3. Plugin-based extensibility - Add 2FA, organizations, passkeys, SCIM, OAuth provider when needed
  4. Framework-agnostic - Works with any TypeScript web framework
  5. Performance-focused - Experimental joins (2-3x faster), cookie caching, stateless sessions

Core Patterns

Pattern 1: Server Configuration (auth.ts)

Create the auth instance with database adapter. Single source of truth for all authentication config.

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

const SESSION_EXPIRES_IN_SECONDS = 60 * 60 * 24 * 7; // 7 days
const SESSION_UPDATE_AGE_SECONDS = 60 * 60 * 24; // Refresh daily

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg" }),
  emailAndPassword: {
    enabled: true,
    minPasswordLength: 8,
    maxPasswordLength: 128,
  },
  session: {
    expiresIn: SESSION_EXPIRES_IN_SECONDS,
    updateAge: SESSION_UPDATE_AGE_SECONDS,
  },
  trustedOrigins: [process.env.APP_URL || "http://localhost:3000"],
});

Why good: Named constants make session policy auditable, env vars for URLs, single exported instance

// BAD: Magic numbers, hardcoded secrets, default export
const auth = betterAuth({
  database: { url: "postgres://user:pass@localhost/db" },
  session: { expiresIn: 604800 },
});
export default auth;

Why bad: Hardcoded credentials leak in source control, magic numbers obscure policy, default export

See examples/core.md for full setup with email verification and Drizzle adapter configuration.


Pattern 2: Session Middleware with Type Safety

Mount auth handler and create typed middleware for session access in routes.

// CRITICAL: CORS must be configured BEFORE auth routes
app.use("/auth/*", cors({ origin: APP_URL, credentials: true }));
app.on(["POST", "GET"], "/auth/*", (c) => auth.handler(c.req.raw));
// middleware/auth-middleware.ts - Type-safe session access
type AuthVariables = {
  user: typeof auth.$Infer.Session.user | null;
  session: typeof auth.$Infer.Session.session | null;
};

export const authMiddleware = createMiddleware<{ Variables: AuthVariables }>(
  async (c, next) => {
    const session = await auth.api.getSession({ headers: c.req.raw.headers });
    c.set("user", session?.user ?? null);
    c.set("session", session?.session ?? null);
    await next();
  },
);

Why good: auth.$Infer.Session ensures c.get("user") is correctly typed, CORS before auth prevents preflight failures, c.req.raw provides the Web Standard Request that Better Auth expects

// BAD: No type annotation - c.user is any, bypasses type system
app.use("*", async (c, next) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers });
  c.user = session?.user; // any - no autocomplete
  await next();
});

Why bad: No AuthVariables type = any access, direct property assignment bypasses typed Variables

See examples/core.md for protected route patterns.


Pattern 3: Schema Generation After Plugins

Every plugin adds database tables. Run the CLI after adding or modifying plugins:

# Step 1: Generate Better Auth schema (outputs ORM-specific files)
npx auth@latest generate

# Step 2: Generate migration with your ORM tool
npx drizzle-kit generate

# Step 3: Apply migration
npx drizzle-kit migrate

Always run all 3 steps. The Better Auth migrate command only works with the Kysely adapter - for Drizzle, use generate + Drizzle Kit.


Pattern 4: Email/Password with Verification

Configure email/password auth with verification and password reset callbacks.

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg" }),
  emailAndPassword: {
    enabled: true,
    minPasswordLength: 8,
    maxPasswordLength: 128,
    requireEmailVerification: true,
    sendResetPassword: async ({ user, url }) => {
      await sendEmail({
        to: user.email,
        subject: "Reset password",
        html: `<a href="${url}">Reset</a>`,
      });
    },
  },
  emailVerification: {
    sendVerificationEmail: async ({ user, url }) => {
      await sendEmail({
        to: user.email,
        subject: "Verify email",
        html: `<a href="${url}">Verify</a>`,
      });
    },
  },
});

Why good: Email verification prevents fake signups, password requirements enforced server-side

See examples/core.md for client-side sign up/in hooks with error handling.


Pattern 5: Session Strategies

Three session approaches with different trade-offs:

StrategyDB RequiredRevocableBest For
Database (default)YesYesMost apps
Cookie cache + DBYesYes (delayed)Reduce DB load
StatelessNoNo (version-only)Edge/serverless
// Cookie cache: reduces DB hits by caching session in signed cookie
session: {
  cookieCache: { enabled: true, maxAge: CACHE_SECONDS, strategy: "compact" },
}

// Stateless: omit database option entirely
const auth = betterAuth({
  // No database = fully stateless
  session: { cookieCache: { enabled: true, strategy: "jwe" } },
});

Cookie cache strategies: compact (smallest, internal), jwt (standard, third-party verifiable), jwe (encrypted, hides data).

See examples/sessions.md for full configuration and revocation patterns.


<red_flags>

RED FLAGS

  • Hardcoded secrets (clientId/clientSecret in source) - must use environment variables
  • CORS configured after auth routes - preflight requests will fail
  • Missing BETTER_AUTH_SECRET env var - sessions will not work
  • No schema generation after adding plugins - database errors at runtime
  • Untyped session middleware - loses TypeScript safety, c.user becomes any
  • Using auth.migrate() with Drizzle adapter - only works with Kysely, use generate + Drizzle Kit
  • Missing c.req.raw when calling auth.handler() - must pass the raw Web Standard Request

Gotchas & Edge Cases:

  • Google only issues refresh tokens on first consent - use accessType: "offline" and prompt: "consent"
  • GitHub OAuth apps don't issue refresh tokens (access tokens are long-lived)
  • Stateless sessions cannot be revoked individually - increment version to invalidate all
  • Cookie cache revocation is delayed until maxAge expires on other devices
  • Session cookies need SameSite=None + Secure for cross-domain deployments
  • authClient.forgotPassword was renamed to authClient.requestPasswordReset in v1.4
  • InferUser/InferSession removed in v1.5 - use generic User and Session types from better-auth

See reference.md for anti-patterns with code examples, decision frameworks, and version notes.

</red_flags>


<critical_reminders>

CRITICAL REMINDERS

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST mount Better Auth handler on the auth route BEFORE any other middleware that depends on session)

(You MUST configure CORS middleware BEFORE auth routes when client and server are on different origins)

(You MUST use environment variables for ALL secrets (clientId, clientSecret, BETTER_AUTH_SECRET) - NEVER hardcode)

(You MUST run npx auth@latest generate then your ORM migration tool after adding plugins)

(You MUST use auth.$Infer.Session types for type-safe session access in middleware)

Failure to follow these rules will cause authentication failures, security vulnerabilities, or runtime errors.

</critical_reminders>

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.96%
按下载量换算41

Claude

28.36%
按下载量换算33

Cursor

21.34%
按下载量换算25

Gemini CLI

9.43%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills