Performance: Database migrations
Database migrations affect the backend deployment speed and can indirectly impact frontend load times if migrations block API responses.
Jump into concepts and practice - no test required
import { migrate } from 'some-migration-lib'; // Run migrations once during deployment or startup, not per request await migrate(); export async function getServerSideProps() { return { props: {} }; }
import { migrate } from 'some-migration-lib'; export async function getServerSideProps() { await migrate(); // runs migrations on every request return { props: {} }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Run migrations on every request | N/A | N/A | Blocks frontend rendering due to slow API | [X] Bad |
| Run migrations once during deployment | N/A | N/A | Fast API responses, smooth frontend rendering | [OK] Good |
| Run large migrations synchronously in API | N/A | N/A | Blocks API response, causes slow interaction | [X] Bad |
| Run large migrations asynchronously in background | N/A | N/A | Non-blocking API, fast user interaction | [OK] Good |
What is the main purpose of database migrations in a Next.js project?
Which command is used to create and apply a new migration in a Next.js project using Prisma?
?
npx prisma migrate dev creates and applies migrations during development.npm run build builds the app, next dev runs dev server, and npx prisma generate regenerates Prisma client but does not migrate.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-isActiveisActive with default true is added to the User model.true automatically.What is wrong with this migration command usage in a Next.js project?
npx prisma migrate dev --name
--name flag requires a migration name string after it.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?
age Int directly will fail because existing rows lack this data.age Int?), migrate, then update existing data, and finally change it to required.age Int? as optional first, migrate, then backfill data, then make it required -> Option A