auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth 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 (
    auth.ts
    )
    : The single source of truth for the Server Configuration (adapters, plugins, session logic).
  • Client Configuration (
    auth-client.ts
    )
    : The Client Configuration. Exports
    createAuthClient
    for use in
    "use client"
    components to invoke sign-in flows (e.g.,
    signIn.magicLink
    ).
  • Session Wrapper (
    getSession.ts
    )
    : A wrapper utility that bridges the session to Domain Use Cases, preventing direct dependencies on Next.js headers inside the Domain.
  • 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
    )。
  • 会话包装器(
    getSession.ts
    :将会话与领域用例桥接的工具类,避免领域层直接依赖Next.js请求头。
  • UI组件:专用于身份验证的UI组件(登录视图、魔法链接表单)。
  • 邮件模板:用于发送事务性邮件的React Email模板。

2. Server Configuration Rules (
auth.ts
)

2. 服务端配置规则(
auth.ts

When modifying
auth.ts
, you MUST follow these constraints:
  1. Drizzle Adapter: The
    drizzleAdapter
    MUST be used. It MUST map to the PostgreSQL schema via
    src/shared/infrastructure/postgres/schema.ts
    (or
    drizzle-postgres/
    as configured).
  2. 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
      }
    }
  3. Environment Variables: All secret keys (e.g.,
    GOOGLE_CLIENT_ID
    ,
    RESEND_API_KEY
    ) MUST be imported directly from
    src/shared/infrastructure/load-env.ts
    . You MUST NOT use
    process.env
    .
  4. Plugins: For passwordless entry, use the
    magicLink
    and
    emailOTP
    plugins.
修改
auth.ts
时,必须遵循以下约束:
  1. Drizzle适配器:必须使用
    drizzleAdapter
    ,且必须通过
    src/shared/infrastructure/postgres/schema.ts
    (或配置好的
    drizzle-postgres/
    )映射到PostgreSQL schema。
  2. UUID生成:由于本项目采用严格的领域驱动设计(DDD),以UUIDv7作为身份原语,你必须覆盖Better Auth中的默认随机字符串生成逻辑。
    typescript
    advanced: {
      generateId: false, // 让Postgres/Drizzle默认生成UUIDv7
    }
    // 或者如果严格在库内处理:
    advanced: {
      database: {
        generateId: "uuid", // 假设使用标准UUID映射
      }
    }
  3. 环境变量:所有密钥(如
    GOOGLE_CLIENT_ID
    RESEND_API_KEY
    )必须直接从
    src/shared/infrastructure/load-env.ts
    导入,禁止使用
    process.env
  4. 插件:无密码登录需使用
    magicLink
    emailOTP
    插件。

3. Email Infrastructure (Resend &
react-email
)

3. 邮件基础设施(Resend &
react-email

You MUST NOT use the library's default basic email sender logic.
  1. Both
    magicLink
    and
    emailOTP
    plugins MUST be configured to use Resend.
  2. The
    resend
    instance MUST be imported from the centralized service container.
  3. The email HTML bodies MUST be generated using React components. You MUST NOT write raw HTML string templates inside
    auth.ts
    .
  4. Dependencies: You MUST use the
    @react-email/components
    library (which includes components like
    <Html>
    ,
    <Head>
    ,
    <Button>
    ) to build these templates safely. The templates are rendered to static markup before being sent via Resend.
禁止使用库自带的基础邮件发送逻辑。
  1. magicLink
    emailOTP
    插件必须配置为使用Resend
  2. resend
    实例必须从中心化服务容器导入。
  3. 邮件HTML内容必须使用React组件生成,禁止在
    auth.ts
    中编写原始HTML字符串模板。
  4. 依赖要求:必须使用
    @react-email/components
    库(包含
    <Html>
    <Head>
    <Button>
    等组件)安全构建这些模板。模板会先渲染为静态标记,再通过Resend发送。

4. OAuth Providers (Google Login)

4. OAuth提供商(Google登录)

When setting up Google authentication or other social providers:
  1. You MUST fetch and read the official documentation at
    https://better-auth.com/docs/authentication/google
    to understand the setup process.
  2. 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).
  3. You MUST ask the user to obtain the
    GOOGLE_CLIENT_ID
    and
    GOOGLE_CLIENT_SECRET
    and add them to their
    .env
    file, ensuring they are also strictly managed via
    src/shared/infrastructure/load-env.ts
    .
配置Google身份验证或其他社交提供商时:
  1. 必须查阅官方文档
    https://better-auth.com/docs/authentication/google
    了解配置流程。
  2. 必须为用户提供清晰的分步说明,指导其配置Google Cloud Console(OAuth consent screen、授权JavaScript源、重定向URI)。
  3. 必须要求用户获取
    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
auth-client.ts
(e.g.,
useSession()
) if they need reactive auth state.
如果需要响应式身份验证状态,客户端组件必须使用
auth-client.ts
生成的钩子(例如
useSession()
)。

6. Bridging Auth to Use Cases

6. 身份验证与用例的桥接

Domain Use Cases MUST NOT know about
Better Auth
, HTTP headers, or Next.js. Any Use Case requiring the current user's ID MUST receive it as part of its isolated
Params
payload.
The Server Action acts as the adapter:
  1. Server Action calls
    auth.api.getSession()
    .
  2. Extracts
    session.user.id
    .
  3. Passes the ID standardly via
    serviceContainer.module.useCase.execute({ userId: session.user.id, ...params })
    .
领域用例不得知晓
Better Auth
、HTTP请求头或Next.js相关内容。任何需要当前用户ID的用例,必须将其作为独立
Params
负载的一部分传入。
服务端动作作为适配器:
  1. 服务端动作调用
    auth.api.getSession()
  2. 提取
    session.user.id
  3. 通过
    serviceContainer.module.useCase.execute({ userId: session.user.id, ...params })
    标准化传递ID。

7. References

7. 参考资料

For practical examples, you MUST refer to:
  • Auth Reference: A complete reference showing how the the
    drizzleAdapter
    , schemas, Resend integration, and
    magicLink
    /
    emailOTP
    plugins are combined following these strict rules.
如需实用示例,必须参考:
  • 身份验证参考:完整参考文档,展示如何遵循这些严格规则组合使用
    drizzleAdapter
    、schemas、Resend集成以及
    magicLink
    /
    emailOTP
    插件。