性能优化
在本指南中,我们将介绍一些方法,帮助你优化应用,使 Better Auth 应用的性能更佳。
🌐 In this guide, we’ll go over some of the ways you can optimize your application for a more performant Better Auth app.
缓存
🌐 Caching
缓存是一种强大的技术,通过减少数据库查询次数和加快响应时间,可以显著提高你的 Better Auth 应用的性能。
🌐 Caching is a powerful technique that can significantly improve the performance of your Better Auth application by reducing the number of database queries and speeding up response times.
Cookies 缓存
🌐 Cookie Cache
每次调用 useSession 或 getSession 时访问数据库并不理想,尤其是当会话不经常变化时。Cookie 缓存通过将会话数据存储在短期有效的、签名的 cookie 中来处理这一问题,这类似于使用刷新令牌的 JWT 访问令牌的方式。
🌐 Calling your database every time useSession or getSession is invoked isn’t ideal, especially if sessions don’t change frequently. Cookie caching handles this by storing session data in a short-lived, signed cookie similar to how JWT access tokens are used with refresh tokens.
要启用 Cookie 缓存,只需在你的身份验证配置中设置 session.cookieCache:
🌐 To turn on cookie caching, just set session.cookieCache in your auth config:
import { betterAuth } from "better-auth";
export const auth = betterAuth({
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
},
});阅读有关 cookie 缓存 的更多内容。
🌐 Read more about cookie caching.
框架缓存
🌐 Framework Caching
以下是一些在不同框架和环境中进行缓存的示例:
🌐 Here are examples of how you can do caching in different frameworks and environments:
自 Next v15 起,我们可以使用“使用缓存”指令来缓存服务器函数的响应。
export async function getUsers() {
'use cache'
const { users } = await auth.api.listUsers();
return users
}了解有关 NextJS 使用缓存指令的更多信息 点击这里。
在 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 与 Route 缓存头的不错指南 here。
在 SolidStart 中,你可以使用 query 函数来缓存数据。下面是一个示例:
const getUsers = query(
async () => (await auth.api.listUsers()).users,
"getUsers"
);在这里了解更多关于 SolidStart query 函数的信息 here。
使用 TanStack 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>
);
}在这里了解有关 TanStack Query 的更多信息。
SSR 优化
🌐 SSR Optimizations
如果你使用支持服务器端渲染的框架,通常最好在服务器上预先获取用户会话,并在客户端将其作为备用使用。
🌐 If you're using a framework that supports server-side rendering, it's usually best to pre-fetch the user session on the server and use it as a fallback on the client.
const session = await auth.api.getSession({
headers: await headers(),
});
//then pass the session to the client数据库优化
🌐 Database optimizations
优化数据库性能对于充分发挥 Better Auth 的最佳效果至关重要。
🌐 Optimizing database performance is essential to get the best out of Better Auth.
建议建立索引的字段
🌐 Recommended fields to index
| 表格 | 字段 | 插件 |
|---|---|---|
| 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 |
我们计划在未来的模式生成工具中添加索引支持。
包大小优化
🌐 Bundle Size Optimization
如果你使用自定义适配器(如 Prisma、Drizzle 或 MongoDB),可以通过使用 better-auth/minimal 而不是 better-auth 来减少你的包大小。这个版本不包含 Kysely,Kysely 仅在使用直接数据库连接时需要。
🌐 If you're using custom adapters (like Prisma, Drizzle, or MongoDB), you can reduce your bundle size by using better-auth/minimal instead of better-auth. This version excludes Kysely, which is only needed when using direct database connections.
用法
🌐 Usage
只需从 better-auth/minimal 导入,而不是 better-auth:
🌐 Simply import from better-auth/minimal instead of better-auth:
import { betterAuth } from "better-auth/minimal";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql", // or "mysql", "sqlite"
}),
});import { betterAuth } from "better-auth/minimal";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "./database";
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
}),
});import { betterAuth } from "better-auth/minimal";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.DATABASE_URL!);
const db = client.db();
export const auth = betterAuth({
database: mongodbAdapter(db),
});限制:
- 不支持直接数据库连接(你必须使用适配器)
- 不支持内置迁移。请使用外部迁移工具(如果需要内置迁移支持,请使用
better-auth)