性能优化
在本指南中,我们将介绍一些优化应用程序的方法,以实现更高效的 Better Auth 应用。
缓存
缓存是一种强大的技术,可以通过减少数据库查询次数并加速响应时间来显著提升 Better Auth 应用程序的性能。
Cookie 缓存
每次调用 useSession 或 getSession 时都查询数据库并不是理想的选择,尤其是当会话不经常更改时。Cookie 缓存通过在短期有效的签名 Cookie 中存储会话数据来处理这种情况,这类似于使用刷新令牌的 JWT 访问令牌。
要启用 Cookie 缓存,只需在您的认证配置中设置 session.cookieCache:
import { betterAuth } from "better-auth";
export const auth = betterAuth({
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
},
});阅读更多关于 cookie caching 的内容。
框架缓存
以下是在不同框架和环境中进行缓存的示例:
自 Next v15 起,我们可以使用 "use cache" 指令来缓存服务器函数的响应。
export async function getUsers() {
'use cache'
const { users } = await auth.api.listUsers();
return users
}了解更多关于 NextJS use cache 指令的内容 此处。
在 Remix 中,您可以在 loader 函数中使用 cache 选项来缓存服务器上的响应。以下是一个示例:
import { json } from '@remix-run/node';
export const loader = async () => {
const { users } = await auth.api.listUsers();
return json(users, {
headers: {
'Cache-Control': 'max-age=3600', // Cache for 1 hour
},
});
};您可以阅读 Remix 中 Loader 与路由缓存标头的良好指南 此处。
在 SolidStart 中,您可以使用 query 函数来缓存数据。以下是一个示例:
const getUsers = query(
async () => (await auth.api.listUsers()).users,
"getUsers"
);了解更多关于 SolidStart query 函数的内容 此处。
使用 React Query,您可以使用 useQuery 钩子来缓存数据。以下是一个示例:
import { useQuery } from '@tanstack/react-query';
const fetchUsers = async () => {
const { users } = await auth.api.listUsers();
return users;
};
export default function Users() {
const { data: users, isLoading } = useQuery('users', fetchUsers, {
staleTime: 1000 * 60 * 15, // Cache for 15 minutes
});
if (isLoading) return <div>Loading...</div>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}了解更多关于 React Query use cache 指令的内容 此处。
SSR 优化
如果您使用支持服务器端渲染的框架,通常最好在服务器上预取用户会话,并在客户端将其用作回退。
const session = await auth.api.getSession({
headers: await headers(),
});
//然后将会话传递给客户端数据库优化
优化数据库性能对于充分利用 Better Auth 至关重要。
推荐索引字段
| 表 | 字段 | 插件 |
|---|---|---|
| users | email | |
| accounts | userId | |
| sessions | userId, token | |
| verifications | identifier | |
| invitations | email, organizationId | organization |
| members | userId, organizationId | organization |
| organizations | slug | organization |
| passkey | userId | passkey |
| twoFactor | secret | twoFactor |
我们计划在未来的模式生成工具中添加索引支持。