jwt() Plugin: TypeError: Cannot read properties of undefined (reading 'modelName') on API calls with mongodbAdapter #1199

Closed
opened 2026-03-13 08:27:47 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @Husain010 on GitHub (May 13, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Setup Better Auth:
    • Configure Better Auth in a Next.js project using mongodbAdapter with a valid MongoDB connection.
    • Ensure necessary environment variables (MONGODB_URI, AUTH_DB_NAME, BETTER_AUTH_SECRET, BETTER_AUTH_URL) are set.
    • The lib/auth.ts includes the jwt() plugin. (See "Auth config" section below for the minimal config).
  2. API Route Handler:
    • Set up the Next.js API route handler at app/api/auth/[...all]/route.ts using toNextJsHandler(auth).
  3. Implement Client-Side Auth:
    • Use authClient.signUp.email for user registration.
    • Use authClient.signIn.email for user login.
  4. Trigger the Bug:
    • After a user successfully signs in (the better-auth.session-token cookie is set by the server):
      • Attempt to call the /api/auth/get-session endpoint (this happens automatically if using the useSession hook or if Next.js middleware is configured to check sessions).
      • OR, attempt to call the /api/auth/token endpoint directly (e.g., via fetch from the client).
  5. Observe:
    • A 500 HTTP error is returned from the server for /api/auth/get-session and/or /api/auth/token.
    • The Next.js server console logs show: TypeError: Cannot read properties of undefined (reading 'modelName').
    • The jwks collection is not created in MongoDB if /api/auth/token was the endpoint that failed.

Current vs. Expected behavior

  • Current Behavior:

    • When the jwt() plugin is enabled, calls to /api/auth/get-session and /api/auth/token result in a 500 server error.
    • The server log for this error is: TypeError: Cannot read properties of undefined (reading 'modelName').
    • The JWT functionality (token generation, JWKS creation) does not work.
    • If the jwt() plugin is disabled, /api/auth/get-session works correctly.
    • If only the bearer() plugin is enabled (and jwt() is disabled), /api/auth/get-session also works correctly.
  • Expected Behavior:

    • /api/auth/get-session should return the current session details without a 500 error, even when the jwt() plugin is enabled.
    • /api/auth/token should successfully generate a JWT for an authenticated user and, on its first successful run, initialize the jwks collection in MongoDB.
    • Both endpoints should function without throwing a TypeError related to modelName.

What version of Better Auth are you using?

1.2.7

Provide environment information

*   OS:  macOS Sonoma 14.x
*   Browser: Chrome 136
*   Node.js Version: v20.18.0

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

Backend, Client

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { MongoClient, Db } from "mongodb"; // Assuming MongoClient is used like this
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { jwt /*, bearer */ } from "better-auth/plugins";

// Environment variables (MONGODB_URI, AUTH_DB_NAME, BETTER_AUTH_SECRET, BETTER_AUTH_URL) are checked and used
const uri = process.env.MONGODB_URI!;
const dbNameFromEnv = process.env.AUTH_DB_NAME || "auth";

let dbPromise: Promise<Db> | null = null;
const getDb = () => {
  if (!dbPromise) {
    dbPromise = (async () => {
      const client = new MongoClient(uri);
      await client.connect();
      return client.db(dbNameFromEnv);
    })();
  }
  return dbPromise;
};

export const auth = betterAuth({
  database: async () => {
    const db = await getDb();
    const adapterFactory = mongodbAdapter(db);
    if (typeof adapterFactory === 'function') {
      return adapterFactory({}); // Call the factory if it is one
    }
    return adapterFactory; // Otherwise, assume it's the adapter itself
  },
  secret: process.env.BETTER_AUTH_SECRET || "temporary-dev-secret",
  baseUrl: process.env.BETTER_AUTH_URL || "http://localhost:3000",
  emailAndPassword: {
    enabled: true,
  },
  user: {
    modelName: "user",
    additionalFields: {
      name: { type: "string" },
      // other relevant fields like roles, platformAccess etc. were also defined
    }
  },
  session: {
    // Using default expiresIn, updateAge. May have custom cookieCache settings.
    // Example:
    // expiresIn: 60 * 60 * 24 * 7, // 7 days
    // updateAge: 60 * 60 * 24,    // 1 day
    // cookieCache: {
    //     enabled: true,
    //     maxAge: 5 * 60 // Cache duration in seconds
    // }
  },
  sessionUserInfo: {
    fields: [
      "id",
      "email",
      "name",
      // other relevant fields
    ]
  },
  plugins: [
    jwt(),
    // bearer() // Error occurs even if bearer() is commented out
  ]
});

Additional context

The @better-auth/cli migrate and @better-auth/cli generate commands both indicate that the mongodb-adapter is not supported for these CLI operations. This means the creation of the jwks collection relies on the JWT plugin's runtime behavior (presumably upon the first call to /api/auth/token).

  • The issue seems to stem from the jwt() plugin potentially trying to access user model configurations (like modelName) in a context where it's undefined, specifically when its own API routes (/token) or when it influences other core routes (/get-session) are called.
Originally created by @Husain010 on GitHub (May 13, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. **Setup Better Auth:** * Configure Better Auth in a Next.js project using `mongodbAdapter` with a valid MongoDB connection. * Ensure necessary environment variables (`MONGODB_URI`, `AUTH_DB_NAME`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`) are set. * The `lib/auth.ts` includes the `jwt()` plugin. (See "Auth config" section below for the minimal config). 2. **API Route Handler:** * Set up the Next.js API route handler at `app/api/auth/[...all]/route.ts` using `toNextJsHandler(auth)`. 3. **Implement Client-Side Auth:** * Use `authClient.signUp.email` for user registration. * Use `authClient.signIn.email` for user login. 4. **Trigger the Bug:** * After a user successfully signs in (the `better-auth.session-token` cookie is set by the server): * Attempt to call the `/api/auth/get-session` endpoint (this happens automatically if using the `useSession` hook or if Next.js middleware is configured to check sessions). * OR, attempt to call the `/api/auth/token` endpoint directly (e.g., via `fetch` from the client). 5. **Observe:** * A 500 HTTP error is returned from the server for `/api/auth/get-session` and/or `/api/auth/token`. * The Next.js server console logs show: `TypeError: Cannot read properties of undefined (reading 'modelName')`. * The `jwks` collection is not created in MongoDB if `/api/auth/token` was the endpoint that failed. ### Current vs. Expected behavior * **Current Behavior:** * When the `jwt()` plugin is enabled, calls to `/api/auth/get-session` and `/api/auth/token` result in a 500 server error. * The server log for this error is: `TypeError: Cannot read properties of undefined (reading 'modelName')`. * The JWT functionality (token generation, JWKS creation) does not work. * If the `jwt()` plugin is disabled, `/api/auth/get-session` works correctly. * If only the `bearer()` plugin is enabled (and `jwt()` is disabled), `/api/auth/get-session` also works correctly. * **Expected Behavior:** * `/api/auth/get-session` should return the current session details without a 500 error, even when the `jwt()` plugin is enabled. * `/api/auth/token` should successfully generate a JWT for an authenticated user and, on its first successful run, initialize the `jwks` collection in MongoDB. * Both endpoints should function without throwing a `TypeError` related to `modelName`. ### What version of Better Auth are you using? 1.2.7 ### Provide environment information ```bash * OS: macOS Sonoma 14.x * Browser: Chrome 136 * Node.js Version: v20.18.0 ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { MongoClient, Db } from "mongodb"; // Assuming MongoClient is used like this import { mongodbAdapter } from "better-auth/adapters/mongodb"; import { jwt /*, bearer */ } from "better-auth/plugins"; // Environment variables (MONGODB_URI, AUTH_DB_NAME, BETTER_AUTH_SECRET, BETTER_AUTH_URL) are checked and used const uri = process.env.MONGODB_URI!; const dbNameFromEnv = process.env.AUTH_DB_NAME || "auth"; let dbPromise: Promise<Db> | null = null; const getDb = () => { if (!dbPromise) { dbPromise = (async () => { const client = new MongoClient(uri); await client.connect(); return client.db(dbNameFromEnv); })(); } return dbPromise; }; export const auth = betterAuth({ database: async () => { const db = await getDb(); const adapterFactory = mongodbAdapter(db); if (typeof adapterFactory === 'function') { return adapterFactory({}); // Call the factory if it is one } return adapterFactory; // Otherwise, assume it's the adapter itself }, secret: process.env.BETTER_AUTH_SECRET || "temporary-dev-secret", baseUrl: process.env.BETTER_AUTH_URL || "http://localhost:3000", emailAndPassword: { enabled: true, }, user: { modelName: "user", additionalFields: { name: { type: "string" }, // other relevant fields like roles, platformAccess etc. were also defined } }, session: { // Using default expiresIn, updateAge. May have custom cookieCache settings. // Example: // expiresIn: 60 * 60 * 24 * 7, // 7 days // updateAge: 60 * 60 * 24, // 1 day // cookieCache: { // enabled: true, // maxAge: 5 * 60 // Cache duration in seconds // } }, sessionUserInfo: { fields: [ "id", "email", "name", // other relevant fields ] }, plugins: [ jwt(), // bearer() // Error occurs even if bearer() is commented out ] }); ``` ### Additional context The `@better-auth/cli migrate` and `@better-auth/cli generate` commands both indicate that the `mongodb-adapter is not supported` for these CLI operations. This means the creation of the `jwks` collection relies on the JWT plugin's runtime behavior (presumably upon the first call to `/api/auth/token`). * The issue seems to stem from the `jwt()` plugin potentially trying to access user model configurations (like `modelName`) in a context where it's undefined, specifically when its own API routes (`/token`) or when it influences other core routes (`/get-session`) are called.
Author
Owner

@Bekacru commented on GitHub (Jun 16, 2025):

Hey, could you please confirm this is still an issue with the latest version?

@Bekacru commented on GitHub (Jun 16, 2025): Hey, could you please confirm this is still an issue with the latest version?
Author
Owner

@DiegoGonzalezCruz commented on GitHub (Jun 19, 2025):

I can't use the jwt plugin either.

@DiegoGonzalezCruz commented on GitHub (Jun 19, 2025): I can't use the jwt plugin either.
Author
Owner

@dosubot[bot] commented on GitHub (Sep 18, 2025):

Hi, @Husain010. 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 a TypeError related to reading 'modelName' when using the jwt() plugin with mongodbAdapter in Better Auth.
  • This error causes 500 responses on certain API calls and blocks JWT token generation after user sign-in in a Next.js environment.
  • Disabling the jwt() plugin avoids the error, indicating the issue is specific to that plugin.
  • A maintainer requested confirmation if the issue persists in the latest version.
  • Another user also confirmed being unable to use the jwt plugin, suggesting the problem affects multiple users.

Next Steps:

  • Please let me know if this issue is still relevant with the latest version of better-auth by commenting here.
  • If I don’t hear back within 7 days, I will automatically close this issue.

Thanks for your understanding and contribution!

@dosubot[bot] commented on GitHub (Sep 18, 2025): Hi, @Husain010. 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 a TypeError related to reading 'modelName' when using the jwt() plugin with mongodbAdapter in Better Auth. - This error causes 500 responses on certain API calls and blocks JWT token generation after user sign-in in a Next.js environment. - Disabling the jwt() plugin avoids the error, indicating the issue is specific to that plugin. - A maintainer requested confirmation if the issue persists in the latest version. - Another user also confirmed being unable to use the jwt plugin, suggesting the problem affects multiple users. **Next Steps:** - Please let me know if this issue is still relevant with the latest version of better-auth by commenting here. - If I don’t hear back within 7 days, I will automatically close this issue. Thanks for your understanding and contribution!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1199