What is an Nx Prisma shared library and how is it laid out?

This guide is for platform and backend engineers running several services against one database in an Nx workspace. The pattern: one Nx library owns everything that defines the database contract, and every backend app consumes it.

What the library owns

  • schema.prisma: the single source of truth for models, enums and the datasource.
  • The migrations folder: the ordered history Prisma Migrate produces from that schema.
  • A thin TypeScript module that creates one PrismaClient and re-exports it with the generated model types.

A typical layout:

  • libs/db/prisma/schema.prisma
  • libs/db/prisma/migrations/
  • libs/db/src/client.ts creates the client
  • libs/db/src/index.ts is the public entry point for the client and types
  • apps/orders-api/ and apps/billing-worker/ both import from the library

Dependency direction

Dependencies point one way: apps → libs/db. The library never imports from an app. Apps reference it only through its path alias, such as @myorg/db, which is mapped in the workspace's base tsconfig.

This produces two rules:

  • Never import from the generated client path. That path is a build artifact whose location you may change later. Importing through the alias also lets Nx see the dependency in its project graph. A deep import into generated output hides that edge.
  • Never construct your own PrismaClient in an app. Connection settings, logging and middleware then live in one place. Each service also keeps one predictable connection pool instead of several ad hoc ones.

Schema, migrations and client stay in the same project. A schema change and its generated types therefore always move together.

// libs/db/src/client.ts
import { PrismaClient } from '@prisma/client';

// The only place in the workspace that constructs a client.
// Logging and connection settings are configured once here.
export const prisma = new PrismaClient({
  log: process.env.NODE_ENV === 'production' ? ['error'] : ['warn', 'error'],
});

// libs/db/src/index.ts (the public entry point behind the @myorg/db alias)
export { prisma } from './client';
// Re-export the Prisma namespace and model types so apps never import the generated path.
export { Prisma } from '@prisma/client';
export type { Order, Invoice } from '@prisma/client';

// tsconfig.base.json (excerpt) maps the alias to the library entry point:
//   "paths": { "@myorg/db": ["libs/db/src/index.ts"] }

// apps/orders-api/src/orders.service.ts
// Import only through the alias. This keeps the apps -> libs/db edge visible
// in the Nx project graph and reuses the shared client and its connection pool.
import { prisma, type Order } from '@myorg/db';

export async function findOrder(id: string): Promise<Order | null> {
  return prisma.order.findUnique({ where: { id } });
}

The library's client module and public index create a single PrismaClient and re-export it with the generated types, and an app consumes both only through the @myorg/db alias.

Who should use an Nx Prisma shared library?

Use this pattern if all of the following are true:

  • You have an Nx monorepo with two or more backend projects (APIs, workers, schedulers, CLI scripts) that read or write the same database.
  • One team owns that database, or a few teams that already coordinate releases do. The schema is a shared contract either way. The library makes that contract explicit.
  • You use Prisma as the data layer, or plan to standardize on it, and want one generated client and one migration history instead of a copy per service.

It is also a good fit for platform teams who maintain workspace tooling. They can own the generate and migrate targets and the module boundary rules in one place, so service teams don't each reinvent them.

It is a poor fit for:

  • Workspaces with a single backend app. A plain Prisma setup inside that app is simpler. Extract a library when a second consumer appears.
  • Services in separate bounded contexts with independent release schedules. Every migration in a shared schema gates every consumer. Separate databases or an API boundary suit them better (see the alternatives section).
  • Frontend or edge-only projects. The client and its query engine belong on the server. Module boundary tags should keep them out.

How does the shared library work end to end?

The pattern is a chain of steps. Each one is owned by the database library and wired to the apps through the Nx project graph.

  1. A developer edits libs/db/prisma/schema.prisma. This is the only schema file in the workspace.
  2. They run the library's migrate-dev target locally. Prisma Migrate compares the schema to the development database, writes a new SQL migration into libs/db/prisma/migrations/, applies it, and regenerates the client. The migration file is committed alongside the schema change.
  3. prisma generate produces the typed client inside the library (with a custom output), and the library's index.ts re-exports it together with the single shared prisma instance.
  4. Apps import only from the alias (@myorg/db). Nx detects that import, so the project graph records an edge from each app to the library.
  5. Because of that edge, a schema change marks every consuming app as affected. nx affected runs type-checking, tests and builds for exactly those apps. A renamed field shows up as a compile error in every app that uses it, in the same pull request.
  6. Every consumer target depends on ^generate. Nx runs codegen before any build, serve, test or typecheck. The generate target is cached on the schema and Prisma version, so it actually runs only when one of those changes and is otherwise restored from cache.
  7. In CI, a dedicated job runs nx run db:migrate-deploy against the target environment. It applies pending migrations from the committed history and never creates new ones.
  8. Affected apps roll out after the migration job succeeds. Each one ships with the client generated from the same schema the database now has. Each process creates one connection pool from the shared instance.

The rest of this article covers how to configure each step correctly: where the client lives, how to make caching safe, how to sequence migrations, and what to check at deploy time.

Why share one database client across backend apps, and when should you avoid it?

The main reason to share is that there is only one version of the truth. Every app compiles against the same generated types, so a renamed column fails type checking in every consumer in the same pull request. It does not surface later as a runtime error in the one service nobody rebuilt. There is one migration history, so no app can hold a stale idea of the tables. Client drift, where two services run clients generated from slightly different schemas, cannot happen.

This fits when several services use one database that a single team owns, or that closely coordinated teams own and already ship together. In that setup the coupling exists already at the database level. The shared library only makes it visible to the compiler.

It stops fitting when the services belong to separate bounded contexts, or when teams need their own deploy cadence. A shared schema means a migration for one app is a migration for all of them. Every consumer then has to tolerate the new shape before it ships. As more apps depend on the library, each change reaches further and coordination becomes the bottleneck.

Approach Coupling Independent deploys Drift risk
Shared schema and client library High: one model for all apps Limited: migrations gate everyone None
Schema and client per app, same database Hidden: tables still shared Apparent, but fragile High
Database per bounded context Low Yes Not applicable
One data-owning service exposing an API Through the API contract Yes, if the API is versioned Confined to the API

The per-app schema on a shared database is the option to watch out for. It keeps the coupling and removes the compiler check that would have caught it.

What are the alternatives to a shared Prisma library?

The table above compares the main options. In more detail:

  • A schema and client per app on the same database. Each service keeps its own schema.prisma, often generated with prisma db pull, and its own client. This looks independent, but the tables are still shared. Nothing stops one app's migration from breaking another app's queries, and two migration histories can disagree about the same tables. Choose this only as a short-lived step during a migration, never as a target state.
  • A database per bounded context. Each service owns its own database, schema and migrations, and other services never touch its tables. This removes the shared-migration bottleneck and permits independent deploys. The cost is that cross-context data has to move through APIs or events, and joins across contexts are no longer a single query. In Nx, this usually means one data-access library per context instead of one shared library.
  • One data-owning service that exposes an API. A single service owns the database and the Prisma client. Other apps call it over HTTP, RPC or a message bus. The contract moves from the schema to the API, which you version explicitly. This adds a network hop and an extra service to operate, but it limits schema knowledge to one codebase.
  • A versioned package published outside the monorepo. The schema and client ship as a package that each service pins to a version. This lets services upgrade on their own schedule. It also brings back drift: different services can run different client versions against one database, and the compiler no longer catches the mismatch across them.
  • A different data-access tool. You can apply the same shared-library layout with another ORM, a query builder or hand-written SQL. The structural advice in this article still applies: one owner for the schema and migrations, one client per process, imports through an alias. The Prisma-specific parts (generate, engine binaries, binaryTargets) do not.

A common path is to start with the shared library while one team owns the data. Then split out a database per bounded context once the warning signs described in the blast-radius section appear.

Where should the generated Prisma client live: node_modules or a custom output path?

The default generator writes the client into node_modules, and apps import it from @prisma/client. A custom output in the generator block puts it inside the library, for example a gitignored generated/ folder, and apps import it only through the library's public entry point. That difference affects most of the tooling around the client.

Concern Default (node_modules) Custom path in the library
Import path @prisma/client from any project Library alias only, so the boundary is enforced by the import itself
Editor types Depends on the TS server noticing a change in node_modules, so it often needs a restart after generate Treated like workspace source and picked up on the next file watch
Bundling Usually externalized, so the deploy artifact needs node_modules with the generated client present Bundled with the library unless you mark it external. The query engine file still has to be copied to dist
Generators and tooling Matches the docs, examples and most third-party integrations Some tools assume @prisma/client and need extra configuration
Nx cache output Shared, unowned directory that is fragile to declare and restore Project-scoped path you can declare as the generate target's output

Choose the custom path when caching matters. Nx can only restore what it can safely attribute to a target. A folder owned by the database library can be declared as that target's output and replayed on a cache hit. node_modules is rewritten by every install and shared by every project, so Nx cannot attribute it to one target.

The trade-off is that you move away from the default setup. Copy-pasted snippets that import @prisma/client will not work as written. Each deploy pipeline also has to account for the engine file explicitly.

generator client {
  provider = "prisma-client-js"
  output   = "../generated/client"
}

{
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": ["{projectRoot}/prisma/schema.prisma"],
      "outputs": ["{projectRoot}/generated"],
      "options": {
        "command": "prisma generate --schema=libs/db/prisma/schema.prisma"
      }
    }
  }
}

export * from '../generated/client';

A Prisma generator with a custom output path inside the database library, an Nx generate target that declares that folder as a cacheable output, and the library entry point that re-exports the client.

How do you make prisma generate caching correct in Nx?

Define a generate target on the database library and treat it like any other cacheable build step. Its inputs should be the schema file, any files the generator config references, and the installed Prisma version. Nx supports the last one through an externalDependencies input listing prisma and @prisma/client, which hashes the resolved versions from the lockfile. Declare the generated client directory as the target's outputs. In each app, make build, serve, test and typecheck depend on ^generate. Nx then runs codegen once per change, restores it from cache otherwise, and never lets a consumer start against a missing client.

The failures are silent:

  • A cache hit that restores nothing. The declared output path doesn't match the generator's output, so Nx reports success while the directory stays empty.
  • A stale client. The schema isn't in the inputs, so a column change still hits the cache.
  • CI regenerating on every run. Broad inputs such as {projectRoot}/**/* include the generated files, so each run changes its own hash.

A missing Prisma version input is the most likely subtle bug. After a Prisma upgrade, Nx can restore a client generated by the old version, and nothing fails until runtime.

To verify, run nx show project <db-lib> --json and check the resolved inputs and outputs. Then delete the generated directory and rerun the target. The log should report a cache hit, and the directory should exist again.

Illustrative estimate. Assume generation takes 15 seconds, four apps each run four dependent targets, and there are 40 CI runs a day. Without caching, codegen can run up to 16 times per pipeline, about 4 minutes. With caching, it runs at most once and usually restores in under a second. That saves roughly 2.5 compute-hours a day.

// libs/db/project.json (Nx accepts comments in project.json)
{
  "name": "db",
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "options": {
        "command": "npx prisma generate --schema=libs/db/prisma/schema.prisma"
      },
      "cache": true,
      "inputs": [
        // A schema change must invalidate the cache
        "{projectRoot}/prisma/schema.prisma",
        // Hash the Prisma versions resolved in the lockfile, so an upgrade
        // can't restore a client built by the old generator
        { "externalDependencies": ["prisma", "@prisma/client"] }
      ],
      // Must match the generator block in schema.prisma:
      //   generator client { output = "../src/generated/client" }
      // A mismatch gives a cache hit that restores nothing.
      "outputs": ["{projectRoot}/src/generated/client"]
    }
  }
}

// nx.json: every consumer waits for its dependencies' generate target
// "targetDefaults": {
//   "build":     { "dependsOn": ["^generate"] },
//   "serve":     { "dependsOn": ["^generate"] },
//   "test":      { "dependsOn": ["^generate"] },
//   "typecheck": { "dependsOn": ["^generate"] }
// }

// Verify:
//   nx show project db --json      # check resolved inputs and outputs
//   rm -rf libs/db/src/generated/client && nx run db:generate
//   # expect a cache hit in the log and the directory restored

A cacheable Prisma generate target with explicit schema and Prisma-version inputs, an output path that matches the generator, and targetDefaults that make app targets depend on it.

How should migrations run when several apps share one schema?

The database library should be the only project that defines migrate dev and migrate deploy targets. Backend apps depend on the library but never run migrations. Having a single owner gives you one place to look for migration history and one command to audit. Mark both targets as uncached. A cache hit would skip the command and still report success, which is wrong for a target whose purpose is to change a real database.

Run migrate deploy as its own pipeline job, and order it before any app rolls out. Do not run it at each app's startup. If ten replicas boot at once, they all try to migrate the same database. Even if the tool serializes them with a lock, every pod's readiness now depends on how long the migration takes, and one failed migration crash-loops the whole fleet instead of failing a single job you can retry.

When apps deploy independently, use expand-and-contract:

  1. Expand. Add the new column as nullable so existing writers keep working.
  2. Backfill. Copy existing data into the new column.
  3. Switch. Change readers and writers in every app, one deploy at a time.
  4. Contract. Drop the old column.

Order matters because the generated client names columns explicitly in its queries. If you drop or rename a column while any app still runs the older client, that app's queries fail at runtime.

The contract step is the one that tends to get forgotten. Assign it a named owner and a tracked task when you plan the expand step. Otherwise unused columns and dual-write code stay around indefinitely.

{
  "name": "db",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/db/src",
  "projectType": "library",
  "tags": ["scope:shared", "type:data-access"],
  "targets": {
    "migrate-dev": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "npx prisma migrate dev --schema=libs/db/prisma/schema.prisma"
      }
    },
    "migrate-deploy": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "npx prisma migrate deploy --schema=libs/db/prisma/schema.prisma"
      }
    },
    "migrate-status": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "npx prisma migrate status --schema=libs/db/prisma/schema.prisma"
      }
    }
  }
}

The shared database library's project.json is the only place that defines Prisma migration targets. Every target sets cache to false so Nx always runs the command against the real database. CI runs nx run db:migrate-deploy as its own job before any app rolls out.

How do Nx affected and module boundaries control the blast radius?

A schema edit marks every app that depends on the database library as affected. That is correct, because each one compiles against the regenerated client and may break. The cost is that a one-column change can rebuild and retest every backend service. Teams then look for shortcuts, such as excluding the schema from the library's inputs or declaring dependencies by hand. Those shortcuts make the graph wrong, and a wrong graph is worse than a slow one.

Accept the fan-out and make each affected app cheap to verify. Type-checking and unit tests should run fast on every affected app. Run integration suites against a real database in parallel per app, and rely on the cache so unchanged targets are skipped. For deploys, ship every affected service that has a new build artifact. A service running an outdated client is the failure the graph is there to prevent.

Watch for signs that one schema has outgrown its consumers:

  • Most schema changes touch models that only one app reads.
  • Teams queue behind each other's migrations.
  • Apps own tables that don't overlap.

Each of these suggests splitting into separate schemas and databases.

Use module boundary tags to limit who can import the library. Tag it scope:server and permit that tag only from backend applications and server-side libraries. This keeps the client and its native query engine out of frontend and edge bundles, where it either fails to load or adds significant size.

Set ownership rules as well. The shared library holds the schema, the generated client, connection setup and only the queries that are truly cross-cutting. App-specific queries belong in app-level or domain data-access libraries. Enforce this with a code owner on the shared library who reviews additions to it.

What breaks at runtime and in deployment when apps share a Prisma client?

Each process should construct exactly one PrismaClient and reuse it. Export that instance from the shared library instead of exporting the class. Every new client opens its own connection pool, so a handler or module that calls new PrismaClient() multiplies connections without any obvious signal until the database rejects them. Development hot reload causes the same problem, which is why the instance is usually cached on globalThis outside production.

Each app has its own pool, but every app draws from the same database connection limit. Size each pool through that app's own DATABASE_URL (for example, with connection_limit) and keep the total below the server maximum.

Illustrative estimate (assumed numbers, not a benchmark)

The formula is: Σ(replicas × connection_limit) + reserved ≤ max_connections.

The assumed inputs are:

  • max_connections is 100.
  • 10 connections are reserved for migrations and admin access.
  • The API runs 4 replicas with a limit of 10 each, which uses 40 connections.
  • The worker runs 3 replicas with a limit of 8 each, which uses 24 connections.
  • The scheduler runs 2 replicas with a limit of 5 each, which uses 10 connections.

The total is 74 + 10 = 84, which fits. If the API scales to 6 replicas, the total becomes 104, and new connections start failing. You need to plan pool sizes against the maximum autoscaling replica count, not the typical count.

Failure Typical symptom Likely cause
Client missing at runtime "Cannot find module" or "did you run prisma generate" The bundler externalized the client, but the image never copied it
Engine not found Error naming the missing platform engine The client was generated on a different OS or libc than the container
Extra connections Pool exhaustion appears earlier than expected The bundle contains two copies of the client, and each copy creates its own pool

Verify each item in every app's build output:

  • The generated client is present in the build output, at a path the app's code can resolve.
  • The engine binary matches the container's OS and libc. Check binaryTargets in the generator block.
  • The bundler resolves the shared library to a single module instance.
  • The app logs one pool initialization per process at startup.

How can a shared Prisma library save engineering time?

Most of the savings come from doing each piece of database work once instead of once per service, and from catching mistakes at compile time rather than in production.

  • One schema change, one pull request. A model change, its migration and every affected call site land together. The compiler lists every consumer that needs updating, so nobody has to search other services' code by hand or coordinate parallel schema edits.
  • No client drift to debug. All services generate from the same schema with the same Prisma version. You avoid the class of bugs where one service queries a column another service's migration already removed, which tend to appear only after a deploy and take a long time to trace.
  • Codegen runs only when it has to. With correct inputs and outputs, generate is restored from the Nx cache on most runs, locally and in CI. The illustrative estimate in the caching section shows how this adds up once several apps and targets depend on it.
  • nx affected limits work to what changed. Changes that don't touch the database library don't rebuild every backend. Schema changes rebuild exactly the apps that need it, with no hand-maintained list of dependents.
  • One migration pipeline to build and maintain. A single migrate-deploy job, owned by the library, replaces per-service migration scripts and startup hooks. When a migration fails, there is one job to inspect and retry.
  • Connection and logging setup written once. Pool sizing, logging levels and client configuration live in one module. New services import @myorg/db and get the same behavior without copying setup code.
  • Faster onboarding for new services. Adding a backend app means adding an import and a dependsOn: ["^generate"] (or inheriting it from targetDefaults). There is no new schema, generator configuration or migration folder to set up.

These savings depend on the conditions described in the "Who should use" section. Once teams spend more time queuing behind each other's migrations than they save from shared types, the coordination cost has overtaken the benefit, and one of the alternatives above is likely the better trade.

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 shared library, 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.