# Lynx 集成 (/docs/integrations/lynx)

将 Better Auth 集成到 Lynx 跨平台框架中。



本集成指南适用于将 Better Auth 与 [Lynx](https://lynxjs.org) 一起使用。Lynx 是一个跨平台渲染框架，使开发者能够构建针对 Android、iOS 和 Web 平台的应用程序，同时获得原生渲染性能。

开始之前，请确保您已经配置好一个 Better Auth 实例。如果还没有，请查看 [安装指南](/docs/installation)。

## 安装 [#安装]

安装 Better Auth 和 Lynx 的 React 依赖：

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install better-auth @lynx-js/react
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add better-auth @lynx-js/react
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add better-auth @lynx-js/react
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add better-auth @lynx-js/react
    ```
  </CodeBlockTab>
</CodeBlockTabs>

## 创建客户端实例 [#创建客户端实例]

从 `better-auth/lynx` 导入 `createAuthClient` 来创建客户端实例：

```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/lynx"

export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 你的认证服务器的基础 URL
})
```

## 使用方法 [#使用方法]

Lynx 客户端提供与其他 Better Auth 客户端相同的 API，同时针对 Lynx 的响应式系统进行了优化集成。

### 认证方法 [#认证方法]

```ts
import { authClient } from "./lib/auth-client"

// 使用邮箱和密码登录
await authClient.signIn.email({
    email: "test@user.com",
    password: "password1234"
})

// 注册
await authClient.signUp.email({
    email: "test@user.com", 
    password: "password1234",
    name: "John Doe"
})

// 登出
await authClient.signOut()
```

### Hooks [#hooks]

Lynx 客户端内置了与 Lynx 组件系统无缝集成的响应式 hooks：

#### useSession [#usesession]

```tsx title="components/user.tsx"
import { authClient } from "../lib/auth-client"

export function User() {
    const {
        data: session,
        isPending, // 加载状态
        error // 错误对象
    } = authClient.useSession()

    if (isPending) return <div>加载中...</div>
    if (error) return <div>错误: {error.message}</div>

    return (
        <div>
            {session ? (
                <div>
                    <p>欢迎, {session.user.name}!</p>
                    <button onClick={() => authClient.signOut()}>
                        登出
                    </button>
                </div>
            ) : (
                <button onClick={() => authClient.signIn.social({
                    provider: 'github'
                })}>
                    使用 GitHub 登录
                </button>
            )}
        </div>
    )
}
```

### 状态管理集成 [#状态管理集成]

Lynx 客户端使用 [nanostores](https://github.com/nanostores/nanostores) 进行状态管理，并提供 `useStore` hook 来访问响应式状态：

```tsx title="components/session-info.tsx"
import { useStore } from "better-auth/lynx"
import { authClient } from "../lib/auth-client"

export function SessionInfo() {
    // 直接访问 session store
    const session = useStore(authClient.$store.session)
    
    return (
        <div>
            {session && (
                <pre>{JSON.stringify(session, null, 2)}</pre>
            )}
        </div>
    )
}
```

### 高级状态管理用法 [#高级状态管理用法]

你可以结合选择性键监听来优化组件重新渲染：

```tsx title="components/optimized-user.tsx"
import { useStore } from "better-auth/lynx"
import { authClient } from "../lib/auth-client"

export function OptimizedUser() {
    // 仅在指定键发生变化时重新渲染
    const session = useStore(authClient.$store.session, {
        keys: ['user.name', 'user.email'] // 只监听这几个具体字段
    })
    
    return (
        <div>
            {session?.user && (
                <div>
                    <h2>{session.user.name}</h2>
                    <p>{session.user.email}</p>
                </div>
            )}
        </div>
    )
}
```

## 插件支持 [#插件支持]

Lynx 客户端支持所有 Better Auth 插件：

```ts title="lib/auth-client.ts"
import { createAuthClient } from "better-auth/lynx"
import { magicLinkClient } from "better-auth/client/plugins"

const authClient = createAuthClient({
    plugins: [
        magicLinkClient()
    ]
})

// 使用插件方法
await authClient.signIn.magicLink({
    email: "test@email.com"
})
```

## 错误处理 [#错误处理]

错误处理方式与其他 Better Auth 客户端相同：

```tsx title="components/login-form.tsx"
import { authClient } from "../lib/auth-client"

export function LoginForm() {
    const signIn = async (email: string, password: string) => {
        const { data, error } = await authClient.signIn.email({
            email,
            password
        })
        
        if (error) {
            console.error('登录失败:', error.message)
            return
        }
        
        console.log('登录成功:', data)
    }
    
    return (
        <form onSubmit={(e) => {
            e.preventDefault()
            const formData = new FormData(e.target)
            signIn(formData.get('email'), formData.get('password'))
        }}>
            <input name="email" type="email" placeholder="邮箱" />
            <input name="password" type="password" placeholder="密码" />
            <button type="submit">登录</button>
        </form>
    )
}
```

## 功能特性 [#功能特性]

Lynx 客户端提供：

* **跨平台支持**：适用于 Android、iOS 和 Web 平台
* **优化的性能**：专为 Lynx 的响应式系统构建
* **Nanostores 集成**：使用 nanostores 实现高效的状态管理
* **选择性重新渲染**：监听特定的 store 键，以尽量减少不必要的更新
* **完整的 API 兼容性**：所有 Better Auth 方法和插件均可无缝使用
* **TypeScript 支持**：通过 TypeScript 推断实现完整的类型安全

Lynx 集成保留了 Better Auth 的所有功能和优势，同时在 Lynx 的跨平台生态系统中提供出色的性能和开发者体验。

