Techtrekking

How to manage model or database changes with Prisma for Next.js application

By Pravin

When you make changes to your Prisma schema after the initial migration, you have a few options depending on your environment and needs:

Development Environment

Option 1: Create a New Migration (Recommended)

npx prisma migrate dev --name describe_your_change

Examples:

# Added a new field npx prisma migrate dev --name add_user_phone_field # Added a new model npx prisma migrate dev --name add_comment_model # Changed relationship npx prisma migrate dev --name update_user_post_relation

This command will:

  1. Create a new migration file in prisma/migrations/
  2. Apply the migration to your database
  3. Regenerate Prisma Client automatically

Option 2: Prototype Without Migrations

npx prisma db push

Use this when you're rapidly prototyping and don't want to create migration files yet. It:

  • Pushes schema changes directly to the database
  • Doesn't create migration files
  • Regenerates Prisma Client
  • Warning: Can cause data loss in some scenarios

Production Environment

Apply Migrations

npx prisma migrate deploy

This command:

  • Applies all pending migrations
  • Should be run during your deployment process
  • Never use migrate dev in production

Common Workflow Example

Let's say you want to add a phone field to your User model:

1. Update your schema:

model User { id Int @id @default(autoincrement()) email String @unique name String? phone String? // New field added createdAt DateTime @default(now()) posts Post[] }

2. Create and apply migration (development):

npx prisma migrate dev --name add_user_phone

3. Commit the migration files:

git add prisma/migrations/ git commit -m "Add phone field to User model"

4. Deploy to production:

# On your production server git pull npx prisma migrate deploy npm run build pm2 restart myapp

Additional Useful Commands

Reset Database (Development Only!)

npx prisma migrate reset

This will:

  • Drop the database
  • Create a new database
  • Apply all migrations
  • Run seed scripts (if configured)

Check Migration Status

npx prisma migrate status

Generate Prisma Client Only

npx prisma generate

Run this if you only need to regenerate the client without touching the database.

View Database in Browser

npx prisma studio

for running existing database

npx prisma db pull

Best Practices

  1. Always use descriptive migration names - makes it easier to track changes
  2. Review migration files before applying - check prisma/migrations/[timestamp]_[name]/migration.sql
  3. Never edit applied migrations - create new ones instead
  4. Test migrations on staging before production
  5. Backup your database before applying migrations in production

The key difference: use migrate dev in development to create new migrations, and migrate deploy in production to apply them.

Comments
No comments yet. Be the first to comment!
Leave a Comment
Your comment will be visible after approval.