npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jazim/test

v2.0.7

Published

TypeORM adapter for Better-Auth

Readme

@jazim/typeorm-better-auth

A TypeORM adapter for Better Auth that provides seamless integration between TypeORM and Better Auth's authentication system.

npm version License: 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

npm install @jazim/typeorm-better-auth

or with pnpm:

pnpm add @jazim/typeorm-better-auth

or with yarn:

yarn add @jazim/typeorm-better-auth

Peer Dependencies

This package requires the following peer dependencies:

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.

npx @better-auth/cli@latest generate

For more information, refer to the Better Auth CLI documentation.

Quick Start

1. Setup TypeORM DataSource

Create a TypeORM DataSource configuration:

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

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:

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

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

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:

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

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

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:

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:

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:

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:

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:

Acknowledgments


Made with ❤️ for the Better Auth community