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 devapplies migrations during development. - Knex:
knex migrate:latestruns all pending migrations.
These commands update your database schema to match your code.
bash
npx prisma migrate dev
# or for Knex
knex migrate:latestExample
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
| Command | Purpose |
|---|---|
| npx prisma migrate dev | Apply migrations and update database during development |
| npx prisma migrate deploy | Apply migrations in production environments |
| knex migrate:latest | Run all pending migrations with Knex |
| npx prisma generate | Generate 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.