MikroORM Better Auth Adapter

1.1.1 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the basic setup of `mikro-orm-better-auth` with MikroORM, including `RequestContext` for per-request EntityManager isolation and configuring entity generation.

import { betterAuth } from 'better-auth';
import { mikroOrmAdapter } from 'mikro-orm-better-auth';
import { MikroORM, RequestContext } from '@mikro-orm/core';
import { SqliteDriver, SqlEntityManager } from '@mikro-orm/sqlite';

async function bootstrap() {
  const orm = await MikroORM.init<SqliteDriver>({
    driver: SqliteDriver,
    dbName: 'app.sqlite',
    entities: [], // Mikro-orm-better-auth generates entities, so leave this empty initially or add manually
  });

  // For per-request EntityManager isolation (recommended in web servers)
  const auth = betterAuth({
    database: mikroOrmAdapter(() => RequestContext.getEntityManager()! as SqlEntityManager),
  });

  // Example of generating entities
  const adapter = mikroOrmAdapter(() => orm.em, {
    generateEntity: {
      outputDir: 'src/auth/entities', // Output directory for generated MikroORM entities
    },
  });

  // In a real application, you would pass the adapter to betterAuth and then call auth methods.
  // This snippet focuses on setup and entity generation.
  console.log('MikroORM initialized and adapter configured. Entities will be generated to src/auth/entities.');
}

bootstrap().catch(console.error);

view raw JSON →