0
0
RemixHow-ToBeginner ยท 3 min read

How to Run Database Migrations in Remix Framework

In Remix, you run migrations by using your chosen database tool like Prisma migrate or knex migrate from the command line. Typically, you run npx prisma migrate dev or knex migrate:latest to apply schema changes before starting your Remix app.
๐Ÿ“

Syntax

Running migrations in Remix depends on the migration tool you use. Here are common commands:

  • Prisma: npx prisma migrate dev applies migrations during development.
  • Knex: knex migrate:latest runs all pending migrations.

These commands update your database schema to match your code.

bash
npx prisma migrate dev

# or for Knex
knex migrate:latest
๐Ÿ’ป

Example

This example shows how to run a Prisma migration in a Remix project. First, define your schema in prisma/schema.prisma. Then run the migration command to update your database.

prisma
/* prisma/schema.prisma */

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

// Run migration command in terminal
npx prisma migrate dev --name init

// After migration, start Remix app
npm run dev
Output
โœ” Generated Prisma Client (version x.x.x) to ./node_modules/@prisma/client in 123ms โœ” Migrate database Your database is now in sync with your schema.
โš ๏ธ

Common Pitfalls

Common mistakes when running migrations in Remix include:

  • Not running migrations before starting the app, causing schema mismatches.
  • Forgetting to generate the Prisma client after migration (npx prisma generate).
  • Running migrations in production without backups or testing.
  • Using legacy migration commands instead of the latest recommended ones.
bash
/* Wrong way: Starting app without migration */
npm run dev

/* Right way: Run migration first */
npx prisma migrate dev
npm run dev
๐Ÿ“Š

Quick Reference

CommandPurpose
npx prisma migrate devApply migrations and update database during development
npx prisma migrate deployApply migrations in production environments
knex migrate:latestRun all pending migrations with Knex
npx prisma generateGenerate Prisma client after schema changes
โœ…

Key Takeaways

Always run your migration command before starting your Remix app to keep the database schema in sync.
Use npx prisma migrate dev for development and npx prisma migrate deploy for production.
Remember to generate your Prisma client after migrations with npx prisma generate.
Test migrations in a safe environment before applying them to production.
Choose a migration tool like Prisma or Knex that fits your project and follow its latest commands.