How to Run Database Migrations in Next.js Projects
To run migrations in
Next.js, use a database migration tool like Prisma Migrate or Knex. Define your schema changes in migration files, then run commands like npx prisma migrate dev or knex migrate:latest to apply them to your database.Syntax
Running migrations in Next.js depends on the migration tool you use. For Prisma, the common command is:
npx prisma migrate dev: Applies pending migrations and updates your database during development.npx prisma migrate deploy: Applies migrations in production environments.
For Knex, the commands are:
knex migrate:make <migration_name>: Creates a new migration file.knex migrate:latest: Runs all pending migrations.
Each migration file contains instructions to change the database schema safely.
bash
npx prisma migrate dev knex migrate:latest
Example
This example shows how to run a migration using Prisma in a Next.js project. First, define your schema in prisma/schema.prisma. Then create and apply a migration:
bash
/* prisma/schema.prisma */ model User { id Int @id @default(autoincrement()) name String email String @unique } // Run migration commands in terminal: // 1. Create migration and apply it npx prisma migrate dev --name init // 2. Generate Prisma client npx prisma generate
Output
ā Created migration file
ā Applied migration to database
ā Generated Prisma Client
Common Pitfalls
Common mistakes when running migrations in Next.js include:
- Not running
prisma generateafter migrations, causing outdated client errors. - Running migrations directly in production without testing, risking data loss.
- Forgetting to commit migration files to version control, causing team conflicts.
- Using different database URLs in development and production without proper environment setup.
Always test migrations locally and back up your database before applying in production.
bash
/* Wrong: skipping prisma generate */ npx prisma migrate dev --name add_field // Forgetting this step causes client errors /* Right: run generate after migration */ npx prisma migrate dev --name add_field npx prisma generate
Quick Reference
| Command | Description | When to Use |
|---|---|---|
| npx prisma migrate dev | Apply migrations and update database in development | During development |
| npx prisma migrate deploy | Apply migrations in production | Before deploying to production |
| knex migrate:make | Create a new migration file | When adding schema changes |
| knex migrate:latest | Run all pending migrations | To update database schema |
Key Takeaways
Use a migration tool like Prisma or Knex to manage database schema changes in Next.js.
Run migration commands in your terminal to apply schema updates safely.
Always generate or update your database client after migrations.
Test migrations locally before applying them in production.
Keep migration files under version control to avoid conflicts.