{"id":16855,"library":"mikro-orm-better-auth","title":"MikroORM Better Auth Adapter","description":"mikro-orm-better-auth is an adapter for the 'better-auth' authentication library, specifically designed to integrate with MikroORM. It provides a robust database layer for better-auth, abstracting common CRUD operations and transactional support through MikroORM's `EntityManager`. A key differentiator is its `createSchema` implementation, which leverages `ts-morph` to generate MikroORM entity files automatically. These generated entities are intelligently patched in-place on regeneration, preserving user-owned code like custom imports, decorators, methods, and comments, while only updating generator-managed fields and decorators. The current stable version is 1.1.1, released in March 2026, indicating active development with a focus on stability and feature enhancements. It is primarily SQL-oriented, utilizing MikroORM's SQL entity manager, and defers native join support for future development.","status":"active","version":"1.1.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/xudongcc/mikro-orm-better-auth","tags":["javascript","better-auth","mikro-orm","adapter","authentication","typescript"],"install":[{"cmd":"npm install mikro-orm-better-auth","lang":"bash","label":"npm"},{"cmd":"yarn add mikro-orm-better-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add mikro-orm-better-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core MikroORM functionality required for entity management and database interaction.","package":"@mikro-orm/core","optional":false},{"reason":"Knex.js driver for MikroORM, used for SQL database connectivity. Required when using SQL drivers.","package":"@mikro-orm/knex","optional":false},{"reason":"The core authentication library that this package adapts for MikroORM.","package":"better-auth","optional":false},{"reason":"Used to format generated entity code, ensuring consistency and readability.","package":"prettier","optional":false},{"reason":"Required for programmatically generating and patching TypeScript entity files.","package":"ts-morph","optional":false}],"imports":[{"note":"This library is primarily ESM-first, common in modern TypeScript projects. Avoid CommonJS `require`.","wrong":"const { mikroOrmAdapter } = require('mikro-orm-better-auth');","symbol":"mikroOrmAdapter","correct":"import { mikroOrmAdapter } from 'mikro-orm-better-auth';"},{"note":"While `better-auth` is a peer dependency, it's a named export, not a default one. Incorrectly importing as a default is a common mistake.","wrong":"import betterAuth from 'better-auth';","symbol":"betterAuth","correct":"import { betterAuth } from 'better-auth';"},{"note":"Used for per-request EntityManager isolation in MikroORM. It's a named export from @mikro-orm/core.","wrong":"import RequestContext from '@mikro-orm/core';","symbol":"RequestContext","correct":"import { RequestContext } from '@mikro-orm/core';"}],"quickstart":{"code":"import { betterAuth } from 'better-auth';\nimport { mikroOrmAdapter } from 'mikro-orm-better-auth';\nimport { MikroORM, RequestContext } from '@mikro-orm/core';\nimport { SqliteDriver, SqlEntityManager } from '@mikro-orm/sqlite';\n\nasync function bootstrap() {\n  const orm = await MikroORM.init<SqliteDriver>({\n    driver: SqliteDriver,\n    dbName: 'app.sqlite',\n    entities: [], // Mikro-orm-better-auth generates entities, so leave this empty initially or add manually\n  });\n\n  // For per-request EntityManager isolation (recommended in web servers)\n  const auth = betterAuth({\n    database: mikroOrmAdapter(() => RequestContext.getEntityManager()! as SqlEntityManager),\n  });\n\n  // Example of generating entities\n  const adapter = mikroOrmAdapter(() => orm.em, {\n    generateEntity: {\n      outputDir: 'src/auth/entities', // Output directory for generated MikroORM entities\n    },\n  });\n\n  // In a real application, you would pass the adapter to betterAuth and then call auth methods.\n  // This snippet focuses on setup and entity generation.\n  console.log('MikroORM initialized and adapter configured. Entities will be generated to src/auth/entities.');\n}\n\nbootstrap().catch(console.error);","lang":"typescript","description":"Demonstrates the basic setup of `mikro-orm-better-auth` with MikroORM, including `RequestContext` for per-request EntityManager isolation and configuring entity generation."},"warnings":[{"fix":"Manually install all required peer dependencies: `pnpm add better-auth @mikro-orm/core @mikro-orm/knex prettier ts-morph`.","message":"Starting from v1.1.1, `@mikro-orm/core`, `@mikro-orm/knex`, `better-auth`, `prettier`, and `ts-morph` were moved from direct dependencies to peer dependencies. This means these packages are no longer automatically installed and must be explicitly added to your project's `dependencies`.","severity":"breaking","affected_versions":">=1.1.1"},{"fix":"Wrap your `EntityManager` access in a function: `mikroOrmAdapter(() => orm.em)` or `mikroOrmAdapter(() => RequestContext.getEntityManager()! as SqlEntityManager)`.","message":"The `mikroOrmAdapter` now accepts a closure that returns the `EntityManager` (e.g., `() => orm.em` or `() => RequestContext.getEntityManager()`). Direct passing of the `EntityManager` instance is no longer supported.","severity":"gotcha","affected_versions":">=1.1.0"},{"fix":"Add the generated entity path to your MikroORM configuration, e.g., `entities: ['./dist/auth/entities/**/*.entity.js']` or `entities: ['./src/auth/entities/**/*.entity.ts']` for ts-node environments.","message":"When using entity generation, ensure the output directory for generated entities (`generateEntity.outputDir`) is correctly configured and included in your MikroORM `entities` array during `MikroORM.init` (or handled by an entity discovery mechanism).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Place custom logic (imports, methods, properties, decorators) outside of the generator-owned blocks. Avoid modifying the `@Entity`, `@PrimaryKey`, and `@Property` decorators or the fields they manage.","message":"Direct edits to generator-owned field definitions or MikroORM decorator arguments within generated entities may be overwritten during subsequent regeneration. The patching mechanism preserves user-owned code but not modifications to managed elements.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Run `pnpm add better-auth` (or `npm install better-auth`, `yarn add better-auth`) to install the missing peer dependency.","cause":"The `better-auth` package is a peer dependency and was not installed in the project.","error":"Error: Cannot find module 'better-auth' or its corresponding type declarations."},{"fix":"Ensure you are using `import { mikroOrmAdapter } from 'mikro-orm-better-auth';` and your project is configured for ESM if appropriate.","cause":"Incorrect import statement for `mikroOrmAdapter`, or trying to use it with CommonJS `require()` in an ESM context.","error":"TypeError: mikroOrmAdapter is not a function or is undefined"},{"fix":"Wrap the `EntityManager` in an arrow function: `mikroOrmAdapter(() => orm.em)`.","cause":"Attempting to pass the `EntityManager` instance directly to `mikroOrmAdapter` instead of a function that returns it (since v1.1.0).","error":"Argument of type 'EntityManager<IDatabaseDriver<Connection>>' is not assignable to parameter of type '() => EntityManager<IDatabaseDriver<Connection>>'."}],"ecosystem":"npm","meta_description":null}