I created a small NestJS project with typeorm and mysql

Store the ormconfig in separate file and create a datasource using the orm config

src/db/ormconfig.ts

import { DataSourceOptions, DataSource } from 'typeorm';

export const dataSourceOptions: DataSourceOptions = {
  type: (process.env.TYPE as any) ?? 'mysql',
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT, 10) ?? 3306,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  synchronize: false,
  bigNumberStrings: true,
  multipleStatements: true,
  logging: true,
  entities: ['**/*.entity{ .ts,.js}'],
  migrations: ['dist/db/migrations/*{.ts,.js}'],
  migrationsRun: true,
};

const dataSource = new DataSource(dataSourceOptions);

export default dataSource;


Import the created data source in your app src/app.module.ts

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { dataSourceOptions } from "./db/ormconfig";

@Module({
  imports: [TypeOrmModule.forRoot(dataSourceOptions)], // data source used here
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Add scripts in package.json to generate migrations package.json

{
  // deps and dev deps
  "scripts": {
    // other package json scripts
    "typeorm": "npm run build && npx typeorm -d dist/db/ormconfig.js",
    "migration:generate": "npm run typeorm -- migration:generate",
    "migration:run": "npm run typeorm -- migration:run",
    "migration:revert": "npm run typeorm -- migration:revert"
  }
}

Now, all you have to do is consume your scripts to generate migrations. Since we are creating a build to create and run the migrations, your app may not have the context of .env variables. I usually follow these steps for creating a migration

Step 1:

  • Create a shell file app-env.sh and add all the .env variables with value

app-env.sh

export NODE_ENV=development
export HOST=0.0.0.0
export PORT=3000
# your other environment variables here

  • Populate the environment variables to your shell
source app-env.sh

Step 2: Generate migrations by using the following command

npm run migration:generate -- ./src/db/migrations/YourMigrationNameHere

Step 3: Run the migrations with the following command

npm run migration:run

Step 4 (Optional): If you wanted to revert the applied migration

npm run migration:revert

Please note that unless you close your terminal and start a new terminal, any change in .env will not reflect in the app (since we sourced app-env.sh)

Answer from Sathya on Stack Overflow
🌐
DEV Community
dev.to › dedawit › a-practical-guide-to-database-migrations-in-nestjs-typeorm-jc7
A Practical Guide to Database Migrations in NestJS (TypeORM) - DEV Community
January 13, 2026 - Before generating migrations, set synchronize to false to prevent TypeORM from automatically applying schema changes. Let us add a new username field to User entity: ... import { MigrationInterface, QueryRunner } from 'typeorm'; export class UsernameFieldAddition1768070224042 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `ALTER TABLE "user" ADD "username" character varying NOT NULL`, ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `ALTER TABLE "user" DROP COLUMN "username"`, ); } }
🌐
Peturgeorgievv
peturgeorgievv.com › blog › typeorm-migrations-explained-example-with-nestjs-and-postgresql
TypeORM Migrations Explained - Example with NestJS and PostgreSQL
July 25, 2024 - It's critical to get used to generating, reverting, and writing additional logic in your migrations. This will help you have confidence when going into production. But the "why" is that you will have unknown issues and data loss if you opt out of them. This should be enough of an issue for you to get better at dealing with them. In the end, I'll share a way that I like to handle them while working in a team. ... The first step will be to add these lines to our scripts in package.json. "typeorm:generate": "npx typeorm-ts-node-esm migration:generate -d src/config/migrations-local.config.ts", "ty
Discussions

node.js - How to configure TypeOrm and migrations in NestJs? - Stack Overflow
I've just started a new project with NestJS. I'm just starting to learn. I'd like to implement a migration system. Can you tell me the steps to follow? I'd like to run this command : yarn migration:create "NameOfTheMigration" So that the migration file is created here: database/migrations/NameOfTheMigration · But I can't configure all this. ... Copyimport { TypeOrmModuleOptions ... More on stackoverflow.com
🌐 stackoverflow.com
How I do migrations with TypeORM using DatabaseModule with customs providers?
Also, if you are going to use migrations, I recommend you to let synchronize: false in the data source configs. As any change to the database will be instantly applied if its set to true, once the server runs and you will lose control of those changes, wich is the point of using migrations. More on reddit.com
🌐 r/nestjs
9
9
June 2, 2024
Can someone share an example for database Migrations?
Here's mine https://github.com/leosuncin/nest-api-example I define the TypeORM configuration in a separate file where I use registerAs from @nestjs/config as well as default export to be used by TypeORM CLI import { registerAs } from '@nestjs/config'; import type { TypeOrmModuleOptions } from '@nestjs/typeorm'; import invariant from 'tiny-invariant'; import { type DataSourceOptions, DataSource } from 'typeorm'; const dataSourceOptions: DataSourceOptions = { type: 'postgres', url: process.env.DATABASE_URL, synchronize: false, // entities need to be defined here in order to work with TypeORM CLI entities: [User, Article, Comment], // migrations need to be defined here in order to work with TypeORM CLI migrations: [ CreateUser1637703183543, CreateArticleComment1651517018946, ], }; export const dataSource = registerAs('data-source', () =>{ invariant(process.env.DATABASE_URL, 'DATABASE_URL is missing'); return { ...dataSourceOptions, autoLoadEntities: true, } as TypeOrmModuleOptions; }); export default new DataSource(dataSourceOptions); Then create the scripts inside the package.json "scripts": { "db:create": "ts-node -r dotenv/config -r tsconfig-paths/register node_modules/typeorm-extension/dist/cli/index.js db:create -r src/config --synchronize=no --initialDatabase=postgres", "db:drop": "ts-node -r dotenv/config -r tsconfig-paths/register node_modules/typeorm-extension/dist/cli/index.js db:drop -r src/config --initialDatabase=postgres", "db:seed": "ts-node -r dotenv/config -r tsconfig-paths/register node_modules/typeorm-extension/dist/cli/index.js seed -r src/config", "typeorm": "NODE_OPTIONS='-r dotenv/config -r tsconfig-paths/register' typeorm-ts-node-commonjs -d src/config/data-source" } More on reddit.com
🌐 r/nestjs
2
1
September 1, 2023
I used Typeorm in one of our projects and I have nothing but regrets

I'm an old SQL guy and I've tried ORMs but never found a good use case. Either the project is simple enough that an ORM isn't really needed, or it's complex enough that I'm worried about call performance and any ORM I used had terrible performance for anything beyond the simplest requests.

I guess if you're on a project in a sweet spot of "complex but performance isn't a concern", and you don't know SQL and would rather learn a short-lived node API rather than SQL, then it would make sense.

More on reddit.com
🌐 r/node
79
120
October 2, 2021
🌐
JavaScript in Plain English
javascript.plainenglish.io › nestjs-typeorm-migrations-in-2025-50214275ec8d
NestJS & TypeORM Migrations in 2025 | by Buddika Gunawardena | JavaScript in Plain English
May 27, 2025 - project root/ | | - db/ | | - migrations/ | | - datasource.ts | | - src/ | - package.json ... import { DataSource, DataSourceOptions } from 'typeorm'; import { config } from 'dotenv'; import { ConfigService } from '@nestjs/config'; config(); const configService = new ConfigService(); export const dataSourceOptions: DataSourceOptions = { // @ts-expect-error // TypeORM expects predefined strings for type type: configService.getOrThrow<string>('DB_TYPE'), host: configService.getOrThrow<string>('DB_HOST'), port: configService.getOrThrow<number>('DB_PORT'), username: configService.getOrThrow<string
🌐
Oneclickitsolution
oneclickitsolution.com › home › mobile application
Essential Guide to NestJS Migrations with TypeORM 2026
March 18, 2025 - Modifying or deleting columns, tables, or relationships in migrations without proper backup strategies or safeguards can lead to unintentional data loss ... import { BaseEntity, Column,Entity, PrimaryGeneratedColumn} from 'typeorm'; @Entity('students') export class Students extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() marks: number; }
🌐
GitHub
github.com › ambroiseRabier › typeorm-nestjs-migration-example › blob › master › README.md
typeorm-nestjs-migration-example/README.md at master · ambroiseRabier/typeorm-nestjs-migration-example
import { DynamicModule, Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import * as ormconfig from './ormconfig'; export function DatabaseOrmModule(): DynamicModule { // we could load the configuration from dotEnv here, // but typeORM cli would not be able to find the configuration file.
Author   ambroiseRabier
🌐
DEV Community
dev.to › amirfakour › using-typeorm-migration-in-nestjs-with-postgres-database-3c75
Using TypeORM Migration in NestJS with Postgres Database - DEV Community
May 3, 2023 - import { registerAs } from "@nestjs/config"; import { config as dotenvConfig } from 'dotenv'; import { DataSource, DataSourceOptions } from "typeorm"; dotenvConfig({ path: '.env' }); const config = { type: 'postgres', host: `${process.env.DATABASE_HOST}`, port: `${process.env.DATABASE_PORT}`, username: `${process.env.DATABASE_USERNAME}`, password: `${process.env.DATABASE_PASSWORD}`, database: `${process.env.DATABASE_NAME}`, entities: ["dist/**/*.entity{.ts,.js}"], migrations: ["dist/migrations/*{.ts,.js}"], autoLoadEntities: true, synchronize: false, } export default registerAs('typeorm', () => config) export const connectionSource = new DataSource(config as DataSourceOptions);
🌐
Bytes Technolab
bytestechnolab.com › blog › mastering-migration-with-typeorm-in-nestjs-step-by-step-guide
Mastering Migration with TypeORM in Nest.js (Step-by-Step Guide)
October 6, 2023 - • Here is a small example it’s altering the membership table column and adding the new column “showMyService” · • Note: Add a timestamp before the migration name as it’s easier to track which migration runs first.
Find elsewhere
Top answer
1 of 1
9

I created a small NestJS project with typeorm and mysql

Store the ormconfig in separate file and create a datasource using the orm config

src/db/ormconfig.ts

import { DataSourceOptions, DataSource } from 'typeorm';

export const dataSourceOptions: DataSourceOptions = {
  type: (process.env.TYPE as any) ?? 'mysql',
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT, 10) ?? 3306,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  synchronize: false,
  bigNumberStrings: true,
  multipleStatements: true,
  logging: true,
  entities: ['**/*.entity{ .ts,.js}'],
  migrations: ['dist/db/migrations/*{.ts,.js}'],
  migrationsRun: true,
};

const dataSource = new DataSource(dataSourceOptions);

export default dataSource;


Import the created data source in your app src/app.module.ts

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { dataSourceOptions } from "./db/ormconfig";

@Module({
  imports: [TypeOrmModule.forRoot(dataSourceOptions)], // data source used here
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Add scripts in package.json to generate migrations package.json

{
  // deps and dev deps
  "scripts": {
    // other package json scripts
    "typeorm": "npm run build && npx typeorm -d dist/db/ormconfig.js",
    "migration:generate": "npm run typeorm -- migration:generate",
    "migration:run": "npm run typeorm -- migration:run",
    "migration:revert": "npm run typeorm -- migration:revert"
  }
}

Now, all you have to do is consume your scripts to generate migrations. Since we are creating a build to create and run the migrations, your app may not have the context of .env variables. I usually follow these steps for creating a migration

Step 1:

  • Create a shell file app-env.sh and add all the .env variables with value

app-env.sh

export NODE_ENV=development
export HOST=0.0.0.0
export PORT=3000
# your other environment variables here

  • Populate the environment variables to your shell
source app-env.sh

Step 2: Generate migrations by using the following command

npm run migration:generate -- ./src/db/migrations/YourMigrationNameHere

Step 3: Run the migrations with the following command

npm run migration:run

Step 4 (Optional): If you wanted to revert the applied migration

npm run migration:revert

Please note that unless you close your terminal and start a new terminal, any change in .env will not reflect in the app (since we sourced app-env.sh)

🌐
GitHub
github.com › ambroiseRabier › typeorm-nestjs-migration-example
GitHub - ambroiseRabier/typeorm-nestjs-migration-example: "Example of how to use migrations feature of TypeORM with NestJS. · GitHub
// ... // Check typeORM documentation for more information. const config: ConnectionOptions = { type: 'postgres', host: 'localhost', port: 5432, username: 'postgres', password: 'pwd', database: 'migrationexample', entities: [__dirname + '/**/*.entity{.ts,.js}'], // We are using migrations, synchronize should be set to false.
Starred by 257 users
Forked by 30 users
Languages   TypeScript
🌐
Medium
anjith-p.medium.com › typeorm-database-migrations-in-nestjs-apps-ace923edf1bf
TypeORM database migrations in NestJS apps | by Anjith Paila | Medium
April 12, 2020 - 1.git clone https://github.com/nestjs/typescript-starter.git nestjs-typeorm-migration-demo2.cd nestjs-typeorm-migration-demo3.npm install4.npm install --save @nestjs/typeorm typeorm pg
🌐
Medium
medium.com › @ryanmambou › how-to-generate-and-run-a-migration-using-typeorm-in-nestjs-e0e078baf128
How to Generate and Run a Migration Using TypeORM in NestJS | by Ryan Mambou | Medium
February 15, 2025 - The property “entities” will help TypeORM know the path were our entities are located to generate the migrations.
🌐
LinkedIn
linkedin.com › pulse › nestjs-typeorm-migrations-nestor-iván-scoles
NestJS + TypeORM migrations
September 10, 2021 - Let’s create a folder migrations under src directory and execute the next command: npx typeorm migration:create -n UserData -d src/migrations
🌐
DEV Community
dev.to › andymwamengo › how-to-create-and-generate-migrations-in-typeorm-03-with-nestjs-9-4g55
How to create and generate migrations in Typeorm 0.3+ with NestJS 9+ - DEV Community
October 10, 2023 - import * as dotenv from 'dotenv'; dotenv.config(); import { DataSource } from 'typeorm'; export default new DataSource({ type: 'postgres', host: process.env.DATABASE_HOST, port: +process.env.DATABASE_PORT, username: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_DB, synchronize: false, dropSchema: false, logging: false, logger: 'file', entities: ['dist/**/*.entity{.ts,.js}'], migrations: ['src/migrations/**/*.ts'], subscribers: ['src/subscriber/**/*.ts'], migrationsTableName: 'migration_table', }); Add the following code to your app.module.ts
🌐
CodeBook
blog.mazedul.dev › how-to-setup-typeorm-migrations-in-a-nestjs-project
How to setup TypeORM migrations in a NestJS project
August 3, 2023 - In this article, I'll show how to setup migrations in a NestJS project using TypeORM. Buckle up and let's get started. Let's initialize our project using Nest CLI. ... Navigate to the project folder and install the necessary dependencies. In this example, I am using PostgreSQL, therefore I have added pg as a dependency.
🌐
This Dot Labs
thisdot.co › blog › setting-up-typeorm-migrations-in-an-nx-nestjs-project
Setting Up TypeORM Migrations in an Nx/NestJS Project - This Dot Labs
February 22, 2023 - For example, the previous CreatePost migration could be generated through the following command: ... TypeORM is an amazing ORM framework, but there are a few things you should be aware of when running migrations within a big TypeScript project like NestJS.
🌐
Wanago
wanago.io › home › api with nestjs #69. database migrations with typeorm
API with NestJS #69. Database migrations with TypeORM
July 25, 2022 - Interacting with the application through REPLAPI with NestJS #70. Defining dynamic modules >> ... this is super helpful – thanks so much for taking the time to put it together, i ran into a slight issue running on windows – the $npm_config_ process doesnt seem to work (at all) so i resolved by adding cross-env and then updating the npm scripts as follows ... “typeorm:generate-migration”: “npm run typeorm — -d ./typeOrm.config.ts migration:generate ./src/migrations/%npm_config_name%”,
🌐
GitHub
github.com › sramocki › nestjs-typeorm-example-migrations
GitHub - sramocki/nestjs-typeorm-example-migrations
NestJS Example repository for Postgres TypeORM integration with migrations
Starred by 27 users
Forked by 11 users
Languages   TypeScript 95.8% | JavaScript 4.2% | TypeScript 95.8% | JavaScript 4.2%
🌐
LinkedIn
linkedin.com › pulse › database-migrations-typeorm-nestjs-syed-ali-hamza-zaidi--nbzpf
Database Migrations with TypeORM in NestJS
February 27, 2024 - One critical aspect of database management is handling schema changes over time, and this is where database migrations come into play. In this article, we'll explore the process of using TypeORM for database migrations in a NestJS application. Before we dive into the example, ensure you have ...
🌐
Constantsolutions
constantsolutions.dk › 2024 › 08 › 05 › nestjs-project-with-typeorm-cli-and-automatic-migrations
NestJS with TypeORM, automatic migrations and reused CLI configuration | Constant Solutions
This file is used to configure the TypeORM CLI which you'll be using to generate and run migrations. import { ConfigModule } from '@nestjs/config'; import databaseConfig from 'src/config/database.config'; import { DataSource } from 'typeorm'; ConfigModule.forRoot({ isGlobal: true, load: ...