{"id":16601,"library":"better-auth-mikro-orm","title":"Mikro ORM Adapter for Better Auth","description":"This package provides a Mikro ORM adapter for Better Auth, allowing developers to integrate Better Auth's authentication functionalities with a MikroORM-managed database. The current stable version is `0.5.0`, and the project demonstrates a relatively active release cadence with frequent minor and patch updates based on the provided changelog. A key differentiator is its specific integration with MikroORM, serving as a bridge for authentication operations. It's crucial to note that this adapter does not handle database schema management directly; users are expected to define and manage their core Better Auth and plugin-specific schemas within MikroORM independently. This also means it cannot be used with `@better-auth/cli` for schema generation or migrations, distinguishing it from adapters that abstract schema concerns.","status":"active","version":"0.5.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/octet-stream/better-auth-mikro-orm","tags":["javascript","auth","better-auth","db","database","adapter","better-auth-adapter","mikro-orm","typescript"],"install":[{"cmd":"npm install better-auth-mikro-orm","lang":"bash","label":"npm"},{"cmd":"yarn add better-auth-mikro-orm","lang":"bash","label":"yarn"},{"cmd":"pnpm add better-auth-mikro-orm","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for Mikro ORM functionality and entity management.","package":"@mikro-orm/core","optional":false},{"reason":"The core Better Auth library, which this package extends as a database adapter.","package":"better-auth","optional":false}],"imports":[{"note":"The package is ESM-first, and CommonJS `require` syntax is not directly supported.","wrong":"const mikroOrmAdapter = require('better-auth-mikro-orm');","symbol":"mikroOrmAdapter","correct":"import { mikroOrmAdapter } from 'better-auth-mikro-orm';"},{"note":"Import types separately for strict TypeScript environments or if only the type definition is needed.","symbol":"AdapterInstance","correct":"import type { AdapterInstance } from 'better-auth-mikro-orm';"},{"note":"While not explicitly shown in quickstart, you might need to import types for Better Auth's core schema entities if extending them.","symbol":"AuthEntity","correct":"import type { AuthEntity } from 'better-auth-mikro-orm';"}],"quickstart":{"code":"import { mikroOrmAdapter } from \"better-auth-mikro-orm\";\nimport { betterAuth } from \"better-auth\";\nimport { MikroORM } from \"@mikro-orm/core\";\n\n// Assume 'orm' is an initialized MikroORM instance\n// For demonstration, we'll create a mock, but in a real app, it would be MikroORM.init\nconst mockEntityManager = {\n  find: async () => [],\n  findOne: async () => null,\n  persistAndFlush: async () => {},\n  removeAndFlush: async () => {},\n  nativeInsert: async () => {},\n  nativeUpdate: async () => {},\n  nativeDelete: async () => {},\n  transactional: async (cb: any) => cb(),\n  getRepository: (entity: any) => ({ /* mock methods */ }),\n  count: async () => 0\n};\n\nconst orm = { em: mockEntityManager } as unknown as MikroORM; // Your Mikro ORM instance\n\nexport const auth = betterAuth({\n  database: mikroOrmAdapter(orm),\n\n  // Don't forget to disable the ID generator if it is already managed by MikroORM\n  advanced: {\n    database: {\n      generateId: false\n    }\n  }\n});\n\nconsole.log(\"Better Auth instance initialized with MikroORM adapter.\");\n// You would typically use 'auth' here, e.g., auth.signIn, auth.createUser\n// For example, to check if the adapter works:\nasync function demonstrateUsage() {\n  // This is a conceptual example, actual usage depends on Better Auth's API\n  // which would interact with the adapter's methods like find, create, etc.\n  // Example: Trying to create a user (conceptual, requires Better Auth's specific API)\n  try {\n    // This part is highly dependent on Better Auth's actual API for user creation\n    // and how it interacts with the adapter. This is illustrative.\n    // const newUser = await auth.createUser({ email: \"test@example.com\", password: \"securepassword\" });\n    // console.log(\"Attempted to create user via Better Auth with MikroORM adapter.\");\n    console.log(\"Adapter setup successful. Ready for Better Auth operations.\");\n  } catch (error) {\n    console.error(\"Error during conceptual user creation:\", error);\n  }\n}\n\ndemonstrateUsage();\n","lang":"typescript","description":"This quickstart demonstrates how to initialize Better Auth using the `better-auth-mikro-orm` adapter, passing a MikroORM instance and disabling Better Auth's default ID generator."},"warnings":[{"fix":"For `updateMany` operations, be aware that the Identity Map will not reflect changes. Manual `em.clear()` or `em.refresh()` might be necessary for affected entities if up-to-date Identity Map state is required immediately after `updateMany`.","message":"In `v0.4.2`, the `updateMany` and `deleteMany` methods were changed to use MikroORM's `nativeDelete` and `nativeUpdate` methods. This change prevents the MikroORM Identity Map from being updated for affected entities. While `deleteMany` was later corrected in `v0.4.1` to use `remove` (restoring Identity Map updates for deletions), `updateMany` continues to bypass the Identity Map in `v0.4.x` and potentially later versions.","severity":"breaking","affected_versions":">=0.4.2"},{"fix":"Manually define MikroORM entities for Better Auth's core schema and any plugins. Use MikroORM's migration system (e.g., `mikro-orm migration:create`, `mikro-orm migration:up`) to manage your database schema.","message":"This MikroORM adapter explicitly does not manage database schemas. You cannot use the `@better-auth/cli` for schema generation or migrations with this package. Developers must define and manage all necessary Better Auth and plugin-specific entities and migrations using MikroORM's native schema management tools.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Add `advanced: { database: { generateId: false } }` to your `betterAuth` configuration object to prevent conflicts with MikroORM's ID generation strategy.","message":"When integrating Better Auth with MikroORM, you must disable Better Auth's built-in ID generator by setting `advanced.database.generateId: false` in the Better Auth configuration. MikroORM is expected to manage ID generation for your entities.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure your MikroORM instance is fully initialized before passing it to `mikroOrmAdapter`. For example: `const orm = await MikroORM.init(config);` then `mikroOrmAdapter(orm)`.","message":"The adapter expects an initialized `MikroORM` instance. Ensure that `MikroORM.init` or `MikroORM.initSync` has been called and the resulting `orm` object is passed to `mikroOrmAdapter`. The `EntityManager` (`orm.em`) must be accessible and configured.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you are using `import { mikroOrmAdapter } from 'better-auth-mikro-orm';` for ESM. Verify `\"type\": \"module\"` is set in your `package.json` if using ESM. Check that the package is correctly installed.","cause":"Attempting to use CommonJS `require()` syntax in an ESM project, or incorrect import path/module resolution issues.","error":"Error: Cannot find module 'better-auth-mikro-orm' or its corresponding type declarations."},{"fix":"Verify that `MikroORM.init()` or `MikroORM.initSync()` successfully completes and returns a valid `MikroORM` instance before passing it to `mikroOrmAdapter`. Await the initialization call if it's asynchronous.","cause":"The MikroORM instance passed to `mikroOrmAdapter` was not fully initialized, or `MikroORM.init` failed, resulting in an undefined or null `EntityManager` (`orm.em`).","error":"TypeError: Cannot read properties of undefined (reading 'em') or 'em' is null."},{"fix":"Add or verify `advanced: { database: { generateId: false } }` in your `betterAuth` configuration. Ensure your MikroORM entities have appropriate primary key strategies (e.g., `uuid` or `serial`).","cause":"This typically occurs when `advanced.database.generateId: false` was not set in the Better Auth configuration, leading to Better Auth attempting to generate IDs that conflict with MikroORM's auto-generated primary keys.","error":"Better Auth Error: duplicate key value violates unique constraint \"users_id_pkey\""}],"ecosystem":"npm"}