0
0
NextJSframework~5 mins

Database migrations in NextJS

Choose your learning style9 modes available
Introduction

Database migrations help you change your database structure safely over time. They keep your data organized as your app grows.

When you add a new feature that needs new database tables or columns.
When you fix mistakes in your database design.
When you update your app and need to change how data is stored.
When working with a team to keep everyone's database the same.
When deploying your app to a new environment or server.
Syntax
NextJS
npx prisma migrate dev --name descriptive_migration_name
This command creates and applies a migration using Prisma in a Next.js project.
Replace 'descriptive_migration_name' with a short description of your change.
Examples
This creates a migration to add a new 'User' table to the database.
NextJS
npx prisma migrate dev --name add_user_table
This updates the 'Post' table structure with new columns or changes.
NextJS
npx prisma migrate dev --name update_post_schema
This applies all pending migrations in a production environment.
NextJS
npx prisma migrate deploy
Sample Program

This example shows how to add a new 'User' model to your Prisma schema and create a migration to update the database.

NextJS
/*
1. Define your database schema in prisma/schema.prisma:

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

2. Run migration command in terminal:
npx prisma migrate dev --name add_user_model

3. This creates migration files and updates your database.
*/
OutputSuccess
Important Notes

Always give your migration a clear, simple name describing the change.

Run migrations in development before deploying to production.

Use version control to keep track of migration files with your code.

Summary

Database migrations safely update your database structure as your app changes.

Use migration commands like npx prisma migrate dev in Next.js projects.

Keep migration files organized and named clearly for easy teamwork and deployment.