Skip to content

TypeORM migrations in production

Generate, apply, and roll back TypeORM migrations against a production database with confidence: CLI workflow, transactions, and synchronize: false discipline.

TypeORM offers a synchronize: true option that compares entity decorators against the database and auto-applies the diff at startup. It is dangerous and forbidden in production — it drops columns based on a stale model and has no rollback. Production uses the migration CLI: migration:generate to scaffold from entity diff, migration:run to apply, migration:revert to roll back. This walks through the actual production workflow, including the DataSource configuration that supports both dev and CI/prod, and the operational details that separate a service that ships migrations from one that destroys data.

How to verify

Check what TypeORM thinks is the current state of migrations:

npx typeorm migration:show -d dist/data-source.js
psql $DATABASE_URL -c "SELECT * FROM migrations ORDER BY id DESC LIMIT 5;"
grep -r "synchronize: true" src/  # must return nothing
ls src/migrations/ | tail -5
node -e "require('./dist/data-source').AppDataSource.initialize().then(d => console.log(d.isInitialized))"

If synchronize: true appears anywhere in production code paths, fix that first. Every redeploy can drop columns under that flag.

What’s happening

TypeORM tracks applied migrations in a migrations table (configurable name). The CLI reads src/migrations/ for .ts files (or dist/migrations/*.js for compiled production), compares against the table, and runs the missing ones in transactions. Each migration file exports a class with up() and down() methods — both your responsibility to write. The CLI can generate the up() from an entity diff (migration:generate) but the diff is approximate; review it before committing.

The migration runs in a single transaction by default on Postgres (transaction: true in the config). If any statement fails, the whole migration is rolled back. MySQL does not support DDL in transactions, so a partial failure leaves the schema in a state needing manual repair — that asymmetry is worth knowing before you ship.

The procedure

  1. Set up a single DataSource that both dev and production read. It should disable synchronize and configure migrations:

    // src/data-source.ts
    import { DataSource } from 'typeorm';
    import { User } from './entity/User';
    
    export const AppDataSource = new DataSource({
      type: 'postgres',
      url: process.env.DATABASE_URL,
      entities: [User],
      migrations: [__dirname + '/migrations/*.{ts,js}'],
      synchronize: false,
      migrationsRun: false,           // never auto-run; CI does it
      migrationsTableName: 'migrations',
      logging: ['error', 'warn'],
    });
  2. Generate a migration from an entity diff. Always pass an explicit name; the CLI will use it as the class name and file name:

    npx typeorm migration:generate -d src/data-source.ts src/migrations/AddUserEmail
  3. Review the generated migration. The CLI is usually right for column additions and indexes; it often gets renames wrong (renames look like DROP+CREATE and lose data). Edit the up() / down() by hand for renames, splits, merges, and data backfills:

    import { MigrationInterface, QueryRunner } from 'typeorm';
    
    export class AddUserEmail1717362000000 implements MigrationInterface {
      public async up(qr: QueryRunner): Promise<void> {
        await qr.query(`ALTER TABLE "user" ADD COLUMN "email" varchar`);
        await qr.query(`UPDATE "user" SET "email" = lower("username") || '@example.com' WHERE "email" IS NULL`);
        await qr.query(`ALTER TABLE "user" ALTER COLUMN "email" SET NOT NULL`);
      }
      public async down(qr: QueryRunner): Promise<void> {
        await qr.query(`ALTER TABLE "user" DROP COLUMN "email"`);
      }
    }
  4. Apply in CI/prod against the compiled JavaScript output:

    npm run build
    npx typeorm migration:run -d dist/data-source.js
  5. Wire it into the deploy pipeline before the new app version takes traffic:

    - name: Apply migrations
      run: npx typeorm migration:run -d dist/data-source.js
    - name: Smoke test
      run: curl --fail https://staging.example.com/health
    - name: Switch traffic
      run: ./bin/flip-upstream.sh
  6. To roll back, run revert exactly the number of migrations you want to undo. There’s no “revert to migration X” — you revert by step count:

    npx typeorm migration:revert -d dist/data-source.js  # undo the latest
    npx typeorm migration:revert -d dist/data-source.js  # undo the next-latest

Common pitfalls

  • synchronize: true is the most-cited TypeORM footgun. Audit the DataSource construction; production must be false. A process.env.NODE_ENV === 'development' check is the usual guard.
  • The migration is generated from the current entities and the current connected database. If your dev database is stale, the diff is wrong. Always re-pull or reset dev before generating.
  • MySQL DDL is not transactional. A multi-statement migration that fails midway leaves the schema half-applied. Either split into single-statement migrations or write idempotent SQL.
  • migration:generate includes generated SQL for every entity it can see. If you forget to add an entity to the DataSource, the generator drops its table. Always read the diff.
  • TypeORM’s CLI cannot run .ts directly without ts-node. In CI/prod use the compiled .js; in dev, prefix the CLI command with ts-node or use npx tsx to avoid the build step.

For the same problem in Prisma or Sequelize, see Prisma migrations production and Sequelize migrations production. In the engagements Stack Harbor runs, generated migrations are reviewed for unintended renames and data backfills before they merge; synchronize: true is banned by a lint rule, and the migration step is part of managed operations so a broken migration is caught against a production snapshot before it touches the live database.