Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
migrate
✓ import { migrate } from 'node-pg-migrate';
✗ const migrate = require('node-pg-migrate');
The primary programmatic interface for running migrations. Modern Node.js projects should use ESM imports. CJS `require` might work for older versions or specific setups but is not the recommended pattern for current releases shipping ESM types.
PgLiteral
✓ import { PgLiteral } from 'node-pg-migrate';
✗ import type { PgLiteral } from 'node-pg-migrate';
Used to represent a literal PostgreSQL string that should not be quoted (e.g., `pgm.func('CURRENT_TIMESTAMP')`). It's a value, not just a type.
MigrationBuilder
✓ import type { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';
✗ import { MigrationBuilder } from 'node-pg-migrate';
Core types for defining migration logic. `MigrationBuilder` provides methods for schema manipulation, and `ColumnDefinitions` for shorthand column definitions. These are types, not runtime values.
This quickstart demonstrates how to programmatically run `node-pg-migrate` to apply all pending database migrations using a `pg.Pool` instance and environment variables for connection.
import { migrate } from 'node-pg-migrate';
import { Pool } from 'pg';
import path from 'path';
import 'dotenv/config'; // Make sure to install dotenv if you use it
// --- IMPORTANT: Ensure DATABASE_URL is set in your .env file or environment variables ---
// Example: DATABASE_URL=postgres://user:password@localhost:5432/testdb
async function runDatabaseMigrations() {
const databaseUrl = process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/testdb';
if (!databaseUrl) {
console.error('DATABASE_URL environment variable is not set. Please provide it.');
process.exit(1);
}
const pool = new Pool({
connectionString: databaseUrl,
});
const migrationsDir = path.resolve(__dirname, 'migrations');
try {
console.log('Starting database migrations...');
await migrate({
db: pool, // Pass the pg.Pool instance
migrationsTable: 'pgmigrations', // Table to track applied migrations
dir: migrationsDir, // Directory containing your migration files
direction: 'up', // 'up' to apply, 'down' to revert
count: Infinity, // Apply all pending migrations
createShorthands: true, // Automatically create shorthand definitions
// verbose: true, // Uncomment for detailed logging
log: (message: string) => console.log(`[node-pg-migrate] ${message}`),
noLock: false, // Use advisory locks to prevent concurrent migrations
dryRun: false // Set to true to preview changes without applying
});
console.log('Database migrations completed successfully.');
} catch (error) {
console.error('Database migration failed:', error);
process.exit(1);
} finally {
await pool.end();
}
}
runDatabaseMigrations();
// To run this:
// 1. npm install node-pg-migrate pg dotenv
// 2. Create a 'migrations' directory.
// 3. Create a migration file, e.g., 'migrations/001_initial_schema.ts':
// import type { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';
// export async function up(pgm: MigrationBuilder): Promise<void> {
// pgm.createTable('users', { id: 'id', name: { type: 'varchar(100)', notNull: true } });
// }
// export async function down(pgm: MigrationBuilder): Promise<void> {
// pgm.dropTable('users');
// }
// 4. Configure DATABASE_URL in a .env file.
// 5. Run with `npx ts-node your-migration-script.ts` (assuming ts-node is installed)
pg-migrate --version
Errors
Common errors & fixes
Error: Cannot find module 'node-pg-migrate'
The 'node-pg-migrate' package is not installed or not accessible in the current project environment.
fixRun `npm install node-pg-migrate pg` or `yarn add node-pg-migrate pg` to install the package and its peer dependency.
Error: connect ECONNREFUSED
The PostgreSQL database server is either not running, or the connection string/details (host, port, credentials) are incorrect.
fixVerify that your PostgreSQL server is operational and accessible. Double-check your `DATABASE_URL` environment variable or connection configuration for accuracy, including host, port, username, and password.
ReferenceError: require is not defined in ES module scope
You are attempting to use CommonJS `require()` syntax in an ES module (`.mjs` or `"type": "module"` in `package.json`) for a package that is primarily designed for ESM or ships ESM types.
fixRefactor your imports to use ES module syntax (e.g., `import { migrate } from 'node-pg-migrate';`). If using TypeScript, ensure your `tsconfig.json` `module` and `moduleResolution` settings are appropriate for ESM. TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ...
Node.js cannot directly execute TypeScript migration files (`.ts`) without a transpiler or loader in place (e.g., `ts-node`, `tsx`).
fixUse a runtime TypeScript executor like `ts-node` (`npx ts-node your-script.ts`) or `tsx` (`npx tsx your-script.ts`). Alternatively, compile your TypeScript migration files to JavaScript before running.
Audit
Dependencies
pgrequiredRequired for database connection and query execution. This is a peer dependency.
@types/pgoptionalTypeScript type definitions for the 'pg' client. Highly recommended for TypeScript projects.