Optimizing for Performance

In this guide, we’ll go over some of the ways you can optimize your application for a more performant Better Auth app.

Caching

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 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:

auth.ts
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.

Framework Caching

Here are examples of how you can do caching in different frameworks and environments:

SSR Optimizations

If you're using a framework that supports server-side rendering, it's usually best to pre-fetch 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

Optimizing database performance is essential to get the best out of Better Auth.

TableFieldsPlugin
usersemail
accountsuserId
sessionsuserId, token
verificationsidentifier
invitationsemail, organizationIdorganization
membersuserId, organizationIdorganization
organizationsslugorganization
passkeyuserIdpasskey
twoFactorsecrettwoFactor

We intend to add indexing support in our schema generation tool in the future.

On this page