docs/content/docs/guides/optimizing-for-performance.mdx
In this guide, we’ll go over some of the ways you can optimize your application for a more performant Better Auth app.
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.
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.
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
},
},
});
Read more about cookie caching.
Here are examples of how you can do caching in different frameworks and environments:
<Tabs items={["Next", "react-router", "SolidStart", "TanStack Query"]}>
<Tab value="Next">
Since Next v15, we can use the "use cache" directive to cache the response of a server function.
```ts
export async function getUsers() {
'use cache' // [!code highlight]
const { users } = await auth.api.listUsers();
return users
}
```
Learn more about <Link href="https://nextjs.org/docs/app/api-reference/directives/use-cache">NextJS use cache directive</Link>.
```ts
import { data } from 'react-router';
import type { Route } from './+types/your-route-name';
export const loader = async ({ request }: Route.LoaderArgs) => {
const { users } = await auth.api.listUsers();
return data(users, {
headers: {
'Cache-Control': 'max-age=3600', // Cache for 1 hour
},
});
};
export function headers({ loaderHeaders }: Route.HeadersArgs) {
return loaderHeaders;
}
```
```tsx
const getUsers = query(
async () => (await auth.api.listUsers()).users,
"getUsers"
);
```
Learn more about SolidStart <Link href="https://docs.solidjs.com/solid-router/reference/data-apis/query">`query` function</Link>.
```ts
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>
);
}
```
Learn more about <Link href="https://tanstack.com/query">TanStack Query</Link>.
On serverless platforms (Vercel, Cloudflare Workers), you can improve response times by deferring non-critical work—cleanup, analytics, rate limit updates, email sending—to run after the response is sent. Configure advanced.backgroundTasks and use ctx.context.runInBackground or ctx.context.runInBackgroundOrAwait in hooks.
import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
import { waitUntil } from "@vercel/functions";
export const auth = betterAuth({
advanced: {
backgroundTasks: { handler: waitUntil },
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
if (ctx.path === "/sign-up/email") {
ctx.context.runInBackground(logSignUp(ctx.context.newSession?.user.id));
}
}),
},
});
See the Context documentation for more examples.
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
Optimizing database performance is essential to get the best out of Better Auth.
| Table | Fields | Plugin |
|---|---|---|
| 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 |
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.
Simply import from better-auth/minimal instead of better-auth:
<Tabs items={["Prisma", "Drizzle", "MongoDB"]}> <Tab value="Prisma"> ```ts title="auth.ts" import { betterAuth } from "better-auth/minimal"; // [!code highlight] 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"
}),
});
```
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
}),
});
```
const client = new MongoClient(process.env.DATABASE_URL!);
const db = client.db();
export const auth = betterAuth({
database: mongodbAdapter(db),
});
```
better-auth if you need built-in migration support)