Overview
Migration providers supply migrations to theMigrator class. Kysely provides a built-in FileMigrationProvider for Node.js that reads migrations from a folder, but you can implement custom providers for other use cases.
MigrationProvider Interface
The base interface that all migration providers must implement.getMigrations()
Example Implementation
FileMigrationProvider
Reads all migrations from a folder in Node.js. This provider automatically imports migration files with the following extensions:.js.ts(excluding.d.ts).mjs.mts(excluding.d.mts)
Constructor
Configuration
FileMigrationProviderProps
A file system implementation. In Node.js, use
promises as fs from the node:fs module.The object must have a readdir(path: string): Promise<string[]> method.A path utility implementation. In Node.js, use the
path module.The object must have a join(...path: string[]): string method.The absolute or relative path to the folder containing migration files.
Example
Complete Example with Migrator
Migration File Format
Migration files should export aMigration object with up and optionally down methods:
How It Works
- File Discovery: The provider reads all files from the specified
migrationFolder - File Filtering: Only files with valid extensions (
.js,.ts,.mjs,.mts) are processed - Dynamic Import: Each file is dynamically imported using
import() - Migration Extraction: The provider handles both default exports and named exports
- Key Generation: Migration keys are derived from filenames (without extension)
Naming Conventions
Migration files should follow a naming convention that ensures proper ordering:001_initial_schema.ts002_add_users_table.ts003_add_posts_table.ts2024_01_15_create_comments.ts
Helper Types
FileMigrationProviderFS
Interface for the file system dependency.FileMigrationProviderPath
Interface for the path utility dependency.Custom Migration Providers
You can create custom migration providers for different storage mechanisms (databases, remote APIs, etc.):Best Practices
- Consistent Naming: Use a consistent naming scheme for migration files (e.g., timestamp prefix)
- One Change Per Migration: Keep migrations focused on a single logical change
- Provide Down Methods: Always implement
down()methods when possible for rollback capability - Test Migrations: Test both
up()anddown()methods before deploying - Idempotent Operations: Make migrations safe to retry (use
IF NOT EXISTS, etc.) - Version Control: Always commit migration files to version control