[GH-ISSUE #6231] Schema generation fails when referencing external models in drizzle adapter #27777

Closed
opened 2026-04-17 18:59:14 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @tobisamuel on GitHub (Nov 23, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6231

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Install dependencies:

    bun install
    
  2. Run the schema generation command:

    bun auth:generate
    
  3. You should see the error:

    [BetterAuthError: Model "category" not found in schema]
    

Current vs. Expected behavior

Current behavior:
When adding a references configuration to a field in Better Auth's organization plugin schema that points to an external model (defined in the drizzle adapter's schema config but not in Better Auth's internal schema), the auth:generate command fails with:

[BetterAuthError: Model "category" not found in schema]

The issue occurs because Better Auth's schema generation process (getAuthTables) only includes:

  • Core Better Auth tables (user, session, account, verification)
  • Plugin-defined tables (from plugin.schema)

It does not include external tables defined in the drizzle adapter's schema configuration, which are only used at runtime.

Expected behavior:
Better Auth's schema generation should either:

  1. Include external drizzle schema tables in the generation process, OR
  2. Skip validation of external references during generation (since they're validated at runtime by the drizzle adapter)

Workaround:
Commenting out the references configuration allows the generation to succeed, but this means the foreign key relationship is not validated during schema generation.

What version of Better Auth are you using?

1.4.1

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:32:56 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T8132",
    "release": "25.1.0",
    "cpuCount": 10,
    "cpuModel": "Apple M4",
    "totalMemory": "16.00 GB",
    "freeMemory": "0.27 GB"
  },
  "node": {
    "version": "v24.11.0",
    "env": "development"
  },
  "packageManager": {
    "name": "bun",
    "version": "1.3.3"
  },
  "frameworks": [
    {
      "name": "hono",
      "version": "^4.10.4"
    }
  ],
  "databases": [
    {
      "name": "postgres",
      "version": "^3.4.7"
    },
    {
      "name": "drizzle",
      "version": "^0.44.7"
    }
  ],
  "betterAuth": {
    "version": "^1.4.1"
  }
}


*Generated with: `bunx @better-auth/cli info --config ./src/lib/auth.ts --json`*

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { organization } from "better-auth/plugins";
import { db } from "../db/index";
import * as schema from "../db/schema";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
    schema: schema,  // ← category is in this schema
  }),
  plugins: [
    organization({
      schema: {
        organization: {
          additionalFields: {
            primaryCategoryId: {
              type: "string",
              required: true,
              references: {
                field: "id",
                model: "category",
                onDelete: "restrict",
              },
            },
          },
        },
      },
    }),
  ],
});

Additional context

  • Environment:

    • Better Auth: ^1.4.1
    • Drizzle ORM: ^0.44.7
    • Node.js: v24.11.0
    • Bun: latest
  • Root cause:
    The schema generation process doesn't have access to external tables passed to the drizzle adapter's schema configuration. These tables are only available at runtime, not during the static schema generation phase.

  • Impact:
    This prevents users from defining foreign key relationships to external models in plugin schemas, even though these relationships are valid and work correctly at runtime through the drizzle adapter.

  • Reproduction:
    I tested my reproduction against the latest release (1.4.1).

Originally created by @tobisamuel on GitHub (Nov 23, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6231 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Install dependencies: ```sh bun install ``` 2. Run the schema generation command: ```sh bun auth:generate ``` 3. You should see the error: ``` [BetterAuthError: Model "category" not found in schema] ``` ### Current vs. Expected behavior **Current behavior:** When adding a `references` configuration to a field in Better Auth's organization plugin schema that points to an external model (defined in the drizzle adapter's `schema` config but not in Better Auth's internal schema), the `auth:generate` command fails with: ``` [BetterAuthError: Model "category" not found in schema] ``` The issue occurs because Better Auth's schema generation process (`getAuthTables`) only includes: - Core Better Auth tables (user, session, account, verification) - Plugin-defined tables (from `plugin.schema`) It does **not** include external tables defined in the drizzle adapter's `schema` configuration, which are only used at runtime. **Expected behavior:** Better Auth's schema generation should either: 1. Include external drizzle schema tables in the generation process, OR 2. Skip validation of external references during generation (since they're validated at runtime by the drizzle adapter) **Workaround:** Commenting out the `references` configuration allows the generation to succeed, but this means the foreign key relationship is not validated during schema generation. ### What version of Better Auth are you using? 1.4.1 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:32:56 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T8132", "release": "25.1.0", "cpuCount": 10, "cpuModel": "Apple M4", "totalMemory": "16.00 GB", "freeMemory": "0.27 GB" }, "node": { "version": "v24.11.0", "env": "development" }, "packageManager": { "name": "bun", "version": "1.3.3" }, "frameworks": [ { "name": "hono", "version": "^4.10.4" } ], "databases": [ { "name": "postgres", "version": "^3.4.7" }, { "name": "drizzle", "version": "^0.44.7" } ], "betterAuth": { "version": "^1.4.1" } } *Generated with: `bunx @better-auth/cli info --config ./src/lib/auth.ts --json`* ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { organization } from "better-auth/plugins"; import { db } from "../db/index"; import * as schema from "../db/schema"; export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", schema: schema, // ← category is in this schema }), plugins: [ organization({ schema: { organization: { additionalFields: { primaryCategoryId: { type: "string", required: true, references: { field: "id", model: "category", onDelete: "restrict", }, }, }, }, }, }), ], }); ``` ### Additional context - **Environment:** - Better Auth: ^1.4.1 - Drizzle ORM: ^0.44.7 - Node.js: v24.11.0 - Bun: latest - **Root cause:** The schema generation process doesn't have access to external tables passed to the drizzle adapter's `schema` configuration. These tables are only available at runtime, not during the static schema generation phase. - **Impact:** This prevents users from defining foreign key relationships to external models in plugin schemas, even though these relationships are valid and work correctly at runtime through the drizzle adapter. - **Reproduction:** I tested my reproduction against the latest release (1.4.1).
GiteaMirror added the lockedbug labels 2026-04-17 18:59:14 -05:00
Author
Owner

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

Thank you for reporting this issue. The error is occurring because the schema generation process only includes core Better Auth tables and plugin-defined tables, while your external models (like "category") from the drizzle adapter’s schema aren’t included at generation time. This causes the validation to fail when it encounters a foreign key reference to a model it doesn't know about, even though these references work fine at runtime. A current workaround is to comment out the reference during generation, though this means the foreign key isn’t validated during the schema build [1].

Could you let us know if you’d prefer a solution that dynamically includes external schemas during generation or if skipping these validations is acceptable for your workflow?

tag @better-auth-agent if you would like an answer from the Agent

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3567928713 --> @better-auth-agent[bot] commented on GitHub (Nov 23, 2025): Thank you for reporting this issue. The error is occurring because the schema generation process only includes core Better Auth tables and plugin-defined tables, while your external models (like "category") from the drizzle adapter’s schema aren’t included at generation time. This causes the validation to fail when it encounters a foreign key reference to a model it doesn't know about, even though these references work fine at runtime. A current workaround is to comment out the reference during generation, though this means the foreign key isn’t validated during the schema build [[1]](https://github.com/better-auth/better-auth/issues/4781). Could you let us know if you’d prefer a solution that dynamically includes external schemas during generation or if skipping these validations is acceptable for your workflow? 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 (Nov 23, 2025):

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

This is a known limitation in Better Auth 1.4.1. The schema generation process only includes core tables and plugin-defined tables, not external models from the drizzle adapter's schema config. As a result, any references to models defined only in your external drizzle schema will cause schema generation to fail with errors like Model "category" not found in schema [source][source].

There’s no config or extension point to include external models or skip validation for these references during generation. The only current workaround is to comment out or remove the references config for external models when running schema generation, then add it back for runtime if needed [source][source]. This disables validation at generation time but allows your runtime setup to work as expected.

For runtime, you should merge the Better Auth generated schema with your app schema when creating your Drizzle db instance, as described in the updated docs [source]. But this does not affect the static schema generator, which still cannot see external models.

There’s no planned fix for this as of 1.4.1. You can track related discussions and workarounds in issues like #6200, #3069, and #2307.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

<!-- gh-comment-id:3567931818 --> @dosubot[bot] commented on GitHub (Nov 23, 2025): <!-- Greeting --> Hi @tobisamuel! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This is a known limitation in Better Auth 1.4.1. The schema generation process only includes core tables and plugin-defined tables, not external models from the drizzle adapter's schema config. As a result, any `references` to models defined only in your external drizzle schema will cause schema generation to fail with errors like `Model "category" not found in schema` [[source](https://github.com/better-auth/better-auth/blob/a378f81517bc6c2a6871212f2c5fc2ee72c0a95c/packages/better-auth/src/db/get-tables.ts#L7-L279)][[source](https://github.com/better-auth/better-auth/issues/6200)]. There’s no config or extension point to include external models or skip validation for these references during generation. The only current workaround is to comment out or remove the `references` config for external models when running schema generation, then add it back for runtime if needed [[source](https://github.com/better-auth/better-auth/issues/6200)][[source](https://github.com/better-auth/better-auth/issues/3069)]. This disables validation at generation time but allows your runtime setup to work as expected. For runtime, you should merge the Better Auth generated schema with your app schema when creating your Drizzle db instance, as described in the updated docs [[source](https://github.com/better-auth/better-auth/pull/6117)]. But this does not affect the static schema generator, which still cannot see external models. There’s no planned fix for this as of 1.4.1. You can track related discussions and workarounds in issues like [#6200](https://github.com/better-auth/better-auth/issues/6200), [#3069](https://github.com/better-auth/better-auth/issues/3069), and [#2307](https://github.com/better-auth/better-auth/issues/2307). <!-- 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/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/d6d96760-f12a-4e6a-84b1-25bf720cd89b?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=This%20is%20a%20known%20limitation%20in%20Better%20Auth%201.4.1.%20The%20schema%20generation%20process%20only%20includes%20core%20tables%20and%20plugin-defined%20tables%2C%20not%20external%20models%20from%20the%20drizzle%20adapter%27s%20schema%20config.%20As%20a%20result%2C%20any%20%60references%60%20to%20models%20defined%20only%20in%20your%20external%20drizzle%20schema%20will%20cause%20schema%20generation%20to%20fail%20with%20errors%20like%20%60Model%20%22category%22%20not%20found%20in%20schema%60%C2%A0%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/blob/a378f81517bc6c2a6871212f2c5fc2ee72c0a95c/packages/better-auth/src/db/get-tables.ts%23L7-L279%29%5D%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/6200%29%5D.%0A%0AThere%E2%80%99s%20no%20config%20or%20extension%20point%20to%20include%20external%20models%20or%20skip%20validation%20for%20these%20references%20during%20generation.%20The%20only%20current%20workaround%20is%20to%20comment%20out%20or%20remove%20the%20%60references%60%20config%20for%20external%20models%20when%20running%20schema%20generation%2C%20then%20add%20it%20back%20for%20runtime%20if%20needed%C2%A0%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/6200%29%5D%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/3069%29%5D.%20This%20disables%20validation%20at%20generation%20time%20but%20allows%20your%20runtime%20setup%20to%20work%20as%20expected.%0A%0AFor%20runtime%2C%20you%20should%20merge%20the%20Better%20Auth%20generated%20schema%20with%20your%20app%20schema%20when%20creating%20your%20Drizzle%20db%20instance%2C%20as%20described%20in%20the%20updated%20docs%C2%A0%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/pull/6117%29%5D.%20But%20this%20does%20not%20affect%20the%20static%20schema%20generator%2C%20which%20still%20cannot%20see%20external%20models.%0A%0AThere%E2%80%99s%20no%20planned%20fix%20for%20this%20as%20of%201.4.1.%20You%20can%20track%20related%20discussions%20and%20workarounds%20in%20issues%20like%20%5B%236200%5D%28https%3A//github.com/better-auth/better-auth/issues/6200%29%2C%20%5B%233069%5D%28https%3A//github.com/better-auth/better-auth/issues/3069%29%2C%20and%20%5B%232307%5D%28https%3A//github.com/better-auth/better-auth/issues/2307%29.)&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/6231)
Author
Owner

@ping-maxwell commented on GitHub (Nov 23, 2025):

In your references, you wrote category as a model.

You'll need to tell better-auth this model exists too, and it's field as well.

The easiest way to do this is by making a plugin:

const categoryPlugin = () => {
	return {
		id: "category-plugin",
		schema: {
			category: {
				fields: {
					// id is included by default, don't include it here

					// example fields:
					name: {
						type: "string",
						required: true,
					},
					description: {
						type: "string",
						required: false,
					},
				},
			},
		},
	} satisfies BetterAuthPlugin;
};

Then call that function in your plugins array and it should work.

<!-- gh-comment-id:3568171606 --> @ping-maxwell commented on GitHub (Nov 23, 2025): In your `references`, you wrote `category` as a model. You'll need to tell better-auth this model exists too, and it's field as well. The easiest way to do this is by making a plugin: ```ts const categoryPlugin = () => { return { id: "category-plugin", schema: { category: { fields: { // id is included by default, don't include it here // example fields: name: { type: "string", required: true, }, description: { type: "string", required: false, }, }, }, }, } satisfies BetterAuthPlugin; }; ``` Then call that function in your plugins array and it should work.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#27777