DEV Community

Cover image for Handling Migrations on NestJS with TypeORM
Rivier Grullon
Rivier Grullon

Posted on

Handling Migrations on NestJS with TypeORM

When facing challenges in managing migrations in NestJS with TypeORM, I realized that the existing documentation did not adequately address this area. Given my recent immersion in NestJS, I decided to share the solution I discovered while researching and resolving these issues.

One of the initial challenges arose when I realized that maintaining the "synchronize" property as true is not a recommended practice for production environments, as it could result in data loss. Consequently, I opted to implement migrations. However, initially, I didn't know how to separate the TypeORM configuration into an independent file and turn it into a data source for the TypeORM CLI to recognize.

PSDT: I'll assume that you're ready create a new nestjs project.

1. TypeORM Configuration in an Independent File

In the file src/db/typeorm.ts, I defined the data source options as follows:


// src/db/typeorm.ts
import { DataSource, DataSourceOptions } from 'typeorm';

export const dataSourceOptions: DataSourceOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'securepassword',
  database: 'db',
  synchronize: false,
  entities: ['dist/**/*.entity.js'],
  migrationsRun: false,
  migrations: ['dist/db/migrations/*.js'],
};

const AppDataSource = new DataSource(dataSourceOptions);

export default AppDataSource;
Enter fullscreen mode Exit fullscreen mode

2. Integration into the AppModule

Subsequently, in the file app.module.ts, I imported the data source options and incorporated them into the module's configuration:

// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRoot(dataSourceOptions),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {
  constructor() {}
}
Enter fullscreen mode Exit fullscreen mode

3. Configuration of Scripts in the package.json

Finally, to facilitate the execution of migrations, I added new scripts to the package.json file:

{
  "scripts": {
    "typeorm": "pnpm run build && npx typeorm -d dist/db/typeorm.js",
    "migration:run": "pnpm run typeorm migration:run -- -d dist/db/typeorm.js",
    "migration:generate": "pnpm run typeorm migration:generate",
    "migration:revert": "pnpm run typeorm -- -d ./src/db/typeorm.ts migration:revert"
  }
}
Enter fullscreen mode Exit fullscreen mode

Following these steps, I managed to overcome the issues associated with migrations in NestJS with TypeORM, ensuring a more robust and secure management of the database, especially in production environments. I hope this guide proves helpful in your experience with NestJS and TypeORM.

Top comments (0)