npm package: @jazim/test
Description: TypeORM adapter for Better-Auth
Author: Jazim Abbas
Latest version: 2.0.7

# @jazim/typeorm-better-auth

A TypeORM adapter for [Better Auth](https://www.better-auth.com/) that provides seamless integration between TypeORM and Better Auth's authentication system.

[![npm version](https://img.shields.io/npm/v/@jazim/typeorm-better-auth.svg)](https://www.npmjs.com/package/@jazim/typeorm-better-auth)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔌 **Seamless Integration** - Drop-in TypeORM adapter for Better Auth
- 🗄️ **Multi-Database Support** - PostgreSQL, MySQL, and SQLite
- 🔄 **Auto Generation** - Automatic entity and migration generation
- 🎯 **Type Safe** - Full TypeScript support
- 🛠️ **Customizable** - Configure entity names and paths
- 💪 **Transaction Support** - Built-in transaction handling
- 🔍 **Advanced Queries** - Support for complex where clauses and operators

## Installation

```bash
npm install @jazim/typeorm-better-auth
```

or with pnpm:

```bash
pnpm add @jazim/typeorm-better-auth
```

or with yarn:

```bash
yarn add @jazim/typeorm-better-auth
```

### Peer Dependencies

This package requires the following peer dependencies:

```bash
npm install better-auth typeorm
```

## Better Auth CLI Generate Schema
You can use the Better Auth CLI to generate the database schema using the TypeORM adapter.

```bash
npx @better-auth/cli@latest generate
```

For more information, refer to the [Better Auth CLI documentation](https://www.better-auth.com/docs/concepts/cli).

## Quick Start

### 1. Setup TypeORM DataSource

Create a TypeORM DataSource configuration:

```typescript
import { DataSource } from "typeorm";

export const dataSource = new DataSource({
  type: "postgres", // or "mysql" or "sqlite"
  host: "localhost",
  port: 5432,
  username: "your_username",
  password: "your_password",
  database: "your_database",
  entities: ["./entities/**/*.ts"],
  migrations: ["./migrations/**/*.ts"],
  synchronize: false, // Set to false in production
});
```

### 2. Initialize the Adapter

```typescript
import { betterAuth } from "better-auth";
import { typeormAdapter } from "@jazim/typeorm-better-auth";
import { dataSource } from "./data-source";

// Initialize the datasource
await dataSource.initialize();

export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    entitiesPath: "./entities",
    migrationsPath: "./migrations",
  }),
  // ... other Better Auth options
});
```

### 3. Generate Entities and Migrations

The adapter will automatically generate TypeORM entities and migrations based on your Better Auth configuration. The generated files will be saved to the paths specified in the configuration.

## Configuration

### TypeOrmAdapterConfig

The adapter accepts a configuration object with the following options:

```typescript
interface TypeOrmAdapterConfig {
  /**
   * Database provider
   * @default "postgres"
   */
  provider?: "mysql" | "postgres" | "sqlite";

  /**
   * Custom entity names for the adapter models
   * @default { user: "User", account: "Account", session: "Session", verification: "Verification" }
   */
  entities?: {
    user?: string;
    account?: string;
    session?: string;
    verification?: string;
  };

  /**
   * Generate TypeORM entity files
   * @default true
   */
  generateEntities?: boolean;

  /**
   * Generate migration files
   * @default true
   */
  generateMigrations?: boolean;

  /**
   * Path to save generated entities
   * @default "./entities"
   */
  entitiesPath?: string;

  /**
   * Path to save generated migrations
   * @default "./migrations"
   */
  migrationsPath?: string;

  /**
   * Enable transaction support
   * @default false
   */
  transaction?: boolean;
}
```

## Usage Examples

### Basic Setup with PostgreSQL

```typescript
import { DataSource } from "typeorm";
import { betterAuth } from "better-auth";
import { typeormAdapter } from "@jazim/typeorm-better-auth";

const dataSource = new DataSource({
  type: "postgres",
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT || "5432"),
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  entities: ["./entities/**/*.ts"],
  migrations: ["./migrations/**/*.ts"],
});

await dataSource.initialize();

export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    entitiesPath: "./entities",
    migrationsPath: "./migrations",
  }),
  emailAndPassword: {
    enabled: true,
  },
});
```

### Custom Entity Names

```typescript
export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    entities: {
      user: "CustomUser",
      account: "CustomAccount",
      session: "CustomSession",
      verification: "CustomVerification",
    },
    entitiesPath: "./src/entities",
    migrationsPath: "./src/migrations",
  }),
});
```

### With Better Auth Model Names

If you're using custom model names in Better Auth, the adapter will respect them:

```typescript
export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    entitiesPath: "./entities",
    migrationsPath: "./migrations",
  }),
  user: {
    modelName: "users", // Custom model name
  },
  session: {
    modelName: "user_sessions",
  },
});
```

### SQLite Configuration

```typescript
import { DataSource } from "typeorm";
import { typeormAdapter } from "@jazim/typeorm-better-auth";

const dataSource = new DataSource({
  type: "better-sqlite3",
  database: "./database.sqlite",
  entities: ["./entities/**/*.ts"],
});

await dataSource.initialize();

export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "sqlite",
  }),
});
```

### MySQL Configuration

```typescript
const dataSource = new DataSource({
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: "root",
  password: "password",
  database: "myapp",
  entities: ["./entities/**/*.ts"],
});

await dataSource.initialize();

export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "mysql",
  }),
});
```

### Transaction Support

Enable transaction support for better data consistency:

```typescript
export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    transaction: true, // Enable transactions
  }),
});
```

### Disable Auto-Generation

If you want to manage entities and migrations manually:

```typescript
export const auth = betterAuth({
  database: typeormAdapter(dataSource, {
    provider: "postgres",
    generateEntities: false,
    generateMigrations: false,
  }),
});
```

## Generated Files

### Entity Files

The adapter generates TypeORM entity files based on your Better Auth schema. Example generated entity:

```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity("user")
export class User {
  @PrimaryGeneratedColumn("uuid")
  id!: string;

  @Column("varchar")
  email!: string;

  @Column("varchar")
  name!: string;

  @Column("varchar", { nullable: true })
  emailVerified?: string | null;

  @Column("varchar", { nullable: true })
  image?: string | null;

  @Column("timestamp")
  createdAt!: Date;

  @Column("timestamp")
  updatedAt!: Date;
}
```

### Migration Files

Migration files are generated with timestamps and include both `up` and `down` methods:

```typescript
import { MigrationInterface, QueryRunner, Table } from "typeorm";

export class BetterAuthMigration1234567890 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        name: "user",
        columns: [
          {
            name: "id",
            type: "uuid",
            isPrimary: true,
            isGenerated: true,
            generationStrategy: "uuid",
          },
          // ... more columns
        ],
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable("user");
  }
}
```

## Database Schema

The adapter creates the following tables (default names):

- **user** - User accounts
- **account** - OAuth accounts linked to users
- **session** - User sessions
- **verification** - Email verification tokens

Each table is fully compatible with Better Auth's requirements and supports all authentication features.

## Best Practices

1. **Production Setup**: Always set `synchronize: false` in production and use migrations
2. **Environment Variables**: Store database credentials in environment variables
3. **Connection Pooling**: Configure appropriate connection pool settings for your database
4. **Migrations**: Review generated migrations before running them in production
5. **Custom Entities**: If using custom entity names, ensure consistency across your application
6. **Transaction Support**: Enable transactions for critical operations

### Migration Errors

If migrations fail:

1. Check database connection
2. Verify the provider setting matches your database type
3. Ensure migrations directory exists
4. Check for conflicts with existing tables

### Type Errors

Ensure you're using compatible versions:

- `better-auth` >= 1.4.0
- `typeorm` >= 0.3.2

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT

## Support

For issues and questions:

- [GitHub Issues](https://github.com/jazimabbas/typeorm-better-auth/issues)
- [Better Auth Documentation](https://www.better-auth.com/docs)
- [TypeORM Documentation](https://typeorm.io/)

## Acknowledgments

- [Better Auth](https://www.better-auth.com/) - Modern authentication framework
- [TypeORM](https://typeorm.io/) - ORM for TypeScript and JavaScript

---

Made with ❤️ for the Better Auth community