node-pg-migrate and postgres-migrations are both tools designed to handle database schema changes (migrations) for PostgreSQL in Node.js environments. node-pg-migrate is a comprehensive, opinionated framework that provides a rich CLI, a fluent JavaScript API for defining schema changes, and built-in support for rolling back changes. It is often used as a standalone tool or integrated into larger frameworks like NestJS. postgres-migrations, in contrast, is a lightweight, functional library that focuses strictly on executing SQL files in order. It avoids heavy abstraction, offering a simple API to run up/down scripts located in a folder, making it ideal for developers who prefer writing raw SQL and managing their own tooling.
When building Node.js applications with PostgreSQL, managing database schema changes is critical. You need a reliable way to apply updates, track versions, and revert changes when things go wrong. node-pg-migrate and postgres-migrations solve this problem but take very different approaches. One offers a full-featured framework with a fluent API, while the other provides a lightweight engine for raw SQL files. Let's dive into how they compare in real-world scenarios.
The most significant difference lies in how you write your migration logic.
node-pg-migrate encourages you to write migrations in JavaScript using a fluent builder API. This approach gives you auto-completion and helps prevent syntax errors before you run anything. You describe what you want to change, and the library generates the SQL for you.
// node-pg-migrate: Using the fluent API
exports.up = (pgm) => {
pgm.createTable('users', {
id: 'id',
email: { type: 'varchar(255)', notNull: true },
created_at: { type: 'timestamp', default: pgm.func('current_timestamp') }
});
pgm.createIndex('users', 'email');
};
exports.down = (pgm) => {
pgm.dropTable('users');
};
postgres-migrations takes a hands-off approach. It expects plain .sql files. You write standard PostgreSQL SQL, giving you 100% control over the syntax and allowing you to use database-specific features immediately without waiting for the library to support them.
-- postgres-migrations: 001-create-users.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users (email);
-- Down migration is typically in a separate file or handled by convention
-- 001-create-users.down.sql
DROP TABLE IF EXISTS users;
How you execute these migrations differs based on the tool's philosophy.
node-pg-migrate ships with a powerful Command Line Interface (CLI). You can run migrations directly from your terminal, which is great for local development and CI/CD pipelines. It handles connection strings, logging, and execution order automatically.
# node-pg-migrate: Running via CLI
npx node-pg-migrate up
# Running with a specific config file
npx node-pg-migrate up --config-file my-config.js
You can also run it programmatically if you need to embed it in a custom startup script.
// node-pg-migrate: Programmatic usage
const { runner } = require('node-pg-migrate');
await runner({
databaseUrl: 'postgres://user:pass@localhost/db',
migrationsTable: 'pgmigrations',
dir: 'migrations'
});
postgres-migrations is designed to be called from your own code. It does not provide a standalone CLI for running migrations out of the box. You write a small script (e.g., migrate.js) to invoke it. This gives you flexibility to hook into your app's lifecycle exactly how you want.
// postgres-migrations: Running via custom script
const { migrate } = require('postgres-migrations');
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgres://user:pass@localhost/db' });
async function runMigrations() {
await client.connect();
try {
await migrate({ client }, './migrations');
} finally {
await client.end();
}
}
runMigrations().catch(console.error);
Handling mistakes is a key part of migration strategies.
node-pg-migrate has built-in support for rolling back migrations. Because it tracks state in a database table and understands the structure of your JS files (which export both up and down functions), it can easily revert the last change.
# node-pg-migrate: Rolling back the last migration
npx node-pg-migrate down
# Rolling back multiple steps
npx node-pg-migrate down 3
postgres-migrations supports down migrations if you follow the naming convention (e.g., name.sql and name.down.sql). However, the responsibility to ensure the down script correctly reverses the up script lies entirely on you. The library simply executes the file it finds. It does not offer a "rollback last" CLI command by default; you would need to extend your custom script to handle specific file selection.
// postgres-migrations: Custom rollback logic required
// You must manually specify the file or logic to run down scripts
// The library itself just runs what you tell it to run.
await migrate({ client }, './migrations', { useTransaction: true });
// Note: It wraps each migration in a transaction by default for safety.
Creating new migration files manually can be tedious.
node-pg-migrate excels here with its generation CLI. It can scaffold files for tables, columns, indexes, and more, pre-filling the JavaScript template for you.
# node-pg-migrate: Generate a new migration
npx node-pg-migrate create add-login-column
# Generate a specific table creation template
npx node-pg-migrate create create-users --table
postgres-migrations does not include a generator. You must create the SQL files yourself. While this seems like extra work, many teams prefer this because it forces them to think about the exact SQL they need rather than relying on a template that might not cover edge cases.
# postgres-migrations: Manual file creation
touch migrations/002-add-login-column.sql
touch migrations/002-add-login-column.down.sql
Despite their differences, both libraries solve the core problem effectively and share some fundamental traits.
Both tools understand the importance of atomicity. They wrap migrations in database transactions by default. If a migration fails halfway through, the database reverts to its previous state, preventing corrupt schemas.
// node-pg-migrate: Automatic transactions
// (Handled internally by the runner)
// postgres-migrations: Automatic transactions
// (Enabled by default via the `useTransaction` option)
await migrate({ client }, './migrations', { useTransaction: true });
Both libraries maintain a tracking table inside your database to record which migrations have run. This prevents duplicate executions and ensures order.
-- Both create a table similar to this internally:
-- node-pg-migrate defaults to 'pgmigrations'
-- postgres-migrations defaults to 'schema_migrations' (configurable)
CREATE TABLE IF NOT EXISTS pgmigrations (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
run_on timestamp NOT NULL
);
Both work seamlessly with the standard pg (node-postgres) client. You can pass an existing client instance to either tool, making them compatible with connection pooling strategies used in production apps.
// Shared pattern: Passing a client instance
const client = new Client(config);
await client.connect();
// Works for both libraries (with slight API differences)
// node-pg-migrate runner accepts databaseUrl or client
// postgres-migrations requires client
| Feature | node-pg-migrate | postgres-migrations |
|---|---|---|
| Migration Format | JavaScript (Fluent API) | Raw SQL Files |
| CLI Included | โ Yes (Rich features) | โ No (Bring your own) |
| File Generation | โ Built-in generators | โ Manual creation |
| Rollback Ease | โ
Easy (down command) | โ ๏ธ Requires custom script logic |
| Abstraction Level | High (Builder pattern) | Low (Direct SQL) |
| Best For | Teams wanting structure & DX | Teams wanting simplicity & SQL control |
node-pg-migrate is like a fully equipped workshop ๐จ. It provides the tools to build, generate, and fix your database schema with ease. It is the right choice for teams that value Developer Experience (DX), want strong typing via TypeScript (since the API is JS-based), and prefer not to write repetitive SQL boilerplate. It shines in larger projects where consistency and automated scaffolding save time.
postgres-migrations is like a precise scalpel ๐ก๏ธ. It cuts out the fluff and lets you write exactly the SQL you need. It is perfect for developers who find ORMs and builders restrictive or who need to use advanced PostgreSQL features that haven't been wrapped by a library yet. If you are comfortable managing your own file structure and scripts, this lightweight option keeps your dependency graph clean and your SQL transparent.
Final Thought: If you want a battery-included solution that guides your team, pick node-pg-migrate. If you prefer a minimal engine that stays out of your way and trusts you to write good SQL, pick postgres-migrations.
Choose node-pg-migrate if you want a robust, all-in-one solution with a powerful CLI that can generate migration files for you. It is the best fit for teams that prefer defining schema changes using a fluent JavaScript API rather than raw SQL, as it provides type safety and auto-completion within your IDE. Select this package if you need complex rollback capabilities or if you are using a framework like NestJS that has first-party integration with it.
Choose postgres-migrations if you prefer a minimalistic approach where migrations are simply ordered SQL files. It is ideal for projects where you want full control over the SQL syntax without the overhead of a builder API or a heavy CLI. Pick this library if you want a dependency that does one thing wellโrunning scripts in sequenceโand you are comfortable writing your own scripts to generate or manage those SQL files.
Node.js database migration management built exclusively for postgres. (But can also be used for other DBs conforming to SQL standard - e.g. CockroachDB.)
| Name | GitHub |
|---|---|
| Christopher Quadflieg | @Shinigami92 |
| Breno A. | @brenoepics |
| Omar Diab | @osdiab |
| Name | Link |
|---|---|
| Theo Ephraim | @theoephraim |
| Salsita Software | salsita.ai |
If you don't already have the pg library installed, you will need to add pg as either a direct or dev dependency
npm add pg
npm add --save-dev node-pg-migrate
Installing this module adds a runnable file into your node_modules/.bin directory. If installed globally (with the -g option), you can run node-pg-migrate and if not, you can run ./node_modules/.bin/node-pg-migrate.js
Add "migrate": "node-pg-migrate" to scripts section of your package.json so you are able to quickly run commands.
Run npm run migrate create my-first-migration. It will create file xxx_my-first-migration.js in migrations folder.
Open it and change contents to:
export const up = (pgm) => {
pgm.createTable('users', {
id: 'id',
name: { type: 'varchar(1000)', notNull: true },
createdAt: {
type: 'timestamp',
notNull: true,
default: pgm.func('current_timestamp'),
},
});
pgm.createTable('posts', {
id: 'id',
userId: {
type: 'integer',
notNull: true,
references: '"users"',
onDelete: 'CASCADE',
},
body: { type: 'text', notNull: true },
createdAt: {
type: 'timestamp',
notNull: true,
default: pgm.func('current_timestamp'),
},
});
pgm.createIndex('posts', 'userId');
};
Save migration file.
Now you should put your DB connection string to DATABASE_URL environment variable and run npm run migrate up.
(e.g. DATABASE_URL=postgres://test:test@localhost:5432/test npm run migrate up)
You should now have two tables in your DB :tada:
If you want to change your schema later, you can e.g. add lead paragraph to posts:
Run npm run migrate create posts_lead, edit xxx_posts_lead.js:
export const up = (pgm) => {
pgm.addColumns('posts', {
lead: { type: 'text', notNull: true },
});
};
Run npm run migrate up and there will be a new column in posts table :tada:
Want to know more? Read docs:
Full docs are available at https://salsita.github.io/node-pg-migrate
Why only Postgres? - By writing this migration tool specifically for postgres instead of accommodating many databases, we can actually provide a full featured tool that is much simpler to use and maintain. I was tired of using crippled database tools just in case one day we switch our database.
Async / Sync - Everything is async in node, and that's great, but a migration tool should really just be a fancy wrapper that generates SQL. Most other migration tools force you to bring in control flow libraries or wrap everything in callbacks as soon as you want to do more than a single operation in a migration. Plus by building up a stack of operations, we can automatically infer down migrations (sometimes) to save even more time.
Naming / Raw Sql - Many tools force you to use their constants to do things like specify data types. Again, this tool should be a fancy wrapper that generates SQL, so whenever possible, it should just pass through user values directly to the SQL. The hard part is remembering the syntax of the specific operation, not remembering how to type "timestamp"!
๐ Welcome, new contributors!
Whether you're a seasoned developer or just getting started, your contributions are valuable to us. Don't hesitate to jump in, explore the project, and make an impact.