What are per-service Nx Prisma migration targets, and who should use them?

In this pattern, every service that owns a database also owns its Prisma schema. The orders service keeps schema.prisma and its migrations/ folder under apps/orders/prisma/, and billing does the same under apps/billing/prisma/. Each project then exposes four Nx targets that wrap the Prisma CLI and point it at that project's schema:

  • generate builds the Prisma client for this service only.
  • migrate-dev creates and applies migrations against a local database.
  • migrate-deploy applies committed migrations in shared environments.
  • migrate-status reports drift between the migrations folder and a target database.

Three things are scoped to each service, and they have to stay consistent with each other:

  • Schema. Each service's datasource reads its connection string from its own environment variable, such as ORDERS_DATABASE_URL or BILLING_DATABASE_URL. A migration run for orders cannot reach the billing database by accident.
  • Client. The generator writes its client to a per-service output path, so two services never overwrite each other's generated code.
  • Targets. The targets bind the schema and its variable together. Running nx run orders:migrate-deploy resolves to one schema, one database and one migrations history.

The pattern depends on that one-to-one mapping. With a single shared schema.prisma, every service's target would run the same migrations against the same database. You would have several names for one operation, and Nx's project graph would know nothing useful about which change affects which data.

The pattern suits two groups:

  • Backend teams running several services where each one owns a separate database or schema.
  • Platform engineers who maintain the CI pipelines that must migrate those databases independently, in order, without rebuilding everything on every commit.
   nx run orders:<target>            nx run billing:<target>
              |                                 |
              v                                 v
+-----------------------------+   +-----------------------------+
| apps/orders/  (Nx project)  |   | apps/billing/ (Nx project)  |
|                             |   |                             |
|  targets:                   |   |  targets:                   |
|   generate  migrate-dev     |   |   generate  migrate-dev     |
|   migrate-deploy            |   |   migrate-deploy            |
|   migrate-status            |   |   migrate-status            |
|          |                  |   |          |                  |
|          v                  |   |          v                  |
|  prisma/schema.prisma       |   |  prisma/schema.prisma       |
|  prisma/migrations/         |   |  prisma/migrations/         |
+------+---------------+------+   +------+---------------+------+
       |               |                 |               |
   generate        migrate-*         generate        migrate-*
       |               |                 |               |
       v               v                 v               v
+-------------+ +-------------+   +-------------+ +-------------+
| orders      | | env:        |   | billing     | | env:        |
| client      | | ORDERS_     |   | client      | | BILLING_    |
| (own output)| | DATABASE_URL|   | (own output)| | DATABASE_URL|
+-------------+ +------+------+   +-------------+ +------+------+
                       |                                 |
                       v                                 v
                +-------------+                   +-------------+
                | orders DB   |                   | billing DB  |
                +-------------+                   +-------------+

Each Nx project owns its schema.prisma and migrations folder, and its targets bind that schema to a per-service generated client and to one database, reached through its own connection-string environment variable.

How do you define Prisma migration targets in project.json?

Each service gets its own small set of nx:run-commands targets in its project.json, typically prisma-generate, migrate-dev, migrate-deploy and migrate-status. Every target calls the Prisma CLI directly and passes --schema with a path relative to the workspace root, such as apps/orders/prisma/schema.prisma. Nx runs commands from the workspace root by default. Without the explicit path, Prisma looks for a schema in its default locations and either fails or picks up the wrong one. Stating the path also makes the target safe to copy into a terminal as-is.

The schema's datasource block should read its URL from a service-specific variable, for example env("ORDERS_DATABASE_URL"), instead of the shared default DATABASE_URL. That way two services can never point at each other's database because of a leftover variable. Locally, put the value in apps/orders/.env, which Nx loads for tasks in that project. In CI, set the variable directly in the job environment and do not commit any .env file.

Give each schema's generator client block a custom output path, such as a generated folder inside the service or its data library. If every service generates into the default location, each prisma generate overwrites the previous client, and whichever service generated last wins.

Then add prisma-generate to dependsOn for build and serve. The client will always exist and match the schema before compilation starts.

Keep each target to a single command with no wrapper scripts. When a migration fails, the command Nx prints should be the one you would rerun by hand.

{
  "name": "orders",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/orders/src",
  "projectType": "application",
  "targets": {
    "prisma-generate": {
      "executor": "nx:run-commands",
      "options": { "command": "npx prisma generate --schema=apps/orders/prisma/schema.prisma" }
    },
    "migrate-dev": {
      "executor": "nx:run-commands",
      "options": { "command": "npx prisma migrate dev --schema=apps/orders/prisma/schema.prisma" }
    },
    "migrate-deploy": {
      "executor": "nx:run-commands",
      "options": { "command": "npx prisma migrate deploy --schema=apps/orders/prisma/schema.prisma" }
    },
    "migrate-status": {
      "executor": "nx:run-commands",
      "options": { "command": "npx prisma migrate status --schema=apps/orders/prisma/schema.prisma" }
    },
    "build": {
      "executor": "nx:run-commands",
      "dependsOn": ["prisma-generate"],
      "options": { "command": "npx tsc -p apps/orders/tsconfig.app.json" }
    },
    "serve": {
      "executor": "nx:run-commands",
      "dependsOn": ["prisma-generate"],
      "options": { "command": "node dist/apps/orders/main.js" }
    }
  }
}

An orders project.json with thin nx:run-commands Prisma targets that pass an explicit --schema path from the workspace root, plus build and serve that depend on prisma-generate.

When should you use migrate dev, migrate deploy and migrate status?

Each of the three commands answers a different question, so each gets its own target per service.

migrate-dev is for a developer's own database. It compares the schema against the migration history, writes a new migration folder, applies it, and regenerates the client. It also uses a shadow database to detect drift. If it finds drift or a migration it cannot apply cleanly, it can prompt you to reset the database, which drops all data. That behaviour is why it must never point at a shared staging or production database. A single accepted prompt, or a run in a non-interactive shell, can wipe data that other people depend on. It also writes files, so running it in CI would create migrations that nobody reviewed.

migrate-deploy only applies migration files that are already committed. It never generates migrations, never resets the database, and never prompts. That makes it safe to run unattended in release pipelines.

migrate-status reads the migration table and reports pending or failed migrations. It returns a non-zero exit code when the database is out of sync, so you can use it as a pre-deploy gate before application code ships.

Target Environment Side effects Interactive Cacheable
migrate-dev Local, disposable DB Writes migration files, alters schema, may reset data Yes No
migrate-deploy CI, staging, production Applies committed migrations only No No
migrate-status Pre-deploy checks None (read-only) No No

None of these targets are cacheable. Their result depends on the live state of the database, and that state is not part of the target's inputs.

How should caching and nx affected be configured for a migration target?

The one target that should be cached is prisma-generate. Its output is a deterministic function of the schema file and the installed Prisma version, so scope its inputs to the schema file rather than the whole project, and declare the generated client directory in outputs. Editing a service handler then leaves the generate cache intact. Changing a model invalidates it.

Every target that touches a live database needs cache: false, and this has to be set explicitly on each one. The common mistake is copying the prisma-generate block, cache settings included, to create migrate-deploy. The two targets have the same inputs, so the second CI run after an unchanged schema gets a cache hit. Nx replays the stored terminal output, reports success, and never connects to the database. A freshly provisioned staging database stays empty, and the pipeline still shows green. If you put migrate-deploy in targetDefaults, set caching off there as well, so a project-level override cannot turn it on by accident.

For nx affected to work, it has to see schema and migration changes. When the prisma directory sits inside the project root, the default inputs already cover it. When the schema lives elsewhere, such as a shared libs folder or a top-level prisma/ directory, add that path to the project's inputs. Otherwise, a commit that only adds a migration will not mark the service as affected, and its migration will never run.

Some situations call for skipping affected and running migrate-deploy across every service with run-many:

  • Bootstrapping a new environment
  • Restoring from a backup
  • Recovering after a failed release

In each case the database state no longer matches git history, so the git diff tells you nothing useful. Because migrate deploy skips migrations that are already applied, running it against every service is safe.

// apps/orders-service/project.json (Nx accepts comments in project.json)
{
  "name": "orders-service",
  "namedInputs": {
    // Only needed if the schema lives outside the project root,
    // e.g. a shared libs/orders-db/prisma folder
    "prismaSchema": ["{workspaceRoot}/libs/orders-db/prisma/**/*"]
  },
  "targets": {
    "prisma-generate": {
      "executor": "nx:run-commands",
      "options": {
        "command": "prisma generate --schema=libs/orders-db/prisma/schema.prisma"
      },
      // Deterministic output: cache it, keyed only on the schema file,
      // so editing a handler does not invalidate the generated client
      "cache": true,
      "inputs": ["{workspaceRoot}/libs/orders-db/prisma/schema.prisma"],
      "outputs": ["{projectRoot}/src/generated/client"]
    },
    "migrate-deploy": {
      "executor": "nx:run-commands",
      "options": {
        "command": "prisma migrate deploy --schema=libs/orders-db/prisma/schema.prisma"
      },
      // Changes a live database: never replay from cache.
      // Set this explicitly; do not copy the generate block.
      "cache": false,
      "inputs": ["default", "prismaSchema"]
    }
  }
}

// Normal CI: only services whose code, schema or migrations changed
//   npx nx affected -t migrate-deploy
// Bootstrap, restore or recovery: ignore git history, run for every service
//   npx nx run-many -t migrate-deploy

A project.json that caches prisma-generate on the schema file alone, sets cache to false on migrate-deploy, adds an external schema path to inputs, and shows when to use affected versus run-many.

How do you run Nx Prisma migrations safely in CI?

Run migrations as their own pipeline step, after build and test and before any application rollout. If the new code deploys first, it can briefly query columns that don't exist yet. A separate step also gives you one clear point to stop the pipeline: if migrations fail, nothing new ships.

When several services' databases live on the same database server, or one service's migration depends on another's, run the deploy target with --parallel=1. Nx otherwise runs independent targets concurrently. Concurrent DDL against one server competes for locks and connections, and you lose a deterministic order of changes. Sequential execution is slower but predictable.

This step couples pipeline success to database availability. A network blip or a lock timeout now fails a build that has nothing wrong with its code. Retry transient connection errors, but don't blindly retry a migration that failed partway. Prisma records it as failed, and migrate deploy will refuse to continue until you resolve it with prisma migrate resolve.

Because migrations run before rollout, the old application version must keep working against the new schema. Use expand-then-contract:

  • Expand: add the new column or table and make it nullable or give it a default.
  • Migrate the code: deploy code that writes both versions or reads the new one.
  • Contract: drop the old structure in a later release.

Prisma Migrate has no automatic down migrations. Plan for partial success up front. Keep each migration small, and decide in advance what forward-fix migration you would write if one service's migration succeeds and another's fails.

# .github/workflows/deploy.yml (excerpt)
# Assumes each service project defines a `db-migrate` Nx target that runs
# `prisma migrate deploy --schema=<that service's schema.prisma>`.
jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx nx run-many -t build test

  migrate:
    needs: build-test            # only migrate code that built and passed tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      # One service at a time: the databases share a server, so avoid
      # concurrent DDL competing for locks and keep the order deterministic.
      # No blind retry here: a migration that failed partway is recorded as
      # failed and must be handled with `prisma migrate resolve` plus a
      # forward fix, not re-run automatically.
      - run: npx nx run-many -t db-migrate --parallel=1
        env:
          ORDERS_DATABASE_URL: ${{ secrets.ORDERS_DATABASE_URL }}
          BILLING_DATABASE_URL: ${{ secrets.BILLING_DATABASE_URL }}

  deploy:
    needs: migrate               # if migrations fail, nothing new ships
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      # Old pods keep running during rollout, so the migrations above must be
      # expand-only (nullable or defaulted additions); drops come in a later release.
      - run: npx nx run-many -t deploy

A GitHub Actions pipeline that runs each service's Prisma migrations sequentially with --parallel=1 as a gated step between build/test and application rollout.

When should you avoid per-service Prisma schemas, and what are the alternatives?

Per-service schemas only make sense when the services genuinely own their data. Prisma cannot model a relation that crosses schema files, so you lose foreign keys and joins between services. If you find yourself recreating those relations by hand, or one service's migration keeps breaking another's queries, you have a shared database pretending to be separate. Splitting it into targets hides that coupling instead of removing it.

When several services share one physical database with a separate schema each, confirm that each service writes its own _prisma_migrations table and that object names cannot collide. The location of that table depends on how each connection string resolves the default schema. Verify it in a scratch database rather than assuming it. If two services end up recording history in the same table, migrate deploy can report drift or apply migrations in the wrong place.

Every schema also adds a generated client. That means more work during install and build, plus editors that offer the wrong PrismaClient import when more than one is resolvable.

Approach Fits when Main cost
One shared schema, one migration target Services are tightly coupled or share tables Every schema change affects all services
Each service migrates at startup Single instance per service, simple deploys Concurrent replicas race on startup; failures block boot
Separate migrations repo or pipeline A DBA or platform team owns schema changes Schema and code changes ship out of step

How does this setup affect development cost and save engineering time?

A shared helpers library, not a shared schema

Most duplication across services sits around the client, not in the schema. Put a client factory, query logging and connection-lifecycle handling in a library such as libs/prisma-utils. The factory should accept a service's generated PrismaClient class as a parameter and never import one itself. That keeps the library free of any schema or generated types. As a result, editing orders-api's schema doesn't mark every consumer of the helpers as affected. Changing the helpers does, which is correct because their runtime behaviour changed.

A new engineer's local loop

With the targets from earlier sections, a first schema change stays inside one project:

  1. nx run orders-api:migrate-dev --name=add_order_status creates and applies the migration against that service's local database only.
  2. nx run orders-api:prisma-generate regenerates that service's client.
  3. nx run orders-api:migrate-status confirms nothing is pending.

The engineer never has to work out which .env file, schema path or --schema flag applies, because the target encodes those.

Weighing the cost

The upfront cost is real. Someone writes and reviews target definitions for each service, decides cache inputs and wires CI. Each new service also needs the same scaffolding, which a generator can reduce.

That configuration buys you three things:

  • No wrong-database migrations. The target encodes the schema path and connection, so a migration can't run against a database that belongs to another service.
  • No silently skipped deploys. CI runs migrate-status and migrate-deploy through nx affected, so a service whose schema changed can't ship without its migrations.
  • No manual command list. Engineers stop keeping notes on which flags each service needs.

Wrong-database migrations and skipped deploys are expensive to diagnose and repair, so the configuration effort usually pays for itself after the first incident it prevents.

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 prisma migrations, 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.