[GH-ISSUE #3584] PrismaClientValidationError during Account Creation with Prisma Adapter #18285

Closed
opened 2026-04-15 16:42:54 -05:00 by GiteaMirror · 2 comments
Owner

Originally created by @lu00009 on GitHub (Jul 24, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/3584

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Environment Setup:
    Node.js version: [e.g., v20.x.x or v24.x.x]
    @prisma/client version: 6.12.0
    prisma version: 6.12.0
    Database: PostgreSQL
  2. prisma/schema.prisma content:
    // This is your Prisma schema file.
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql" // or "mysql", "sqlite", etc.
  url      = env("DATABASE_URL")
}

// User model remains the same, with non-optional fields
model User {
  id                  String   @id @default(uuid())
  name                String?
  first_name          String?
  last_name           String?
  email               String   @unique
  password            String?
  role                Role?
  is_active           Boolean  @default(true)
  phone               String?  @unique
  profile_picture_url String?
  gender              Gender?
  last_login_at       DateTime?
  emailVerified       Boolean?
  createdAt           DateTime @default(now())
  updatedAt           DateTime @default(now())

  accounts            Account[]
  sessions            Session[]
}

model Registration {
  id                 Int      @id @default(autoincrement())
  email              String   @unique
  role               Role
  verification_token String   @unique
  expires_at         DateTime
  created_at         DateTime @default(now())
}

model Account {
  id                 String   @id @default(uuid())
  userId             String
  type               String?
  provider           String
  providerAccountId  String
  refresh_token      String?
  access_token       String?
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?
  session_state      String?
  user               User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(uuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

// Your Enums
enum Role {
  USER
  ADMIN
  TUTOR
}

enum Gender {
  MALE
  FEMALE
  OTHER
  PREFER_NOT_TO_SAY

}
3. // Copy the relevant parts of your betterAuth config, especially the prismaAdapter setup

import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
import { sendEmail } from "./mailer"; // your email sender utility

const prisma = new PrismaClient();

export const auth = betterAuth({
  database: prismaAdapter(prisma, { provider: "postgresql" }),
 
  emailVerification: {
    sendOnSignUp: true,
    sendVerificationEmail: async ({ user, url }, req) => {
      // ... (your enhanced logging is good to include here)
    },
  },
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
  },
});
  1. Relevant registration service code (src/api/v1/auth/auth.Service.ts):
    // Showing the call to auth.api.signUpEmail
    export const registerUser = async (userData: {
      firstName: string;
      lastName: string;
      password: string;
      gender: Gender;
      role: Role;
      email: string;
    }) => {
      // ...
      const result = await auth.api.signUpEmail({
        body: {
          name: `${userData.firstName} ${userData.lastName}`, // Required by better-auth types
          email: userData.email,
          password: userData.password,
        }
      });
      // ...
    };

```5. Steps to Trigger the Bug:
Ensure database is clean (e.g., npx prisma migrate reset --force).
Start the Node.js server.
Send a POST request to /api/v1/auth/register with valid user data (email, firstName, lastName, password, role, gender).


Additional Context:
We've ensured all fields in the Prisma Account model are explicitly marked as required (String, not String?).
A full npx prisma migrate reset has been performed to rule out database inconsistencies.
The error originates directly from within the better-auth adapter's db[model].create() call, suggesting it's not passing the type field to Prisma.
This behavior makes better-auth's Prisma integration unusable without compromising schema integrity by making required fields optional.


### Current vs. Expected behavior

Current : The better-auth Prisma adapter fails to create an Account record when the Account model in schema.prisma has a required type: String field. The adapter attempts the prisma.account.create operation without including the type property, leading to a Prisma validation error: Argument 'type' is missing.
 Expected: User is registered, and an Account record is created successfully in the database, with all required fields (including type and provider) populated correctly.

### What version of Better Auth are you using?

1.3.3

### Provide environment information

```bash
- OS (Linux)

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

No response

Originally created by @lu00009 on GitHub (Jul 24, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/3584 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Environment Setup: Node.js version: [e.g., v20.x.x or v24.x.x] @prisma/client version: 6.12.0 prisma version: 6.12.0 Database: PostgreSQL 2. prisma/schema.prisma content: // This is your Prisma schema file. ``` generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" // or "mysql", "sqlite", etc. url = env("DATABASE_URL") } // User model remains the same, with non-optional fields model User { id String @id @default(uuid()) name String? first_name String? last_name String? email String @unique password String? role Role? is_active Boolean @default(true) phone String? @unique profile_picture_url String? gender Gender? last_login_at DateTime? emailVerified Boolean? createdAt DateTime @default(now()) updatedAt DateTime @default(now()) accounts Account[] sessions Session[] } model Registration { id Int @id @default(autoincrement()) email String @unique role Role verification_token String @unique expires_at DateTime created_at DateTime @default(now()) } model Account { id String @id @default(uuid()) userId String type String? provider String providerAccountId String refresh_token String? access_token String? expires_at Int? token_type String? scope String? id_token String? session_state String? user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([provider, providerAccountId]) } model Session { id String @id @default(uuid()) sessionToken String @unique userId String expires DateTime user User @relation(fields: [userId], references: [id], onDelete: Cascade) } model VerificationToken { identifier String token String @unique expires DateTime @@unique([identifier, token]) } // Your Enums enum Role { USER ADMIN TUTOR } enum Gender { MALE FEMALE OTHER PREFER_NOT_TO_SAY ``` } 3. // Copy the relevant parts of your betterAuth config, especially the prismaAdapter setup ``` ``` import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { PrismaClient } from "@prisma/client"; import { sendEmail } from "./mailer"; // your email sender utility const prisma = new PrismaClient(); export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql" }), emailVerification: { sendOnSignUp: true, sendVerificationEmail: async ({ user, url }, req) => { // ... (your enhanced logging is good to include here) }, }, emailAndPassword: { enabled: true, requireEmailVerification: true, }, }); ``` ``` 4. Relevant registration service code (src/api/v1/auth/auth.Service.ts): // Showing the call to auth.api.signUpEmail ``` export const registerUser = async (userData: { firstName: string; lastName: string; password: string; gender: Gender; role: Role; email: string; }) => { // ... const result = await auth.api.signUpEmail({ body: { name: `${userData.firstName} ${userData.lastName}`, // Required by better-auth types email: userData.email, password: userData.password, } }); // ... }; ```5. Steps to Trigger the Bug: Ensure database is clean (e.g., npx prisma migrate reset --force). Start the Node.js server. Send a POST request to /api/v1/auth/register with valid user data (email, firstName, lastName, password, role, gender). Additional Context: We've ensured all fields in the Prisma Account model are explicitly marked as required (String, not String?). A full npx prisma migrate reset has been performed to rule out database inconsistencies. The error originates directly from within the better-auth adapter's db[model].create() call, suggesting it's not passing the type field to Prisma. This behavior makes better-auth's Prisma integration unusable without compromising schema integrity by making required fields optional. ### Current vs. Expected behavior Current : The better-auth Prisma adapter fails to create an Account record when the Account model in schema.prisma has a required type: String field. The adapter attempts the prisma.account.create operation without including the type property, leading to a Prisma validation error: Argument 'type' is missing. Expected: User is registered, and an Account record is created successfully in the database, with all required fields (including type and provider) populated correctly. ### What version of Better Auth are you using? 1.3.3 ### Provide environment information ```bash - OS (Linux) ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context _No response_
GiteaMirror added the locked label 2026-04-15 16:42:54 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Jul 24, 2025):

Hi @lu00009! I'm Dosu and I’m helping the better-auth team.

This is a known issue with better-auth's Prisma adapter: if your Account model has required fields like type (or name), the adapter may not supply them during account creation, leading to PrismaClientValidationError. The maintainers have acknowledged that the adapter and schema can get out of sync, especially if you enforce stricter requirements than the default schema. The recommended workarounds are to either make such fields optional in your schema or auto-fill them with a placeholder/default value if not collected from users. This mismatch has been addressed in upcoming releases, so upgrading to the latest beta may resolve it for you. See the relevant discussion and maintainer guidance here.

If you need an immediate fix and don't want to relax your schema, you can patch your local Prisma adapter to ensure all required fields are supplied during account creation. Customizing the adapter or using database hooks to fill in missing fields is possible, but requires manual changes and careful alignment between your schema and what the adapter provides. More details on schema customization and hooks are discussed here.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3112949912 --> @dosubot[bot] commented on GitHub (Jul 24, 2025): <!-- Greeting --> Hi @lu00009! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This is a known issue with better-auth's Prisma adapter: if your Account model has required fields like type (or name), the adapter may not supply them during account creation, leading to PrismaClientValidationError. The maintainers have acknowledged that the adapter and schema can get out of sync, especially if you enforce stricter requirements than the default schema. The recommended workarounds are to either make such fields optional in your schema or auto-fill them with a placeholder/default value if not collected from users. This mismatch has been addressed in upcoming releases, so upgrading to the latest beta may resolve it for you. See the relevant discussion and maintainer guidance [here](https://github.com/better-auth/better-auth/issues/3394). If you need an immediate fix and don't want to relax your schema, you can patch your local Prisma adapter to ensure all required fields are supplied during account creation. Customizing the adapter or using database hooks to fill in missing fields is possible, but requires manual changes and careful alignment between your schema and what the adapter provides. More details on schema customization and hooks are discussed [here](https://github.com/better-auth/better-auth/discussions/3249). <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/281634c9-e0e7-4076-85dc-c078e36cecc1?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/3584)
Author
Owner

@coollad49 commented on GitHub (Aug 23, 2025):

Hello, the issue is because of the enum type defined for role in the User model, i too have been searching for a way to use the enum type with better auth.

Image
<!-- gh-comment-id:3216582465 --> @coollad49 commented on GitHub (Aug 23, 2025): Hello, the issue is because of the enum type defined for role in the User model, i too have been searching for a way to use the enum type with better auth. <img width="613" height="372" alt="Image" src="https://github.com/user-attachments/assets/eeb20806-0044-47a0-b15e-67d725e4970a" />
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18285