[GH-ISSUE #6260] Error: Malformed ObjectID generated by Better Auth during user creation #10463

Closed
opened 2026-04-13 06:37:53 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @abdirahmanmahamoud on GitHub (Nov 24, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6260

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

To Reproduce

  1. Initialize a new Prisma project using the MongoDB provider:

    datasource db {
      provider = "mongodb"
      url      = env("DATABASE_URL")
    }
    
  2. Use the default Better Auth Prisma schema (MongoDB version), for example:

    model User {
      id            String    @id @default(auto()) @map("_id") @db.ObjectId
      name          String
      email         String
      emailVerified Boolean   @default(false)
      image         String?
      createdAt     DateTime  @default(now())
      updatedAt     DateTime  @updatedAt
      sessions      Session[]
      accounts      Account[]
    
      @@unique([email])
      @@map("users")
    }
    
  3. Generate the Prisma Client:

    npx prisma generate
    
  4. Initialize Better Auth with the Prisma adapter:

    import { betterAuth } from "better-auth";
    import { prismaAdapter } from "better-auth/adapters/prisma";
    import { PrismaClient } from "@/generated/prisma/client";
    
    const prisma = new PrismaClient();
    
    export const auth = betterAuth({
      database: prismaAdapter(prisma, {
        provider: "sqlite",   // (Problem: Not matching MongoDB)
      }),
      emailAndPassword: {
        enabled: true,
      },
    });
    
  5. Attempt to create a user via email/password sign-up:

    await auth.api.signUp("email", {
      email: "test@example.com",
      password: "123456",
    });
    
  6. The following error appears:

    PrismaClientKnownRequestError (P2023)
    Invalid ObjectId
    Malformed ObjectID: invalid character 'j'
    

Current vs. Expected behavior

Current Behavior

My Prisma schema uses MongoDB (provider = "mongodb").

However, when using prismaAdapter(prisma, { provider: "sqlite" }), Better Auth tries to operate as if the database is SQLite, which causes a conflict.

As a result, authentication does not work correctly — sessions, accounts, and verifications cannot be created or fail unexpectedly.

Some operations behave as if migrations or tables follow SQLite structure, which does not match the MongoDB models defined in the Prisma schema.

Expected Behavior

Better Auth should correctly detect and work with MongoDB as defined in the Prisma datasource.

The Prisma adapter should support the existing MongoDB models (User, Session, Account, Verification).

Authentication flows like sign-up, login, session creation, and verification should work properly without conflicts.

The provider option in the adapter should match or automatically infer the database provider from the Prisma schema (MongoDB).

What version of Better Auth are you using?

I am using Better Auth version: 1.4.1.

System info

Better Auth version: 1.4.1

Prisma version: 6.19.0

Database provider: mongodb

Runtime: Node v22.18.0

Package manager: npm 

Framework: Next.js v16.0.3

Operating System: Windows 11

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@/generated/prisma/client";
import { nextCookies } from "better-auth/next-js";

const prisma = new PrismaClient();
export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: "sqlite",
  }),
  emailAndPassword: {
    enabled: true,
  },
  plugins: [nextCookies()],
});

Additional context

No response

Originally created by @abdirahmanmahamoud on GitHub (Nov 24, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6260 ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce ### **To Reproduce** 1. Initialize a new Prisma project using the **MongoDB provider**: ```prisma datasource db { provider = "mongodb" url = env("DATABASE_URL") } ``` 2. Use the default Better Auth Prisma schema (MongoDB version), for example: ```prisma model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String email String emailVerified Boolean @default(false) image String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt sessions Session[] accounts Account[] @@unique([email]) @@map("users") } ``` 3. Generate the Prisma Client: ```bash npx prisma generate ``` 4. Initialize Better Auth with the Prisma adapter: ```ts import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { PrismaClient } from "@/generated/prisma/client"; const prisma = new PrismaClient(); export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "sqlite", // (Problem: Not matching MongoDB) }), emailAndPassword: { enabled: true, }, }); ``` 5. Attempt to create a user via email/password sign-up: ```ts await auth.api.signUp("email", { email: "test@example.com", password: "123456", }); ``` 6. The following error appears: ``` PrismaClientKnownRequestError (P2023) Invalid ObjectId Malformed ObjectID: invalid character 'j' ``` ### Current vs. Expected behavior Current Behavior My Prisma schema uses MongoDB (provider = "mongodb"). However, when using prismaAdapter(prisma, { provider: "sqlite" }), Better Auth tries to operate as if the database is SQLite, which causes a conflict. As a result, authentication does not work correctly — sessions, accounts, and verifications cannot be created or fail unexpectedly. Some operations behave as if migrations or tables follow SQLite structure, which does not match the MongoDB models defined in the Prisma schema. Expected Behavior Better Auth should correctly detect and work with MongoDB as defined in the Prisma datasource. The Prisma adapter should support the existing MongoDB models (User, Session, Account, Verification). Authentication flows like sign-up, login, session creation, and verification should work properly without conflicts. The provider option in the adapter should match or automatically infer the database provider from the Prisma schema (MongoDB). ### What version of Better Auth are you using? I am using Better Auth version: 1.4.1. ### System info ```bash Better Auth version: 1.4.1 Prisma version: 6.19.0 Database provider: mongodb Runtime: Node v22.18.0 Package manager: npm Framework: Next.js v16.0.3 Operating System: Windows 11 ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { PrismaClient } from "@/generated/prisma/client"; import { nextCookies } from "better-auth/next-js"; const prisma = new PrismaClient(); export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "sqlite", }), emailAndPassword: { enabled: true, }, plugins: [nextCookies()], }); ``` ### Additional context _No response_
GiteaMirror added the lockedbug labels 2026-04-13 06:37:53 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Nov 24, 2025):

It appears the error is due to a mismatch between your Prisma schema (using MongoDB) and the adapter configuration, which is set to "sqlite." To resolve this, update your Prisma adapter configuration to use "mongodb" as the provider so that Better Auth correctly handles MongoDB’s ObjectIDs. For example:

  import { betterAuth } from "better-auth";
  import { prismaAdapter } from "better-auth/adapters/prisma";
  import { PrismaClient } from "@/generated/prisma/client";

  const prisma = new PrismaClient();
  export const auth = betterAuth({
   database: prismaAdapter(prisma, {
    provider: "mongodb", // updated from "sqlite"
   }),
   emailAndPassword: {
    enabled: true,
   },
   plugins: [nextCookies()],
  });

This change should ensure that the adapter uses the correct schema for MongoDB, preventing malformed ObjectIDs [1]. Does this help address your issue, or do you have any additional questions? Tag @better-auth-agent if you would like an answer from the Agent.

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3569840853 --> @better-auth-agent[bot] commented on GitHub (Nov 24, 2025): It appears the error is due to a mismatch between your Prisma schema (using MongoDB) and the adapter configuration, which is set to "sqlite." To resolve this, update your Prisma adapter configuration to use "mongodb" as the provider so that Better Auth correctly handles MongoDB’s ObjectIDs. For example:   import { betterAuth } from "better-auth";   import { prismaAdapter } from "better-auth/adapters/prisma";   import { PrismaClient } from "@/generated/prisma/client";   const prisma = new PrismaClient();   export const auth = betterAuth({    database: prismaAdapter(prisma, {     provider: "mongodb", // updated from "sqlite"    }),    emailAndPassword: {     enabled: true,    },    plugins: [nextCookies()],   }); This change should ensure that the adapter uses the correct schema for MongoDB, preventing malformed ObjectIDs [[1]](https://github.com/better-auth/better-auth/issues/4125). Does this help address your issue, or do you have any additional questions? Tag @better-auth-agent if you would like an answer from the Agent. <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@dosubot[bot] commented on GitHub (Feb 23, 2026):

Hi, @abdirahmanmahamoud. I'm Dosu, and I'm helping the better-auth team manage their backlog and am marking this issue as stale.

Issue Summary:

  • You reported errors with Better Auth when using the Prisma MongoDB provider but configuring the prismaAdapter with provider set to "sqlite."
  • The errors were due to malformed ObjectID issues caused by this provider mismatch.
  • I identified the root cause as the adapter configuration not matching the Prisma schema provider.
  • Updating the prismaAdapter provider to "mongodb" resolved the authentication failures.
  • I offer further assistance if needed.

Next Steps:

  • Please confirm if this issue is still relevant with the latest version of better-auth by commenting here.
  • If no response is received within 7 days, I will automatically close this issue.

Thank you for your understanding and contribution!

<!-- gh-comment-id:3945745762 --> @dosubot[bot] commented on GitHub (Feb 23, 2026): Hi, @abdirahmanmahamoud. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary:** - You reported errors with Better Auth when using the Prisma MongoDB provider but configuring the prismaAdapter with provider set to "sqlite." - The errors were due to malformed ObjectID issues caused by this provider mismatch. - I identified the root cause as the adapter configuration not matching the Prisma schema provider. - Updating the prismaAdapter provider to "mongodb" resolved the authentication failures. - I offer further assistance if needed. **Next Steps:** - Please confirm if this issue is still relevant with the latest version of better-auth by commenting here. - If no response is received within 7 days, I will automatically close this issue. Thank you for your understanding and contribution!
Author
Owner

@dosubot[bot] commented on GitHub (Feb 23, 2026):

Thank you for your contribution, abdirahmanmahamoud! We appreciate your help in keeping the issues up to date.

<!-- gh-comment-id:3945844466 --> @dosubot[bot] commented on GitHub (Feb 23, 2026): Thank you for your contribution, abdirahmanmahamoud! We appreciate your help in keeping the issues up to date.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#10463