性能优化

在本文中,我们将介绍一些可以优化应用程序以获得更高性能 Better Auth 应用的方法。

缓存

缓存是一种强大的技术,通过减少数据库查询次数和加快响应时间,可以显著提高 Better Auth 应用程序的性能。

每次调用 useSessiongetSession 时都查询数据库并不理想,尤其是当会话不经常变化时。Cookie 缓存通过将会话数据存储在短期的签名 cookie 中来解决这个问题——类似于如何将 JWT 访问令牌与刷新令牌一起使用。

要开启 cookie 缓存,只需在你的认证配置中设置 session.cookieCache

auth.ts
const auth = new betterAuth({
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60, // 缓存持续时间(秒)
    },
  },
});

了解更多关于 cookie 缓存 的信息。

框架缓存

以下是在不同框架和环境中实现缓存的示例:

SSR 优化

如果你使用支持服务器端渲染的框架,通常最好在服务器上预先获取用户会话,并在客户端使用它作为备选方案。

const session = await auth.api.getSession({
  headers: await headers(),
});
// 然后将会话传递给客户端

数据库优化

优化数据库性能对于充分利用 Better Auth 至关重要。

推荐建立索引的字段

字段插件
usersemail
accountsuserId
sessionsuserId, token
verificationsidentifier
invitationsemail, organizationIdorganization
membersuserId, organizationIdorganization
organizationsslugorganization
passkeyuserIdpasskey
twoFactorsecrettwoFactor

我们计划在未来的模式生成工具中添加索引支持。

On this page