[PR #5873] [CLOSED] Feat/5807 map custom id field #6288

Closed
opened 2026-03-13 12:53:33 -05:00 by GiteaMirror · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/better-auth/better-auth/pull/5873
Author: @Ridhim-RR
Created: 11/9/2025
Status: Closed

Base: canaryHead: feat/5807-map-custom-id-field


📝 Commits (10+)

  • a0f74d0 feat(session): persist additionalFields in cookie cache (fixes #5700)
  • 22330a2 chore: run biome format and lint fixes
  • 8d2c961 refactor(dateFormat) : refreshedSession date format issue resolved
  • ebc3aba chore:(biome format) : run biome format and lint fixes
  • 9d36bf9 feat: Add lastUsed field to Organization(#5728)
  • 321f413 Update packages/better-auth/src/api/routes/session-api.test.ts
  • 5650ff6 Merge branch 'canary' into feat/5728-add-last-used-to-organization
  • d94090a fix(types):TypeScript type errors in your codebase.
  • c0ef4b5 chore(biome format): formatting error from Biome
  • bbf11f5 fix: type errors, cookie cache parsing, and import fixes

📊 Changes

23 files changed (+1433 additions, -130 deletions)

View changed files

📝 packages/better-auth/src/__snapshots__/init.test.ts.snap (+15 -0)
📝 packages/better-auth/src/adapters/adapter-factory/index.ts (+159 -22)
📝 packages/better-auth/src/adapters/adapter-factory/test/adapter-factory.test.ts (+61 -0)
📝 packages/better-auth/src/adapters/mongodb-adapter/mongodb-adapter.ts (+81 -5)
📝 packages/better-auth/src/api/middlewares/oauth.ts (+6 -1)
📝 packages/better-auth/src/api/routes/session-api.test.ts (+2 -2)
📝 packages/better-auth/src/api/routes/sign-in.test.ts (+173 -0)
📝 packages/better-auth/src/db/get-migration-schema.test.ts (+231 -31)
📝 packages/better-auth/src/db/get-migration.ts (+176 -53)
📝 packages/better-auth/src/db/get-tables.test.ts (+118 -0)
📝 packages/better-auth/src/db/get-tables.ts (+60 -2)
📝 packages/better-auth/src/plugins/organization/adapter.ts (+34 -0)
📝 packages/better-auth/src/plugins/organization/index.ts (+1 -0)
📝 packages/better-auth/src/plugins/organization/organization.test.ts (+10 -4)
📝 packages/better-auth/src/plugins/organization/organization.ts (+6 -0)
📝 packages/better-auth/src/plugins/organization/routes/crud-org.test.ts (+199 -0)
📝 packages/better-auth/src/plugins/organization/routes/crud-org.ts (+10 -0)
📝 packages/better-auth/src/plugins/organization/schema.ts (+5 -0)
packages/better-auth/src/plugins/organization/utils.ts (+65 -0)
📝 packages/cli/src/generators/drizzle.ts (+9 -6)

...and 3 more files

📄 Description

OverView
This PR implements the feature for custom ID field mapping.
Related to #5807

This PR adds support for custom ID field names in Better Auth, enabling users to use database column names like user_id, userId, or any custom name instead of the default id. This removes the need for duplicate schema definitions and aligns Better Auth with common database naming conventions.

Note: This feature is added for these table only user ,session and account tables


Features

Core Functionality

  • Custom ID Field Names: Users can specify custom ID field names for user, session, and account tables.
  • Automatic Field Mapping: Better Auth automatically maps logical field names (id) to database column names (user_id).
  • Type-Safe: Fully supports TypeScript with proper type inference.
  • Backward Compatible: Existing code continues working without changes.

Example Usage

const auth = betterAuth({
  user: {
    fields: {
      id: "user_id"  // Custom ID field name
    }
  },
  session: {
    fields: {
      id: "session_id"
    }
  },
  account: {
    fields: {
      id: "account_id"
    }
  }

📋 Changes Made

1. Type Definitions (init-options.ts)
Allowed customization of the id field in fields property.
Before, id was excluded; now it’s allowed for users to customize.

2. Schema Generation (get-tables.ts)
Added helpers to get custom ID field names.
Updated schema generation and foreign keys to respect custom ID names.

3. Adapter Factory (adapter-factory/index.ts)
Added isIdField() helper to detect default and custom ID fields.
Added getIdFieldName() to get the database name for the ID.
Updated transformInput() with an early exit to skip ID field on create when useNumberId is true.
Updated transformOutput() to map database custom ID fields back to logical id.
Updated transformWhereClause() to use these helpers and convert IDs properly.

4. MongoDB Adapter
Updated ID field detection and transformation to support custom IDs and MongoDB’s _id.

5. Migration Generation (get-migration.ts)
Migrates proper ID field names with null safety and plugin table defaults.

6. Schema Generators (Prisma, Drizzle)
Respect custom ID fields during schema generation.
Remove redundant or conflicting attributes to match databases correctly.

🧪 Testing

  • New tests for adapter factory, MongoDB adapter, migration schema, and generators.
  • Coverage for custom ID field handling, number ID conversions, nullable foreign keys, and more.
  • All tests passing with updated snapshot files.

🚀 Migration Guide

  • Existing users: No changes needed.
  • New users with custom ID fields:
  • Update Better Auth config with custom ID field names.
  • Regenerate database schemas.
  • Run migrations.

📝 Key Fixes

  • Early exit in transformInput() to skip ID field completely for useNumberId: true + create.
  • Prevents sending id: null to the database, avoiding constraint violation errors.
  • Comprehensive ID detection with support for custom ID names in all operations.

Summary by cubic

Adds support for custom ID column names (e.g., user_id, session_id, account_id) across adapters, migrations, and schema generators. Also introduces organization lastUsed tracking and auto-activates the last used organization on sign-in. Addresses Linear 5807.

  • New Features

    • Configurable id field for user, session, and account; automatic mapping for id/_id and foreign keys in all adapters (incl. MongoDB).
    • Migrations and CLI generators (Prisma/Drizzle) respect custom ID columns; plugin tables get a default id field.
    • Organization: adds lastUsed; setActive updates lastUsed, and a helper auto-sets the last-used org on sign-in.
    • Safer number ID handling: skip id on create when useNumberId=true, avoid NaN, and persist additionalFields in session cookie cache.
  • Migration

    • Optional: set fields.id in user/session/account config, regenerate schema, and run migrations. Existing setups continue to work.

Written for commit cbae148dad. Summary will update automatically on new commits.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/better-auth/better-auth/pull/5873 **Author:** [@Ridhim-RR](https://github.com/Ridhim-RR) **Created:** 11/9/2025 **Status:** ❌ Closed **Base:** `canary` ← **Head:** `feat/5807-map-custom-id-field` --- ### 📝 Commits (10+) - [`a0f74d0`](https://github.com/better-auth/better-auth/commit/a0f74d0ab94f415f0c64a4bacfc3f1150227f16b) feat(session): persist additionalFields in cookie cache (fixes #5700) - [`22330a2`](https://github.com/better-auth/better-auth/commit/22330a2bd503828191432f4924927599203cb748) chore: run biome format and lint fixes - [`8d2c961`](https://github.com/better-auth/better-auth/commit/8d2c96132acfcaec35e4da056be6f257b3199a45) refactor(dateFormat) : refreshedSession date format issue resolved - [`ebc3aba`](https://github.com/better-auth/better-auth/commit/ebc3aba555389863c4dca013c9426e2668a97e9e) chore:(biome format) : run biome format and lint fixes - [`9d36bf9`](https://github.com/better-auth/better-auth/commit/9d36bf9cb24ae19835d09a9f52132a500253fe3a) feat: Add lastUsed field to Organization(#5728) - [`321f413`](https://github.com/better-auth/better-auth/commit/321f4136e3f8fe4048dde679b8d5b36d8f535111) Update packages/better-auth/src/api/routes/session-api.test.ts - [`5650ff6`](https://github.com/better-auth/better-auth/commit/5650ff69076cd7a38d6445d291856796461af928) Merge branch 'canary' into feat/5728-add-last-used-to-organization - [`d94090a`](https://github.com/better-auth/better-auth/commit/d94090a7de521950494672dd689f5642947773de) fix(types):TypeScript type errors in your codebase. - [`c0ef4b5`](https://github.com/better-auth/better-auth/commit/c0ef4b5235c3ecc44c1acf34393bb3f3e8976da2) chore(biome format): formatting error from Biome - [`bbf11f5`](https://github.com/better-auth/better-auth/commit/bbf11f52c3ce4c39179fad8c5d6bdf2bc212dd42) fix: type errors, cookie cache parsing, and import fixes ### 📊 Changes **23 files changed** (+1433 additions, -130 deletions) <details> <summary>View changed files</summary> 📝 `packages/better-auth/src/__snapshots__/init.test.ts.snap` (+15 -0) 📝 `packages/better-auth/src/adapters/adapter-factory/index.ts` (+159 -22) 📝 `packages/better-auth/src/adapters/adapter-factory/test/adapter-factory.test.ts` (+61 -0) 📝 `packages/better-auth/src/adapters/mongodb-adapter/mongodb-adapter.ts` (+81 -5) 📝 `packages/better-auth/src/api/middlewares/oauth.ts` (+6 -1) 📝 `packages/better-auth/src/api/routes/session-api.test.ts` (+2 -2) 📝 `packages/better-auth/src/api/routes/sign-in.test.ts` (+173 -0) 📝 `packages/better-auth/src/db/get-migration-schema.test.ts` (+231 -31) 📝 `packages/better-auth/src/db/get-migration.ts` (+176 -53) 📝 `packages/better-auth/src/db/get-tables.test.ts` (+118 -0) 📝 `packages/better-auth/src/db/get-tables.ts` (+60 -2) 📝 `packages/better-auth/src/plugins/organization/adapter.ts` (+34 -0) 📝 `packages/better-auth/src/plugins/organization/index.ts` (+1 -0) 📝 `packages/better-auth/src/plugins/organization/organization.test.ts` (+10 -4) 📝 `packages/better-auth/src/plugins/organization/organization.ts` (+6 -0) 📝 `packages/better-auth/src/plugins/organization/routes/crud-org.test.ts` (+199 -0) 📝 `packages/better-auth/src/plugins/organization/routes/crud-org.ts` (+10 -0) 📝 `packages/better-auth/src/plugins/organization/schema.ts` (+5 -0) ➕ `packages/better-auth/src/plugins/organization/utils.ts` (+65 -0) 📝 `packages/cli/src/generators/drizzle.ts` (+9 -6) _...and 3 more files_ </details> ### 📄 Description > **OverView** This PR implements the feature for custom ID field mapping. Related to #5807 This PR adds support for custom ID field names in Better Auth, enabling users to use database column names like user_id, userId, or any custom name instead of the default id. This removes the need for duplicate schema definitions and aligns Better Auth with common database naming conventions. ### **Note**: This feature is added for these table only user ,session and account tables **** ### Features **Core Functionality** - Custom ID Field Names: Users can specify custom ID field names for user, session, and account tables. - Automatic Field Mapping: Better Auth automatically maps logical field names (id) to database column names (user_id). - Type-Safe: Fully supports TypeScript with proper type inference. - Backward Compatible: Existing code continues working without changes. ### Example Usage ``` const auth = betterAuth({ user: { fields: { id: "user_id" // Custom ID field name } }, session: { fields: { id: "session_id" } }, account: { fields: { id: "account_id" } } ``` ### 📋 Changes Made **1. Type Definitions (init-options.ts)** Allowed customization of the id field in fields property. Before, id was excluded; now it’s allowed for users to customize. **2. Schema Generation (get-tables.ts)** Added helpers to get custom ID field names. Updated schema generation and foreign keys to respect custom ID names. **3. Adapter Factory (adapter-factory/index.ts)** Added isIdField() helper to detect default and custom ID fields. Added getIdFieldName() to get the database name for the ID. Updated transformInput() with an early exit to skip ID field on create when useNumberId is true. Updated transformOutput() to map database custom ID fields back to logical id. Updated transformWhereClause() to use these helpers and convert IDs properly. **4. MongoDB Adapter** Updated ID field detection and transformation to support custom IDs and MongoDB’s _id. **5. Migration Generation (get-migration.ts)** Migrates proper ID field names with null safety and plugin table defaults. **6. Schema Generators (Prisma, Drizzle)** Respect custom ID fields during schema generation. Remove redundant or conflicting attributes to match databases correctly. ### 🧪 Testing - New tests for adapter factory, MongoDB adapter, migration schema, and generators. - Coverage for custom ID field handling, number ID conversions, nullable foreign keys, and more. - All tests passing with updated snapshot files. ### 🚀 Migration Guide - Existing users: No changes needed. - New users with custom ID fields: - Update Better Auth config with custom ID field names. - Regenerate database schemas. - Run migrations. ### 📝 Key Fixes - Early exit in transformInput() to skip ID field completely for useNumberId: true + create. - Prevents sending id: null to the database, avoiding constraint violation errors. - Comprehensive ID detection with support for custom ID names in all operations. <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Adds support for custom ID column names (e.g., user_id, session_id, account_id) across adapters, migrations, and schema generators. Also introduces organization lastUsed tracking and auto-activates the last used organization on sign-in. Addresses Linear 5807. - **New Features** - Configurable id field for user, session, and account; automatic mapping for id/_id and foreign keys in all adapters (incl. MongoDB). - Migrations and CLI generators (Prisma/Drizzle) respect custom ID columns; plugin tables get a default id field. - Organization: adds lastUsed; setActive updates lastUsed, and a helper auto-sets the last-used org on sign-in. - Safer number ID handling: skip id on create when useNumberId=true, avoid NaN, and persist additionalFields in session cookie cache. - **Migration** - Optional: set fields.id in user/session/account config, regenerate schema, and run migrations. Existing setups continue to work. <sup>Written for commit cbae148dad6ede389d2631b9f5644b8dfa5d1f1c. Summary will update automatically on new commits.</sup> <!-- End of auto-generated description by cubic. --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
GiteaMirror added the pull-request label 2026-03-13 12:53:34 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#6288