What is an Nx database migration target, and who should use one?

An Nx database migration target is a named target, such as migrate or migrate-deploy, defined in a service's own project configuration. It applies the migration files stored inside that service's folder. For a Prisma-based service, those files sit in prisma/migrations next to the schema. For a Flyway-based service, they are versioned SQL files in a directory like db/migrations under the same project root. Either way, the migrations belong to the project that owns the schema, and Nx runs them like any other target.

Placing migrations there has three practical effects:

  • Ownership. If you use a CODEOWNERS file, the rule covering apps/billing/ also covers billing's migrations. The team that owns the schema reviews every change to it.
  • Code review. A schema change and the application code that depends on it arrive in the same pull request. Reviewers can check that the column exists before the query that uses it ships.
  • Dependency graph. Nx treats a new migration file as a change to that project, so nx affected and the project graph see schema changes the same way they see code changes.

The usual alternative is a root-level scripts/migrate.sh or a CI step that loops over hard-coded paths. That setup works until a new service is added and nobody updates the loop. It also hides which team owns each migration.

This pattern is for backend and platform teams running several services in one Nx monorepo, where each service has its own schema, or its own database, and its own migration history.

+-- Nx monorepo ---------------------------------------------------+
|                                                                  |
| CODEOWNERS: apps/billing/ -> billing team                        |
|             apps/orders/  -> orders team                         |
|                                                                  |
| +-- apps/billing/ (Prisma) ---+  +-- apps/orders/ (Flyway) ----+ |
| | src/                        |  | src/                        | |
| | prisma/schema.prisma        |  | db/migrations/V1__init.sql  | |
| | prisma/migrations/          |  | db/migrations/V2__*.sql     | |
| | project.json                |  | project.json                | |
| |   target: migrate-deploy    |  |   target: migrate           | |
| +--------------+--------------+  +--------------+--------------+ |
|                |                                |                |
+----------------+--------------------------------+----------------+
                 |                                |
                 | nx run billing:migrate-deploy  | nx run orders:migrate
                 | (prisma migrate deploy)        | (flyway migrate)
                 |                                |
                 v                                v
        +-----------------+              +-----------------+
        |   billing DB    |              |   orders DB     |
        |   own history   |              |   own history   |
        +-----------------+              +-----------------+

 A new file under apps/billing/prisma/migrations/ makes billing affected;
 orders is untouched, and the billing CODEOWNERS rule covers the review.

Each service keeps its migrations and its migration target inside its own project folder, so CODEOWNERS, pull request review and nx affected all resolve to the service that owns the schema.

How do you define Prisma and Flyway migrate targets with nx:run-commands?

…migration history lives next to its code. Each service gets its own targets in its project.json, all using the nx:run-commands executor.

Prisma

Define one migrate target whose default options run prisma migrate deploy --schema=prisma/schema.prisma, with cwd set to the service root (for example apps/orders-api). Setting cwd matters because Prisma resolves the schema path and any .env file relative to where it runs. Add a development configuration that overrides the command with prisma migrate dev. Use it only on a laptop or a throwaway database. migrate dev can prompt interactively, generate a new migration from schema drift, and offer to reset the database when it detects drift. Those behaviours are useful locally and destructive anywhere else. The staging and production configurations keep migrate deploy, which only applies committed migrations.

Flyway

Give Flyway three targets: migrate, validate, and info. Each passes -configFiles= pointing at the service's own Flyway config, with cwd set to the service directory so relative migration locations resolve correctly. With separate targets, CI can run validate and info without permission to change anything.

Configurations and credentials

Use configurations only to select behaviour, never to embed connection strings. Prisma reads DATABASE_URL from the environment, and Flyway reads FLYWAY_URL, FLYWAY_USER and FLYWAY_PASSWORD, so CI injects these per environment. Name configurations carefully, and never make development the defaultConfiguration. If a configuration is misnamed or set as the default by mistake, nx run orders-api:migrate with no explicit configuration could run migrate dev against whatever database the environment points to.

{
  "name": "orders-api",
  "targets": {
    "migrate": {
      "executor": "nx:run-commands",
      "options": {
        "command": "npx prisma migrate deploy --schema=prisma/schema.prisma",
        "cwd": "apps/orders-api"
      },
      "configurations": {
        "development": {
          "command": "npx prisma migrate dev --schema=prisma/schema.prisma"
        },
        "staging": {
          "command": "npx prisma migrate deploy --schema=prisma/schema.prisma"
        },
        "production": {
          "command": "npx prisma migrate deploy --schema=prisma/schema.prisma"
        }
      }
    }
  }
}

An orders-api project.json where the migrate target defaults to prisma migrate deploy, only the development configuration runs migrate dev, no defaultConfiguration is set, and DATABASE_URL comes from the environment.

Which migration targets are safe to cache, and which must never be?

The fix for that misconfiguration risk starts with separating targets by what they touch. Some targets read only files in the repo. Others change a live database. Nx cannot tell them apart, so you have to say which is which with the cache setting.

Target Depends on Cache?
prisma-generate schema.prisma Yes
prisma-validate schema.prisma Yes
SQL lint / naming check Migration files Yes
flyway validate Files and the schema history table No
migrate / migrate deploy Files and live database state No

Note that flyway validate belongs in the uncached group. It compares local scripts against the history table in the target database, so its result depends on more than files.

Caching a migrate target causes a specific, quiet failure. You run migrate against staging, Nx stores the result, and later you point the same target at a fresh production database. The inputs hash the same, so Nx replays the cached success and prints the old logs. The migration never runs. Set cache: false on every target that mutates a database. Those runs will always be slower, and you should accept that.

Keep connection strings out of cached targets. If you list DATABASE_URL as an env input, the cache key depends on a secret, and every credential rotation invalidates the cache. Nx also stores terminal output with each cache entry, and with remote caching those entries leave the machine. Any credential a cacheable target prints ends up in that stored output.

{
  "name": "orders-service",
  "root": "services/orders",
  "targets": {
    "prisma-generate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": ["{projectRoot}/prisma/schema.prisma"],
      "options": {
        "command": "prisma generate --schema=services/orders/prisma/schema.prisma"
      }
    },
    "prisma-validate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": ["{projectRoot}/prisma/schema.prisma"],
      "options": {
        "command": "prisma validate --schema=services/orders/prisma/schema.prisma"
      }
    },
    "flyway-validate": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "flyway -locations=filesystem:services/orders/db/migration validate"
      }
    },
    "migrate": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "prisma migrate deploy --schema=services/orders/prisma/schema.prisma"
      }
    }
  }
}

A project.json that caches only the file-only Prisma targets and sets cache to false on flyway validate and migrate; credentials come from DATABASE_URL and FLYWAY_URL in the environment, never from inputs or command arguments.

How should migration ordering work across services?

Ordering between migration targets should reflect real schema dependencies, not deployment habits. Add dependsOn or implicitDependencies only when one service's migrations cannot succeed without another's. Examples include two services sharing a database, a view in one schema that selects from tables in another, or a foreign data wrapper that expects a remote table to already exist. In those cases a dependsOn entry pointing at the upstream project's migrate target records a fact about the data model.

When each service owns its own database, leave the targets unordered on purpose. Nx will run them in parallel, which is what you want. Adding dependsOn "just to be safe" ties the release of one service to another's schema. This is how a distributed monolith comes back: one failed migration in billing now blocks a deploy of notifications. Once teams start relying on that coupling, it is hard to remove.

Sometimes services are logically independent but share a physical database server, and you want to avoid lock contention or connection exhaustion. Limit concurrency instead of inventing dependencies. Passing --parallel=1 to run-many or affected serializes that single invocation and changes nothing in the project graph. If only a subset of targets touch the same database, chain those targets explicitly and let the rest run in parallel.

Nx ordering is not your concurrency control. Two CI jobs or two pods can still start migrations at the same moment. The real protection comes from the tools themselves. Prisma Migrate takes a database advisory lock on supported engines. Flyway records applied versions and checksums in its schema history table and locks it during a run.

# Separate databases per service: no inter-service ordering.
# Nx runs migrate targets in parallel (default concurrency).
npx nx run-many -t migrate

# Logically independent services on one physical DB server:
# serialize this invocation only. The project graph is unchanged.
npx nx run-many -t migrate --parallel=1

# Only some services share a database: run that subset one at a
# time, then run everything else in parallel.
npx nx run-many -t migrate -p billing-api,invoicing-api --parallel=1
npx nx run-many -t migrate --exclude=billing-api,invoicing-api

# A genuine schema dependency (e.g. reporting-api defines views over
# orders-api tables) belongs in reporting-api's project.json instead:
#   "migrate": {
#     "dependsOn": [{ "projects": ["orders-api"], "target": "migrate" }]
#   }

# None of this stops two CI jobs racing. Prisma's advisory lock and
# Flyway's schema history table handle concurrent runs.

Running migrate targets in parallel by default, limiting concurrency with --parallel=1 for services that share a database server, and keeping dependsOn for real schema dependencies.

When should you use nx affected for migrations, and when should you run everything?

Use nx affected for the checks that only matter when something changed. On a pull request, running nx affected -t validate or a generate target limits the work to projects whose schema files, migration directories, or dependencies differ from the base commit. If a change touches only one service's Prisma schema, only that service regenerates its client and checks its migrations. The other services are skipped, which keeps feedback fast.

Do not use affected to decide what gets applied to a database. Nx computes affected projects by diffing files between --base and --head. It never connects to a database and has no idea what any environment contains. Consider a migration that merged but failed during deploy, or a deploy job that was cancelled. On the next pipeline the base commit has moved past that change, so the service no longer appears as affected, even though its migration was never applied. Tracking the last successful CI run as the base narrows this gap but does not close it. A restored snapshot, a manual rollback, or a hotfix applied by hand still leaves the database out of step with what CI believes.

For production deploys and for provisioning a fresh environment, run the deploy target for every service. This costs little, because both tools compare pending migrations against their own history and do nothing when the database is current. After the deploy, confirm the result with prisma migrate status and flyway info. Those commands report the database's actual state, which is the only reliable answer to whether every migration has been applied.

How do you wire migration targets into CI and deployment safely?

On pull requests, run only the targets that never touch a shared database: validate and generate for each affected service. A PR that breaks the Prisma schema or adds a Flyway script with a bad name fails there, before anyone tries it against staging.

Treat deploy-style migrations (prisma migrate deploy, flyway migrate) as their own pipeline step that runs before the new service version rolls out. If that step exits non-zero, the deployment must stop. Do not let the rollout continue on a "best effort" basis. Code that expects a column that doesn't exist fails at request time, which is harder to diagnose than a failed pipeline step.

Running migrations first only works if the schema stays compatible with the code that is already running. Use expand-then-contract:

  1. Add nullable columns or new tables.
  2. Ship code that writes to both the old and new shapes.
  3. Drop the old shape in a later release.

Old instances keep serving traffic during the rollout because nothing they depend on has disappeared.

The common workflow has no automatic down migrations. Prisma doesn't generate them, and Flyway's migrate only moves forward. Plan rollback as a forward fix: write a new migration that corrects the problem. Keep each change small enough that writing that fix is quick.

Decide where migrations run:

  • From CI runners. This is simple, but the runner needs network access to production databases and credentials with DDL rights. That widens the blast radius of any leaked CI secret.
  • Inside the deploy environment. Running migrations as a job in the same network as the service keeps credentials there. The cost is more plumbing to surface logs and exit codes back to the pipeline.

When should you avoid this approach, and what are the alternatives?

The pattern pays off only when several services share one repository and one pipeline. Skip it in these cases:

  • There is one service. A package script that calls prisma migrate deploy or flyway migrate gives the same result without a project graph.
  • Services live in separate repositories. Nx cannot detect changes or declare ordering across repository boundaries.
  • A platform deployment tool already applies migrations. If both Nx and that tool can apply migrations, changes can be applied twice or skipped, and failures are hard to trace.
Alternative Fits when Main cost
Standalone package scripts One service, one database No ordering, no affected detection
CI-only migration job One pipeline deploys everything CI holds database credentials
Migrate at application startup Single replica, small schemas Replicas can race, and a failed migration blocks boot
Job inside the deploy environment Strict network isolation Extra plumbing for logs and exit codes

Using both Prisma and Flyway in one repository has a real cost. Prisma generates SQL from schema diffs, while Flyway applies versioned SQL files you write. Each tool keeps its own history table. Baselining and rollback work differently in each, and engineers have to learn both.

The approach also makes development heavier. Every service needs a database reachable on each laptop, and running all migrations across the repository is slow.

Illustrative estimate. Assume 8 services, 40 PRs a week, 6 minutes for a full migration check, and 1.5 affected services per PR, which brings a check down to about 1.1 minutes. That saves roughly 196 minutes of pipeline time a week. Now assume 3 engineer-days to set it up and 1 hour a week to maintain it. On those inputs, it breaks even only if that faster feedback recovers about an hour of engineer time each week.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx database migration target, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.