Skip to content

Sequelize migrations in production

Run sequelize-cli migrations against a live production database with rollback safety, multi-environment configs, and the seed/migration separation that matters.

Sequelize has two ways to evolve a schema: sequelize.sync() which auto-applies model definitions to the database (forbidden in production), and sequelize-cli migrations which run hand-authored migration files via the Umzug runner. The latter is what production uses. This walks through the production workflow — config files vs JS config, the db:migrate and db:migrate:undo commands, the seed/migration separation, and the operational details that matter when the database is real.

How to verify

Inspect what Sequelize thinks is the applied state:

npx sequelize-cli db:migrate:status --env production
psql $DATABASE_URL -c "SELECT * FROM \"SequelizeMeta\" ORDER BY name DESC LIMIT 5;"
ls migrations/ | tail -5
grep -r "sequelize\.sync\b" src/  # must return nothing for production
cat .sequelizerc                          # confirms migrations + config paths

If sequelize.sync() appears in any code path that runs at boot in production, fix it first. It will drop or alter columns based on the in-memory model.

What’s happening

sequelize-cli reads a config file (by default config/config.json, override with .sequelizerc) that points to the migrations directory and the database. It tracks applied migrations in a SequelizeMeta table containing a name column with the migration filename. db:migrate runs every .js file in migrations/ whose name is not in SequelizeMeta, in lexical order (timestamps prefix the filenames). Each file exports up() and down() functions; both take (queryInterface, Sequelize) and the implementation is up to you.

Seeds are separate: seeders/ and db:seed. Seeds are for non-schema data — reference tables, fixtures, default admin accounts. Seeds use their own tracking table (SequelizeData) and the convention is that they are idempotent and re-runnable. Mixing data setup into migrations is a common mistake; migrations should be schema-only with maybe a one-shot backfill, never recurring fixtures.

The procedure

  1. Replace config.json with a .js config so it reads from environment variables — JSON cannot reference process.env:

    // config/config.js
    require('dotenv').config();
    module.exports = {
      development: { url: process.env.DEV_DATABASE_URL, dialect: 'postgres', logging: console.log },
      test:        { url: process.env.TEST_DATABASE_URL, dialect: 'postgres', logging: false },
      production:  {
        url: process.env.DATABASE_URL,
        dialect: 'postgres',
        logging: false,
        dialectOptions: { ssl: { rejectUnauthorized: true, ca: process.env.DB_CA_CERT } },
      },
    };
    // .sequelizerc
    const path = require('path');
    module.exports = {
      'config':         path.resolve('config', 'config.js'),
      'models-path':    path.resolve('src', 'models'),
      'migrations-path':path.resolve('migrations'),
      'seeders-path':   path.resolve('seeders'),
    };
  2. Generate a migration by hand (the auto-generation from models is buggy; write SQL or queryInterface calls yourself):

    npx sequelize-cli migration:generate --name add-user-email
    'use strict';
    module.exports = {
      async up(queryInterface, Sequelize) {
        await queryInterface.addColumn('Users', 'email', { type: Sequelize.STRING, allowNull: true });
        await queryInterface.sequelize.query(
          `UPDATE "Users" SET "email" = lower("username") || '@example.com' WHERE "email" IS NULL`
        );
        await queryInterface.changeColumn('Users', 'email', { type: Sequelize.STRING, allowNull: false });
        await queryInterface.addIndex('Users', ['email'], { unique: true });
      },
      async down(queryInterface) {
        await queryInterface.removeColumn('Users', 'email');
      },
    };
  3. In a deploy pipeline, run migrate before the new app version takes traffic:

    - name: Apply migrations
      run: NODE_ENV=production npx sequelize-cli db:migrate
    - name: Health check
      run: curl --fail https://staging.example.com/health
    - name: Switch upstream
      run: ./bin/flip.sh
  4. To roll back, db:migrate:undo reverses the most recent migration. To undo a specific one, pass --name:

    NODE_ENV=production npx sequelize-cli db:migrate:undo
    NODE_ENV=production npx sequelize-cli db:migrate:undo --name 20260602120000-add-user-email.js
  5. For programmatic control (e.g., running migrations from inside the app instead of the CLI), use Umzug directly. This is useful in containers where bundling the CLI is overhead:

    import { Umzug, SequelizeStorage } from 'umzug';
    import { sequelize } from './db';
    
    const umzug = new Umzug({
      migrations: { glob: 'migrations/*.js' },
      context: sequelize.getQueryInterface(),
      storage: new SequelizeStorage({ sequelize }),
      logger: console,
    });
    await umzug.up();

Common pitfalls

  • sequelize.sync() and sequelize.sync({ alter: true }) are easy to leave in scaffolds and npm start scripts. They drop columns silently and have no rollback. Search the entire repo before going to production.
  • Postgres DDL is transactional but MySQL is not. A multi-statement migration on MySQL that fails midway leaves the schema partially applied. Split into single-statement migrations or write idempotent SQL.
  • The seeders/ directory is for reference data, not schema. Putting addColumn in a seeder bypasses the migration tracking and breaks the rollback story.
  • db:migrate runs every migration in migrations/. If you copy a migration file with the same filename in another branch and merge both, you get a duplicate apply (Sequelize tracks by name) and the second run fails noisily — which is right, but cleanup is manual.
  • The CLI uses Babel by default in some versions, which mangles ES modules. If migrations use ESM, prefer the Umzug programmatic approach.

For the same problem in Prisma or TypeORM, see Prisma migrations production and TypeORM migrations production. In the engagements Stack Harbor runs, every Sequelize migration is reviewed for backward compatibility before merge, sync() is removed from boot paths, and the migrate step is part of managed operations — broken migrations are caught against a production snapshot, not in the live database.