[GH-ISSUE #5756] Error using prismaAdapter with mongodb schema in next.js 16 #18972

Closed
opened 2026-04-15 17:42:51 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @RobinWitzschke on GitHub (Nov 4, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5756

Hey everyone,

I ran into an issue using better-auth in next.js with the prismaAdapter using a mongodb prisma.schema

so im using this prisma.schema file

`generator client {
provider = "prisma-client"
output = "../src/generated/prisma/user"
}

datasource db {
provider = "mongodb"
url = env("DATABASE_URL_USER")
}

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
externalId String @unique @default(uuid()) // externe ID
name String
email String @unique
emailVerified Boolean @default(false)
image String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isAnonymous Boolean? @default(false)

sessions Session[]
accounts Account[]
}

model Session {
id String @id @default(auto()) @map("_id") @db.ObjectId
externalId String @unique @default(uuid()) // externe ID
userId String
token String @unique
expiresAt DateTime
ipAddress String?
userAgent String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

user User @relation(fields: [userId], references: [externalId])
}

model Account {
id String @id @default(auto()) @map("_id") @db.ObjectId
externalId String @unique @default(uuid()) // externe ID
userId String
accountId String
providerId String
accessToken String?
refreshToken String?
accessTokenExpiresAt DateTime?
refreshTokenExpiresAt DateTime?
scope String?
idToken String?
password String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

user User @relation(fields: [userId], references: [externalId])
}

model Verification {
id String @id @default(auto()) @map("_id") @db.ObjectId
externalId String @unique @default(uuid()) // externe ID
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}`

and mapped the fields in the auth.ts file

`import { betterAuth } from "better-auth";
import { anonymous } from "better-auth/plugins";
import { prismaAdapter } from "better-auth/adapters/prisma";
// If your Prisma file is located elsewhere, you can change the path
import { PrismaClient as UserPrismaClient } from "@/generated/prisma/user/client";

const prisma = new UserPrismaClient();

export const auth = betterAuth({
user: {
modelName: "User",
fields: {
id: "externalId",
name: "name",
email: "email",
emailVerified: "emailVerified",
image: "image",
createdAt: "createdAt",
updatedAt: "updatedAt",
isAnonymous: "isAnonymous",
sessions: "sessions",
accounts: "accounts",
},
},
session: {
expiresIn: 1 * 24 * 60 * 60, // 1 day in seconds
modelName: "Session",
fields: {
userId: "userId",
token: "token",
expiresAt: "expiresAt",
ipAddress: "ipAddress",
userAgent: "userAgent",
createdAt: "createdAt",
updatedAt: "updatedAt",
},
},
account: {
modelName: "Account",
fields: {
userId: "userId",
accountId: "accountId",
providerId: "providerId",
accessToken: "accessToken",
refreshToken: "refreshToken",
accessTokenExpiresAt: "accessTokenExpiresAt",
refreshTokenExpiresAt: "refreshTokenExpiresAt",
scope: "scope",
idToken: "idToken",
password: "password",
createdAt: "createdAt",
updatedAt: "updatedAt",
},
},
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
advanced: {
cookiePrefix: "myapp",
useSecureCookies: true,
cookies: {
sesssion_token: {
name: "custom_session_token",
},
},
},
socialProviders: {
microsoft: {
clientId: process.env.MICROSOFT_CLIENT_ID as string,
clientSecret: process.env.MICROSOFT_CLIENT_SECRET as string,
// Optional
tenantId: "common",
authority: "https://login.microsoftonline.com", // Authentication authority URL
prompt: "select_account", // Forces account selection
},
},
plugins: [anonymous()],
});`

so when know trying to login anonymously I ran into this error when '/api/auth' gets called

ERROR [Better Auth]: Invalid db[model].create()` invocation in
C:\Users...................next\dev\server\chunks\node_modules_better-auth_dist_8a45898b._.js:1143:44

1140 if (!db[model]) {
1141 throw new TURBOPACK__imported__module$5b$project$5d2f$node_modules$2f40$better$2d$auth$2f$core$2f$dist$2f$error$2f$index$2e$mjs__$5b$app$2d$route$5d$$28$ecmascript$29$["BetterAuthError"](Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate');
1142 }
→ 1143 return await db[model].create(
Inconsistent column data: Malformed ObjectID: invalid character 'p' was found at index 1 in the provided hex string: "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS" for the field 'id'.

SERVER_ERROR: Error [PrismaClientKnownRequestError]:

Invalid db[model].create() invocation in
C:\Users...............next\dev\server\chunks\node_modules_better-auth_dist_8a45898b._.js:1143:44

1140 if (!db[model]) {
1141 throw new TURBOPACK__imported__module$5b$project$5d2f$node_modules$2f40$better$2d$auth$2f$core$2f$dist$2f$error$2f$index$2e$mjs__$5b$app$2d$route$5d$$28$ecmascript$29$["BetterAuthError"](Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate');
1142 }
→ 1143 return await db[model].create(
Inconsistent column data: Malformed ObjectID: invalid character 'p' was found at index 1 in the provided hex string: "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS" for the field 'id'.
at ignore-listed frames {
code: 'P2023',
meta: [Object],
clientVersion: '6.18.0'
}`

Im not really sure why im running into this error nor who to fix this. Anyone here has an idea?

Originally created by @RobinWitzschke on GitHub (Nov 4, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5756 Hey everyone, I ran into an issue using better-auth in next.js with the prismaAdapter using a mongodb prisma.schema so im using this prisma.schema file `generator client { provider = "prisma-client" output = "../src/generated/prisma/user" } datasource db { provider = "mongodb" url = env("DATABASE_URL_USER") } model User { id String @id @default(auto()) @map("_id") @db.ObjectId externalId String @unique @default(uuid()) // externe ID name String email String @unique emailVerified Boolean @default(false) image String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt isAnonymous Boolean? @default(false) sessions Session[] accounts Account[] } model Session { id String @id @default(auto()) @map("_id") @db.ObjectId externalId String @unique @default(uuid()) // externe ID userId String token String @unique expiresAt DateTime ipAddress String? userAgent String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User @relation(fields: [userId], references: [externalId]) } model Account { id String @id @default(auto()) @map("_id") @db.ObjectId externalId String @unique @default(uuid()) // externe ID userId String accountId String providerId String accessToken String? refreshToken String? accessTokenExpiresAt DateTime? refreshTokenExpiresAt DateTime? scope String? idToken String? password String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User @relation(fields: [userId], references: [externalId]) } model Verification { id String @id @default(auto()) @map("_id") @db.ObjectId externalId String @unique @default(uuid()) // externe ID identifier String value String expiresAt DateTime createdAt DateTime @default(now()) updatedAt DateTime @updatedAt }` and mapped the fields in the auth.ts file `import { betterAuth } from "better-auth"; import { anonymous } from "better-auth/plugins"; import { prismaAdapter } from "better-auth/adapters/prisma"; // If your Prisma file is located elsewhere, you can change the path import { PrismaClient as UserPrismaClient } from "@/generated/prisma/user/client"; const prisma = new UserPrismaClient(); export const auth = betterAuth({ user: { modelName: "User", fields: { id: "externalId", name: "name", email: "email", emailVerified: "emailVerified", image: "image", createdAt: "createdAt", updatedAt: "updatedAt", isAnonymous: "isAnonymous", sessions: "sessions", accounts: "accounts", }, }, session: { expiresIn: 1 * 24 * 60 * 60, // 1 day in seconds modelName: "Session", fields: { userId: "userId", token: "token", expiresAt: "expiresAt", ipAddress: "ipAddress", userAgent: "userAgent", createdAt: "createdAt", updatedAt: "updatedAt", }, }, account: { modelName: "Account", fields: { userId: "userId", accountId: "accountId", providerId: "providerId", accessToken: "accessToken", refreshToken: "refreshToken", accessTokenExpiresAt: "accessTokenExpiresAt", refreshTokenExpiresAt: "refreshTokenExpiresAt", scope: "scope", idToken: "idToken", password: "password", createdAt: "createdAt", updatedAt: "updatedAt", }, }, database: prismaAdapter(prisma, { provider: "mongodb", }), advanced: { cookiePrefix: "myapp", useSecureCookies: true, cookies: { sesssion_token: { name: "custom_session_token", }, }, }, socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID as string, clientSecret: process.env.MICROSOFT_CLIENT_SECRET as string, // Optional tenantId: "common", authority: "https://login.microsoftonline.com", // Authentication authority URL prompt: "select_account", // Forces account selection }, }, plugins: [anonymous()], });` so when know trying to login anonymously I ran into this error when '/api/auth' gets called `ERROR [Better Auth]: Invalid `db[model].create()` invocation in C:\Users\......\.....\.......\.next\dev\server\chunks\node_modules_better-auth_dist_8a45898b._.js:1143:44 1140 if (!db[model]) { 1141 throw new __TURBOPACK__imported__module__$5b$project$5d2f$node_modules$2f40$better$2d$auth$2f$core$2f$dist$2f$error$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["BetterAuthError"](`Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`); 1142 } → 1143 return await db[model].create( Inconsistent column data: Malformed ObjectID: invalid character 'p' was found at index 1 in the provided hex string: "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS" for the field 'id'. # SERVER_ERROR: Error [PrismaClientKnownRequestError]: Invalid `db[model].create()` invocation in C:\Users\.....\....\.....\.next\dev\server\chunks\node_modules_better-auth_dist_8a45898b._.js:1143:44 1140 if (!db[model]) { 1141 throw new __TURBOPACK__imported__module__$5b$project$5d2f$node_modules$2f40$better$2d$auth$2f$core$2f$dist$2f$error$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["BetterAuthError"](`Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`); 1142 } → 1143 return await db[model].create( Inconsistent column data: Malformed ObjectID: invalid character 'p' was found at index 1 in the provided hex string: "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS" for the field 'id'. at ignore-listed frames { code: 'P2023', meta: [Object], clientVersion: '6.18.0' }` Im not really sure why im running into this error nor who to fix this. Anyone here has an idea?
GiteaMirror added the locked label 2026-04-15 17:42:51 -05:00
Author
Owner

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

(tag @better-auth-agent) Could you clarify if you’re seeing the malformed ObjectID error during user creation specifically with anonymous sign-in, or does it occur generally when using the prismaAdapter with MongoDB? It appears the error is triggered when Better Auth attempts to create a new entry using an invalid ObjectID string (the error notes an invalid character 'p' in "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS") [1]. One possibility is that our adapter mapping for your MongoDB schema might be conflicting with the generated ObjectIDs, especially since you’re overriding the user id field to use externalId instead of MongoDB’s native _id. Could you check that when users are created, the externalId is generated in a valid format acceptable for MongoDB (or consider using the native ObjectID provided by MongoDB instead)? Additionally, ensure you've generated the Prisma client properly (via 'npx prisma generate') as suggested in the error message, and that your mapping in auth.ts correctly aligns with your prisma.schema definitions [1].

Does any of this help, or do you need further customization instructions? Feel free to ask more questions!

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3487741711 --> @better-auth-agent[bot] commented on GitHub (Nov 4, 2025): (tag @better-auth-agent) Could you clarify if you’re seeing the malformed ObjectID error during user creation specifically with anonymous sign-in, or does it occur generally when using the prismaAdapter with MongoDB? It appears the error is triggered when Better Auth attempts to create a new entry using an invalid ObjectID string (the error notes an invalid character 'p' in "1pDib0ZNtLUtkSXXWKmh2BggpPuBYwlS") [[1]](https://github.com/better-auth/better-auth/issues/5688). One possibility is that our adapter mapping for your MongoDB schema might be conflicting with the generated ObjectIDs, especially since you’re overriding the user id field to use externalId instead of MongoDB’s native _id. Could you check that when users are created, the externalId is generated in a valid format acceptable for MongoDB (or consider using the native ObjectID provided by MongoDB instead)? Additionally, ensure you've generated the Prisma client properly (via 'npx prisma generate') as suggested in the error message, and that your mapping in auth.ts correctly aligns with your prisma.schema definitions [[1]](https://github.com/better-auth/better-auth/issues/5688). Does any of this help, or do you need further customization instructions? Feel free to ask more questions! <!-- 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 (Nov 4, 2025):

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

This error happens because better-auth's default ID generation creates string IDs that aren't valid MongoDB ObjectIds, but your Prisma schema expects ObjectIds for the id fields (because of @db.ObjectId). When you try to create a user/session (especially with anonymous login), Prisma throws a "Malformed ObjectID" error since the generated ID doesn't match the required format.

To fix this:

  1. In your better-auth config, disable internal ID generation so MongoDB can auto-generate valid ObjectIds. Add this to your config:

    advanced: {
      database: {
        generateId: false,
      },
      // ...other advanced options
    },
    

    (If you already have an advanced section, just add the database.generateId: false part.)

  2. Make sure all your Prisma model id fields are defined as:

    id String @id @default(auto()) @map("_id") @db.ObjectId
    

    (Which you already have.)

This will let MongoDB handle ObjectId generation, and the error should go away. If you ever need custom IDs, you can provide a generateId function that returns a valid ObjectId string, but for most cases, letting MongoDB generate them is the simplest and safest approach.

References:

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:3487749169 --> @dosubot[bot] commented on GitHub (Nov 4, 2025): <!-- Greeting --> Hi @RobinWitzschke! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This error happens because better-auth's default ID generation creates string IDs that aren't valid MongoDB ObjectIds, but your Prisma schema expects ObjectIds for the id fields (because of @db.ObjectId). When you try to create a user/session (especially with anonymous login), Prisma throws a "Malformed ObjectID" error since the generated ID doesn't match the required format. To fix this: 1. In your better-auth config, disable internal ID generation so MongoDB can auto-generate valid ObjectIds. Add this to your config: ```ts advanced: { database: { generateId: false, }, // ...other advanced options }, ``` (If you already have an advanced section, just add the database.generateId: false part.) 2. Make sure all your Prisma model id fields are defined as: ``` id String @id @default(auto()) @map("_id") @db.ObjectId ``` (Which you already have.) This will let MongoDB handle ObjectId generation, and the error should go away. If you ever need custom IDs, you can provide a generateId function that returns a valid ObjectId string, but for most cases, letting MongoDB generate them is the simplest and safest approach. References: - [GitHub Issue: Malformed ObjectID with Prisma and MongoDB](https://github.com/better-auth/better-auth/issues/4106) - [GitHub Issue: Disable auto-generated IDs to fix ObjectId errors](https://github.com/better-auth/better-auth/issues/1100) <!-- 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/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/743c7dd4-647a-41f6-b595-98b943fcafbb?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/5756)
Author
Owner

@RobinWitzschke commented on GitHub (Nov 4, 2025):

Thanks it really was the

advanced: { database: { generateId: false, }, // ...other advanced options },

<!-- gh-comment-id:3487812781 --> @RobinWitzschke commented on GitHub (Nov 4, 2025): Thanks it really was the `advanced: { database: { generateId: false, }, // ...other advanced options },`
Author
Owner

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

Hey there! I’m glad you isolated the issue. Since you’re using MongoDB with Prisma, MongoDB manages ObjectIDs automatically. Better Auth’s default behavior generates an ID that doesn’t match MongoDB’s ObjectID format. By disabling the built‑in ID generation with advanced.database.generateId set to false, you allow Prisma and MongoDB to handle the IDs properly [2].

Next steps:
• Confirm that you’ve re‑generated your Prisma client (using “npx prisma generate”) so that your adapter and schema are in sync.
• Double‑check that all your mapped fields (especially the ones for IDs) correspond to the correct types in your MongoDB schema.
• Test the anonymous login again to verify that the ObjectIDs are now correctly generated by MongoDB.

Does that cover everything, or do you need further help with another aspect of your integration?
tag @better-auth-agent

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3487814010 --> @better-auth-agent[bot] commented on GitHub (Nov 4, 2025): Hey there! I’m glad you isolated the issue. Since you’re using MongoDB with Prisma, MongoDB manages ObjectIDs automatically. Better Auth’s default behavior generates an ID that doesn’t match MongoDB’s ObjectID format. By disabling the built‑in ID generation with advanced.database.generateId set to false, you allow Prisma and MongoDB to handle the IDs properly [[2]](https://www.better-auth.com/docs/concepts/database). Next steps: • Confirm that you’ve re‑generated your Prisma client (using “npx prisma generate”) so that your adapter and schema are in sync. • Double‑check that all your mapped fields (especially the ones for IDs) correspond to the correct types in your MongoDB schema. • Test the anonymous login again to verify that the ObjectIDs are now correctly generated by MongoDB. Does that cover everything, or do you need further help with another aspect of your integration? tag @better-auth-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)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18972