Docs

Typescript

Better Auth is designed to be type-safe. Both the client and server are built with TypeScript, allowing you to easily infer types.

Infering Types

Both the client SDK and the server offer types that can be inferred using the $Infer property. Plugins can extend base types like User and Session, and you can use $Infer to infer these types. Additionally, plugins can provide extra types that can also be inferred through $Infer.

client.ts
import {  } from "better-auth/client"
 
const  = ()
 
export type  = typeof ..

The Session type includes both session and user properties. The user property represents the user object type, and the session property represents the session object type.

You can also infer types on the server side.

auth.ts
import {  } from "better-auth"
import  from "better-sqlite3"
 
export const  = ({
    : new ("database.db")
})
 
type  = typeof ..

Additional Fields

Better Auth allows you to add additional fields to the user and session objects. All additional fields are properly inferred and available on the server and client side.

import {  } from "better-auth"
import  from "better-sqlite3"
 
export const  = ({
    : new ("database.db"),
    : {
       : {
          : {
              : "string"
            } 
        }
    }
   
})
 
type  = typeof ..

In the example above, we added a role field to the user object. This field is now available on the Session type.

Inferring Additional Fields on Client

To make sure proper type inference for additional fields on the client side, you need to inform the client about these fields. There are two approaches to achieve this, depending on your project structure:

  1. For Monorepo or Single-Project Setups

If your server and client code reside in the same project, you can use the inferAdditionalFields plugin to automatically infer the additional fields from your server configuration.

import { inferAdditionalFields } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
import type { auth } from "./auth";
 
export const authClient = createAuthClient({
  plugins: [inferAdditionalFields<typeof auth>()],
});
  1. For Separate Client-Server Projects

If your client and server are in separate projects, you'll need to manually specify the additional fields when creating the auth client.

import type { auth } from "./auth";
import { inferAdditionalFields } from "better-auth/client/plugins";
 
export const authClient = createAuthClient({
  plugins: [inferAdditionalFields({
      user: {
        role: {
          type: "string"
        }
      }
  })],
});

On this page

Edit on GitHub