auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth Configuration
身份验证配置
1. The Specialized Auth Bounded Context
1. 专用的Auth限界上下文
The auth Bounded Context is a specialized module. Unlike standard 4-layer DDD modules, it acts strictly as an infrastructural bridge wrapping the Better Auth library. You MUST adhere to the following file responsibilities:
- Server Configuration (): The single source of truth for the Server Configuration (adapters, plugins, session logic).
auth.ts - Client Configuration (): The Client Configuration. Exports
auth-client.tsfor use increateAuthClientcomponents to invoke sign-in flows (e.g.,"use client").signIn.magicLink - Session Wrapper (): A wrapper utility that bridges the session to Domain Use Cases, preventing direct dependencies on Next.js headers inside the Domain.
getSession.ts - UI Components: UI components exclusive to authentication (Login views, magic link forms).
- Email Templates: React Email templates used for outbound transactional emails.
Auth限界上下文是一个专用模块。与标准的四层DDD模块不同,它严格作为封装Better Auth库的基础设施桥梁存在。你必须遵守以下文件职责划分:
- 服务端配置():服务端配置的唯一可信来源(包含适配器、插件、会话逻辑)。
auth.ts - 客户端配置():客户端配置文件。导出
auth-client.ts供createAuthClient组件调用登录流程(例如"use client")。signIn.magicLink - 会话包装器():将会话与领域用例桥接的工具类,避免领域层直接依赖Next.js请求头。
getSession.ts - UI组件:专用于身份验证的UI组件(登录视图、魔法链接表单)。
- 邮件模板:用于发送事务性邮件的React Email模板。
2. Server Configuration Rules (auth.ts
)
auth.ts2. 服务端配置规则(auth.ts
)
auth.tsWhen modifying , you MUST follow these constraints:
auth.ts- Drizzle Adapter: The MUST be used. It MUST map to the PostgreSQL schema via
drizzleAdapter(orsrc/shared/infrastructure/postgres/schema.tsas configured).drizzle-postgres/ - UUID Generation: Because this project enforces strict Domain-Driven Design (DDD) using UUIDv7 as identity primitives, you MUST override the default random string generation in Better Auth.
typescript
advanced: { generateId: false, // Let Postgres/Drizzle default generate the UUIDv7 } // or if strictly handled within the library: advanced: { database: { generateId: "uuid", // Assuming standard UUID mapping } } - Environment Variables: All secret keys (e.g., ,
GOOGLE_CLIENT_ID) MUST be imported directly fromRESEND_API_KEY. You MUST NOT usesrc/shared/infrastructure/load-env.ts.process.env - Plugins: For passwordless entry, use the and
magicLinkplugins.emailOTP
修改时,必须遵循以下约束:
auth.ts- Drizzle适配器:必须使用,且必须通过
drizzleAdapter(或配置好的src/shared/infrastructure/postgres/schema.ts)映射到PostgreSQL schema。drizzle-postgres/ - UUID生成:由于本项目采用严格的领域驱动设计(DDD),以UUIDv7作为身份原语,你必须覆盖Better Auth中的默认随机字符串生成逻辑。
typescript
advanced: { generateId: false, // 让Postgres/Drizzle默认生成UUIDv7 } // 或者如果严格在库内处理: advanced: { database: { generateId: "uuid", // 假设使用标准UUID映射 } } - 环境变量:所有密钥(如、
GOOGLE_CLIENT_ID)必须直接从RESEND_API_KEY导入,禁止使用src/shared/infrastructure/load-env.ts。process.env - 插件:无密码登录需使用和
magicLink插件。emailOTP
3. Email Infrastructure (Resend & react-email
)
react-email3. 邮件基础设施(Resend & react-email
)
react-emailYou MUST NOT use the library's default basic email sender logic.
- Both and
magicLinkplugins MUST be configured to use Resend.emailOTP - The instance MUST be imported from the centralized service container.
resend - The email HTML bodies MUST be generated using React components. You MUST NOT write raw HTML string templates inside .
auth.ts - Dependencies: You MUST use the library (which includes components like
@react-email/components,<Html>,<Head>) to build these templates safely. The templates are rendered to static markup before being sent via Resend.<Button>
禁止使用库自带的基础邮件发送逻辑。
- 和
magicLink插件必须配置为使用Resend。emailOTP - 实例必须从中心化服务容器导入。
resend - 邮件HTML内容必须使用React组件生成,禁止在中编写原始HTML字符串模板。
auth.ts - 依赖要求:必须使用库(包含
@react-email/components、<Html>、<Head>等组件)安全构建这些模板。模板会先渲染为静态标记,再通过Resend发送。<Button>
4. OAuth Providers (Google Login)
4. OAuth提供商(Google登录)
When setting up Google authentication or other social providers:
- You MUST fetch and read the official documentation at to understand the setup process.
https://better-auth.com/docs/authentication/google - You MUST provide the user with clear, step-by-step instructions on how to configure the Google Cloud Console (OAuth consent screen, Authorized JavaScript origins, and Redirect URIs).
- You MUST ask the user to obtain the and
GOOGLE_CLIENT_IDand add them to theirGOOGLE_CLIENT_SECRETfile, ensuring they are also strictly managed via.env.src/shared/infrastructure/load-env.ts
配置Google身份验证或其他社交提供商时:
- 必须查阅官方文档了解配置流程。
https://better-auth.com/docs/authentication/google - 必须为用户提供清晰的分步说明,指导其配置Google Cloud Console(OAuth consent screen、授权JavaScript源、重定向URI)。
- 必须要求用户获取和
GOOGLE_CLIENT_ID并添加到GOOGLE_CLIENT_SECRET文件,同时确保这些变量通过.env严格管理。src/shared/infrastructure/load-env.ts
5. Retrieving Auth State in Next.js
5. 在Next.js中获取身份验证状态
In Server Actions
在服务端动作(Server Actions)中
You MUST protect Server Actions. Obtaining the user session MUST be the very first operation inside the action.
typescript
import { auth } from "@/auth/auth";
import { headers } from "next/headers";
// Inside the server action
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
return { success: false, error: "UNAUTHORIZED" };
}必须保护服务端动作,获取用户会话必须是动作内的第一个操作。
typescript
import { auth } from "@/auth/auth";
import { headers } from "next/headers";
// 在服务端动作内部
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
return { success: false, error: "UNAUTHORIZED" };
}In Server Components
在服务端组件(Server Components)中
Server Components can fetch the session the same way to dictate layout logic or pass user data down the tree.
typescript
import { auth } from "@/auth/auth";
import { headers } from "next/headers";
const session = await auth.api.getSession({ headers: await headers() });服务端组件可通过相同方式获取会话,以控制布局逻辑或向下传递用户数据。
typescript
import { auth } from "@/auth/auth";
import { headers } from "next/headers";
const session = await auth.api.getSession({ headers: await headers() });In Client Components
在客户端组件(Client Components)中
Client components MUST use hooks generated by (e.g., ) if they need reactive auth state.
auth-client.tsuseSession()如果需要响应式身份验证状态,客户端组件必须使用生成的钩子(例如)。
auth-client.tsuseSession()6. Bridging Auth to Use Cases
6. 身份验证与用例的桥接
Domain Use Cases MUST NOT know about , HTTP headers, or Next.js. Any Use Case requiring the current user's ID MUST receive it as part of its isolated payload.
Better AuthParamsThe Server Action acts as the adapter:
- Server Action calls .
auth.api.getSession() - Extracts .
session.user.id - Passes the ID standardly via .
serviceContainer.module.useCase.execute({ userId: session.user.id, ...params })
领域用例不得知晓、HTTP请求头或Next.js相关内容。任何需要当前用户ID的用例,必须将其作为独立负载的一部分传入。
Better AuthParams服务端动作作为适配器:
- 服务端动作调用。
auth.api.getSession() - 提取。
session.user.id - 通过标准化传递ID。
serviceContainer.module.useCase.execute({ userId: session.user.id, ...params })
7. References
7. 参考资料
For practical examples, you MUST refer to:
- Auth Reference: A complete reference showing how the the , schemas, Resend integration, and
drizzleAdapter/magicLinkplugins are combined following these strict rules.emailOTP
如需实用示例,必须参考:
- 身份验证参考:完整参考文档,展示如何遵循这些严格规则组合使用、schemas、Resend集成以及
drizzleAdapter/magicLink插件。emailOTP