Bird
Raised Fist0
NextJSframework~10 mins

Database migrations in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Database migrations
Write migration file
Run migration command
Migration tool reads file
Apply schema changes to DB
Update migration history
App uses updated DB schema
This flow shows how writing and running a migration file updates the database schema step-by-step.
Execution Sample
NextJS
import { migrate } from '@nextjs/db-migrate';

await migrate('2024_06_add_users_table');
This code runs a migration named '2024_06_add_users_table' to update the database schema.
Execution Table
StepActionInputResultDB State Change
1Write migration file'2024_06_add_users_table' with SQL to create users tableMigration file createdNo change yet
2Run migration commandmigrate('2024_06_add_users_table')Migration tool startsNo change yet
3Read migration fileRead SQL commandsSQL commands loadedNo change yet
4Apply schema changesExecute SQL: CREATE TABLE users (...)Users table createdUsers table added
5Update migration historyRecord migration appliedMigration recordedMigration history updated
6Finish migrationReturn successMigration completeDB schema updated
7ExitNo more migrationsProcess endsFinal DB schema with users table
💡 All migration steps completed successfully; database schema is now updated.
Variable Tracker
VariableStartAfter Step 4After Step 5Final
migrationFileundefined'2024_06_add_users_table' content'2024_06_add_users_table' content'2024_06_add_users_table' content
dbSchemaInitial schemaUsers table addedUsers table addedUsers table added
migrationHistoryEmptyEmptyContains '2024_06_add_users_table'Contains '2024_06_add_users_table'
Key Moments - 2 Insights
Why doesn't the database schema change when I just write the migration file?
Writing the migration file only prepares the instructions. The schema changes only happen when you run the migration command, as shown in steps 2 to 4 in the execution table.
What happens if I run the migration command twice?
The migration history (step 5) prevents reapplying the same migration. The tool checks history and skips already applied migrations to avoid errors.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the users table actually created in the database?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Check the 'DB State Change' column for when the users table is added.
According to the variable tracker, what is the state of migrationHistory after step 5?
AEmpty
BContains '2024_06_add_users_table'
CUndefined
DReset to initial
💡 Hint
Look at the migrationHistory row under 'After Step 5' in variable_tracker.
If the migration file is missing, what step would fail in the execution table?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Step 3 reads the migration file; if missing, it cannot load SQL commands.
Concept Snapshot
Database migrations:
- Write migration files with schema changes
- Run migration command to apply changes
- Migration tool reads files and updates DB
- Migration history tracks applied changes
- Prevents duplicate or missing updates
Full Transcript
Database migrations in Next.js involve writing migration files that describe changes to the database schema. When you run the migration command, the tool reads these files and applies the changes to the database. It also records which migrations have been applied to avoid repeating them. This process updates the database schema safely and in order.

Practice

(1/5)
1.

What is the main purpose of database migrations in a Next.js project?

easy
A. To deploy the Next.js app to the server
B. To safely update the database structure as the app evolves
C. To create user interfaces automatically
D. To write CSS styles for the app

Solution

  1. Step 1: Understand database migrations

    Database migrations are used to change the database schema safely without losing data.
  2. Step 2: Relate to Next.js usage

    In Next.js, migrations help keep the database structure in sync with app changes.
  3. Final Answer:

    To safely update the database structure as the app evolves -> Option B
  4. Quick Check:

    Database migrations = safe schema updates [OK]
Hint: Migrations change database structure safely [OK]
Common Mistakes:
  • Confusing migrations with UI or styling tasks
  • Thinking migrations deploy the app
  • Assuming migrations create app features
2.

Which command is used to create and apply a new migration in a Next.js project using Prisma?

?
easy
A. next dev
B. npm run build
C. npx prisma migrate dev
D. npx prisma generate

Solution

  1. Step 1: Identify Prisma migration command

    The command npx prisma migrate dev creates and applies migrations during development.
  2. Step 2: Differentiate from other commands

    npm run build builds the app, next dev runs dev server, and npx prisma generate regenerates Prisma client but does not migrate.
  3. Final Answer:

    npx prisma migrate dev -> Option C
  4. Quick Check:

    Migration command = npx prisma migrate dev [OK]
Hint: Use 'npx prisma migrate dev' to create and apply migrations [OK]
Common Mistakes:
  • Using 'npm run build' to migrate database
  • Confusing 'npx prisma generate' with migration
  • Running 'next dev' expecting migration
3.

Given this Prisma schema change and migration command, what will happen?

model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  name  String?
}

// After adding a new field:
model User {
  id       Int    @id @default(autoincrement())
  email    String @unique
  name     String?
  isActive Boolean @default(true)
}

Command: npx prisma migrate dev --name add-isActive
medium
A. A new migration file is created and applied adding the isActive column with default true
B. The migration fails because isActive is missing in existing rows
C. The database schema remains unchanged
D. The app crashes due to schema mismatch

Solution

  1. Step 1: Understand schema change

    A new Boolean field isActive with default true is added to the User model.
  2. Step 2: Effect of migration command

    The command creates a migration file that adds the new column with default value, so existing rows get true automatically.
  3. Final Answer:

    A new migration file is created and applied adding the isActive column with default true -> Option A
  4. Quick Check:

    Adding field with default = migration applies safely [OK]
Hint: Adding field with default creates migration safely [OK]
Common Mistakes:
  • Thinking migration fails due to missing data for new field
  • Assuming schema does not change without manual SQL
  • Believing app crashes immediately after migration
4.

What is wrong with this migration command usage in a Next.js project?

npx prisma migrate dev --name
medium
A. The command is correct and will run successfully
B. The command should be run with npm, not npx
C. The command should be prisma migrate deploy instead
D. The migration name is missing after --name flag

Solution

  1. Step 1: Check command syntax

    The --name flag requires a migration name string after it.
  2. Step 2: Identify missing argument

    Here, no name is provided, so the command will error out.
  3. Final Answer:

    The migration name is missing after --name flag -> Option D
  4. Quick Check:

    Migration name required after --name [OK]
Hint: Always provide a name after --name flag [OK]
Common Mistakes:
  • Omitting migration name after --name
  • Confusing migrate dev with migrate deploy
  • Using npm instead of npx unnecessarily
5.

You want to add a new required field age Int to your User model in Prisma, but your database already has users without this field. What is the best way to handle this migration?

hard
A. Add age Int? as optional first, migrate, then backfill data, then make it required
B. Add age Int directly and run migration; it will succeed automatically
C. Delete all existing users before migration to avoid errors
D. Skip migration and add the field only in the app code

Solution

  1. Step 1: Understand required field constraints

    Adding a required field age Int directly will fail because existing rows lack this data.
  2. Step 2: Use a safe migration approach

    First add the field as optional (age Int?), migrate, then update existing data, and finally change it to required.
  3. Final Answer:

    Add age Int? as optional first, migrate, then backfill data, then make it required -> Option A
  4. Quick Check:

    Make new required fields optional first [OK]
Hint: Add new required fields as optional first [OK]
Common Mistakes:
  • Adding required field directly causing migration failure
  • Deleting data unnecessarily
  • Skipping migration and causing runtime errors