0
0
NextjsHow-ToBeginner Ā· 4 min read

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 generate after 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

CommandDescriptionWhen to Use
npx prisma migrate devApply migrations and update database in developmentDuring development
npx prisma migrate deployApply migrations in productionBefore deploying to production
knex migrate:make Create a new migration fileWhen adding schema changes
knex migrate:latestRun all pending migrationsTo 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.