@jazim/test
v2.0.7
Published
TypeORM adapter for Better-Auth
Maintainers
Readme
@jazim/typeorm-better-auth
A TypeORM adapter for Better Auth that provides seamless integration between TypeORM and Better Auth's authentication system.
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-author with pnpm:
pnpm add @jazim/typeorm-better-author with yarn:
yarn add @jazim/typeorm-better-authPeer Dependencies
This package requires the following peer dependencies:
npm install better-auth typeormBetter 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 generateFor 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
- Production Setup: Always set
synchronize: falsein production and use migrations - Environment Variables: Store database credentials in environment variables
- Connection Pooling: Configure appropriate connection pool settings for your database
- Migrations: Review generated migrations before running them in production
- Custom Entities: If using custom entity names, ensure consistency across your application
- Transaction Support: Enable transactions for critical operations
Migration Errors
If migrations fail:
- Check database connection
- Verify the provider setting matches your database type
- Ensure migrations directory exists
- Check for conflicts with existing tables
Type Errors
Ensure you're using compatible versions:
better-auth>= 1.4.0typeorm>= 0.3.2
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Support
For issues and questions:
Acknowledgments
- Better Auth - Modern authentication framework
- TypeORM - ORM for TypeScript and JavaScript
Made with ❤️ for the Better Auth community
