---
title: "createAuthMiddleware"
description: "一个与框架无关的工厂，具备路由过滤、会话计时和生命周期钩子。启动时调用一次，然后在各个请求之间复用。"
canonical_url: "https://evlog.zhcndoc.com/use-cases/better-auth/middleware"
---
# createAuthMiddleware

> 一个与框架无关的工厂，具备路由过滤、会话计时和生命周期钩子。启动时调用一次，然后在各个请求之间复用。

`createAuthMiddleware` 用你在每个请求中都需要的内容包装了 `identifyUser`：路由过滤、会话解析耗时、生命周期钩子，以及静默错误处理。启动时调用一次，然后在你框架的 middleware/hook 系统中使用返回的函数。

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

const identify = createAuthMiddleware(auth, {
  exclude: ['/api/auth/**', '/api/public/**'],
  include: ['/api/**'],
  maskEmail: true,
})
```

函数签名为 `(log, headers, path?) => Promise<boolean>`。它会解析会话、调用 `identifyUser`、将耗时记录到 `auth.resolvedIn`、触发生命周期钩子，并且会静默捕获错误，因此会话解析永远不会中断请求。

## 选项

继承所有 [`identifyUser` 选项](https://evlog.zhcndoc.com/use-cases/better-auth/identify-user#options)，另外还有：

<table>
<thead>
  <tr>
    <th>
      选项
    </th>
    
    <th>
      类型
    </th>
    
    <th>
      默认值
    </th>
    
    <th>
      描述
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        exclude
      </code>
    </td>
    
    <td>
      <code>
        string[]
      </code>
    </td>
    
    <td>
      <code>
        ['/api/auth/**']
      </code>
    </td>
    
    <td>
      要跳过的路由模式（glob）。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        include
      </code>
    </td>
    
    <td>
      <code>
        string[]
      </code>
    </td>
    
    <td>
      <code>
        undefined
      </code>
    </td>
    
    <td>
      如果设置，则只会解析匹配的路由。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onIdentify
      </code>
    </td>
    
    <td>
      <code>
        (log, session) => void
      </code>
    </td>
    
    <td>
      <code>
        undefined
      </code>
    </td>
    
    <td>
      成功识别后调用。
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onAnonymous
      </code>
    </td>
    
    <td>
      <code>
        (log) => void
      </code>
    </td>
    
    <td>
      <code>
        undefined
      </code>
    </td>
    
    <td>
      未找到会话时调用。
    </td>
  </tr>
</tbody>
</table>

## 跳过不需要会话的路由

跳过 Better Auth 自身的路由和任何公开端点，以避免无谓的数据库查询：

```typescript
const identify = createAuthMiddleware(auth, {
  exclude: [
    '/api/auth/**',     // Better Auth 自身
    '/api/public/**',   // 公共端点
    '/api/health',      // 健康检查
  ],
})
```

对于高流量应用，可以反过来，只在需要会话的路由上解析会话：

```typescript
const identify = createAuthMiddleware(auth, {
  include: ['/api/dashboard/**', '/api/account/**'],
})
```

`include` 和 `exclude` 使用 glob 模式（`*`、`**`）。如果需要精细控制，可以同时提供两者，并且 `exclude` 的优先级高于 `include`。

## 对识别结果做出响应

使用 `onIdentify` 对用户识别做出响应，例如通过尾部采样为高级用户强制保留日志：

```typescript [server/middleware/auth-identify.ts]
const identify = createAuthMiddleware(auth, {
  onIdentify: (log, session) => {
    if (session.user.plan === 'enterprise') {
      log.set({ _forceKeep: true })
    }
  },
  onAnonymous: (log) => {
    log.set({ anonymous: true })
  },
})
```

钩子会在会话解析完成且 `identifyUser` 已设置其字段后触发。它们会在每个通过 `include`/`exclude` 过滤器的请求上运行，因此请保持它们足够快且无副作用。

<tip>

`onIdentify` 的常见模式：

- 为管理员或高价值套餐强制保留审计日志。
- 用从会话中加载的功能标志或租户信息为请求打标签。
- 为计费目的按用户递增计数器。

</tip>

## 认证失败时会发生什么

中间件会捕获 `getSession` 抛出的所有错误且不记录任何日志，因此无论认证后端是否正常运行，请求都会继续执行。宽事件仍会包含 `auth.resolvedIn` 和 `auth.identified: false`，因此你可以从控制面板监控会话解析的健康状况并设置告警。

---

- [识别用户](https://evlog.zhcndoc.com/use-cases/better-auth/identify-user)
- [性能](https://evlog.zhcndoc.com/use-cases/better-auth/performance)


## Sitemap

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