---
title: "Better Auth 集成"
description: "在经过身份验证的请求中识别用户，这样每个 wide 事件都会携带发起者信息，无需手动调用 log.set。"
canonical_url: "https://evlog.zhcndoc.com/use-cases/better-auth/overview"
---
# Better Auth 集成

> 在经过身份验证的请求中识别用户，这样每个 wide 事件都会携带发起者信息，无需手动调用 log.set。

`evlog/better-auth` 会将匿名 wide 事件转换为已识别事件。每个请求都会自动包含发起者信息，无需手动调用 `log.set({ user })`。

## 接入前

在你的应用中将 [Better Auth](https://better-auth.com/) 作为**直接依赖**使用。`evlog` 不会捆绑 Better Auth。该集成已针对 Better Auth `>=1.6.9` 进行测试（与[ playground](https://github.com/evloghq/evlog/tree/main/apps/playground)使用相同的主版本）。

<code-group>

```bash [pnpm]
pnpm add better-auth
```

```bash [bun]
bun add better-auth
```

```bash [yarn]
yarn add better-auth
```

```bash [npm]
npm install better-auth
```

</code-group>

<prompt :actions="["copy","cursor","claude"]" description="添加 Better Auth 用户识别" icon="i-simple-icons-betterauth">

使用 evlog 为我的应用添加 Better Auth 用户识别。

- 从 'evlog/better-auth' 导入 createAuthMiddleware
- 调用 createAuthMiddleware(auth) 获取 identify 函数
- 在中间件／hook 中调用 identify(log, headers, path)，以便在每个请求中自动识别用户
- 默认安全。仅提取列入白名单的字段，并且绝不会记录密码或令牌
- 支持 include／exclude 路由模式、生命周期 hook 和 Better Auth 插件字段
- 适用于所有框架：Nuxt、Next.js、Express、Hono、Fastify、NestJS、Elysia，以及独立应用

文档：[https://www.evlog.dev/use-cases/better-auth/overview](https://www.evlog.dev/use-cases/better-auth/overview)
适配器：[https://www.evlog.dev/integrate/adapters/overview](https://www.evlog.dev/integrate/adapters/overview)

</prompt>

## 快速开始

一个中间件，所有请求都会被识别：

<framework-tabs>

```typescript [Nuxt]server/middleware/auth-identify.ts
import { createAuthMiddleware } from 'evlog/better-auth'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

export default defineEventHandler(async (event) => {
  if (!event.context.log) return
  await identify(event.context.log, event.headers, event.path)
})
```

```typescript [Next.js]app/api/checkout/route.ts
import { withEvlog, useLogger } from '@/lib/evlog'
import { createAuthMiddleware } from 'evlog/better-auth'
import { auth } from '@/lib/auth'

const identify = createAuthMiddleware(auth)

export const POST = withEvlog(async (request: Request) => {
  const log = useLogger()
  await identify(log, request.headers)
  log.set({ action: 'checkout' })
  return Response.json({ success: true })
})
```

```typescript [Express]src/index.ts
import { createAuthMiddleware } from 'evlog/better-auth'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

app.use(async (req, res, next) => {
  await identify(req.log, req.headers, req.path)
  next()
})
```

```typescript [Hono]src/index.ts
import { createAuthMiddleware } from 'evlog/better-auth'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

app.use(async (c, next) => {
  await identify(c.get('log'), c.req.raw.headers, c.req.path)
  await next()
})
```

```typescript [Fastify]src/index.ts
import { createAuthMiddleware } from 'evlog/better-auth'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

app.addHook('onRequest', async (request) => {
  await identify(request.log, request.headers, request.url)
})
```

```typescript [Elysia]src/index.ts
import { createAuthMiddleware } from 'evlog/better-auth'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

app.derive(async ({ log, request }) => {
  await identify(log, request.headers, new URL(request.url).pathname)
  return {}
})
```

```typescript [NestJS]src/auth-identify.middleware.ts
import { createAuthMiddleware } from 'evlog/better-auth'
import { useLogger } from 'evlog/nestjs'

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**'],
})

@Injectable()
export class AuthIdentifyMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    await identify(useLogger(), req.headers, req.path)
    next()
  }
}
```

```typescript [Standalone]scripts/sync-job.ts
import { identifyUser } from 'evlog/better-auth'
import { createLogger } from 'evlog'

const log = createLogger()
const session = await auth.api.getSession({ headers })
if (session) identifyUser(log, session)
log.emit()
```

</framework-tabs>

现在你的 wide 事件包含了用户信息：

<code-group>

```json [之前 — 匿名]
{
  "level": "info",
  "method": "POST",
  "path": "/api/checkout",
  "status": 200,
  "duration": "120ms",
  "requestId": "a5669202-7765-4f59-b6f0-b9f40ce71599",
  "cart": { "items": 3, "total": 9999 }
}
```

```json [之后 — 已识别]
{
  "level": "info",
  "method": "POST",
  "path": "/api/checkout",
  "status": 200,
  "duration": "120ms",
  "requestId": "a5669202-7765-4f59-b6f0-b9f40ce71599",
  "userId": "QBX9tPjJQExWawAbNll75",
  "user": {
    "id": "QBX9tPjJQExWawAbNll75",
    "name": "Hugo Richard",
    "email": "hugo@example.com",
    "emailVerified": true,
    "createdAt": "2024-01-15T10:00:00.000Z"
  },
  "session": {
    "id": "Xhmh6TxKJQrVKFX0Y0II",
    "expiresAt": "2024-01-22T10:00:00.000Z",
    "ipAddress": "192.168.1.42",
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
    "createdAt": "2024-01-15T10:00:00.000Z"
  },
  "auth": {
    "resolvedIn": 12,
    "identified": true
  },
  "cart": { "items": 3, "total": 9999 }
}
```

</code-group>

## 会话如何到达事件

<better-auth-identify>



</better-auth-identify>

该集成会从请求 cookie 中解析 Better Auth 会话，提取安全白名单中的用户和会话字段，将它们设置到 logger 上，然后触发 `onIdentify`（或 `onAnonymous`）hook。默认会跳过认证路由。解析耗时会记录在 `auth.resolvedIn` 中，因此你可以将认证延迟与 wide 事件的其他部分一起绘制成图表。

## 接下来去哪

<card-group>
<card icon="i-lucide-user-check" title="识别用户" to="https://evlog.zhcndoc.com/use-cases/better-auth/identify-user">

核心构建模块：提取安全字段、隐藏邮箱，并捕获插件数据（组织、角色、2FA）。

</card>

<card icon="i-lucide-shield" title="中间件" to="https://evlog.zhcndoc.com/use-cases/better-auth/middleware">

使用 `include`／`exclude` 过滤路由，通过生命周期 hook 响应识别，并按应用调优行为。

</card>

<card icon="i-lucide-monitor" title="客户端同步" to="https://evlog.zhcndoc.com/use-cases/better-auth/client-sync">

使用 `setIdentity` 和 Better Auth 客户端将用户身份同步到客户端日志中。

</card>

<card icon="i-lucide-gauge" title="性能" to="https://evlog.zhcndoc.com/use-cases/better-auth/performance">

监控会话解析时间，启用会话缓存，并与 AI SDK 集成结合使用。

</card>
</card-group>

## 包导出的内容

<table>
<thead>
  <tr>
    <th>
      导出
    </th>
    
    <th>
      描述
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        identifyUser(log, session)
      </code>
    </td>
    
    <td>
      核心辅助函数——从会话中提取安全字段并将其设置到 logger 上。如果已识别则返回 <code>
        true
      </code>
      
      。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        createAuthMiddleware(auth)
      </code>
    </td>
    
    <td>
      返回一个异步的 <code>
        (log, headers, path?) => Promise<boolean>
      </code>
      
       函数，支持路由过滤、计时和 hooks。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        createAuthIdentifier(auth)
      </code>
    </td>
    
    <td>
      用于独立 Nitro 应用的 Nitro <code>
        request
      </code>
      
       hook 工厂。参见 <a href="https://evlog.zhcndoc.com/use-cases/better-auth/performance#standalone-nitro">
        性能
      </a>
      
      。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        maskEmail(email)
      </code>
    </td>
    
    <td>
      隐藏邮箱：<code>
        hugo@example.com
      </code>
      
       → <code>
        h***@example.com
      </code>
      
      。
    </td>
  </tr>
</tbody>
</table>

---

- [识别用户](https://evlog.zhcndoc.com/use-cases/better-auth/identify-user)
- [中间件](https://evlog.zhcndoc.com/use-cases/better-auth/middleware)
- [客户端同步](https://evlog.zhcndoc.com/use-cases/better-auth/client-sync)
- [性能](https://evlog.zhcndoc.com/use-cases/better-auth/performance)


## Sitemap

See the full [sitemap](https://evlog.zhcndoc.com/sitemap.md) for all pages.
