Adding simple role to User Schema

hi guys! im having a little issue with adding a role to my User schema. I'm using Prisma and i wanted to add a role property to the User schema. It all works well, until i need to use the authClient.useSession() hook. I get the session off of it, but when trying to access the session.user.role property, it says there is no role property on it.

What i've already tried:

  • Adding aditionalFields property to the better auth instance```tsuser: { additionalFields: { role: { type: "string", } }}```
  • Adding the inferAdditionalFields plugins, both ways suggested in here: https://www.better-auth.com/docs/concepts/typescript#inferring-additional-fields-on-client
  • Regenerated my Prisma client
I didnt want to include that whole admin plugin for roles since i dont think theres need for it in my simple app. I believe just an "Admin", "Customer" or "Support" role column on the User schema will do.

But if theres no better way to do it, i'll try that option.
image.png
Better Auth TypeScript integration.
Solution
alright, i'll summarize the fix in here for anybody who happens to have the same issue in the future:

To add a custom field to your User schema:

  1. In your auth.ts file, add the user.additionalFields property: (dont mind the prismaAdapter or socialProviders, these are specific to my project)
import { PrismaClient } from "@/generated/prisma";
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
// If your Prisma file is located elsewhere, you can change the path"

const prisma = new PrismaClient();
export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: "postgresql",
  }),
  socialProviders: {
    cognito: {
      clientId: process.env.COGNITO_CLIENT_ID!,
      clientSecret: process.env.COGNITO_CLIENT_SECRET!,
      domain: process.env.COGNITO_DOMAIN!,
      region: process.env.COGNITO_REGION!,
      userPoolId: process.env.COGNITO_USER_POOL_ID!,
    },
  },
  user: {
    additionalFields: {
      role: {
        type: "string",
      },
    },
  },
});


  1. in your auth-client.ts file, add the inferAdditionalFields plugins:
import { createAuthClient } from "better-auth/react";
import { inferAdditionalFields } from "better-auth/client/plugins";
import type { auth } from "./auth";
export const authClient = createAuthClient({
  /** The base URL of the server (optional if you're using the same domain) */
  baseURL: "http://localhost:3000",
  plugins: [inferAdditionalFields<typeof auth>()],
});


  1. From there, any additional property you add to the User schema, you'll need to include it on the user.additionalFields property from step 1 and they should get automatically picked up when you fetch the user.
Was this page helpful?