What is an Nx Prisma shared library and why use one?
An Nx Prisma shared library is a single Nx library, conventionally libs/db, that owns everything Prisma needs: schema.prisma, the migrations folder, and the generated client. The library's entry point exports a configured client factory and the generated model types. Every backend app in the workspace imports from that library rather than talking to Prisma directly.
There are two common alternatives, and both fail in similar ways. In the first, each app keeps its own copy of the schema. The copies drift as one team adds a column and another doesn't. You end up with several migration histories that each claim to describe the same database, and nobody can say which one is authoritative. In the second, apps import an implicitly generated client from node_modules. The client then depends on whichever prisma generate ran last, Nx can't see it as a project dependency, and its output isn't tied to any project in the graph. That makes caching and affected-project detection unreliable.
Centralising the schema gives you:
- One source of truth. A model change happens once and is type-checked against every consumer in the same commit.
- One migration history. The database has exactly one ordered sequence of migrations.
- One place to change the client. Logging, connection settings, and extensions are configured once.
The pattern suits backend and platform teams running several Node services against one shared database in an Nx workspace. It fits best when those services share a domain model and release together, or at least tolerate coordinated schema changes.
+---------------+ +---------------+ +---------------+
| apps/api | | apps/worker | | apps/admin |
+-------+-------+ +-------+-------+ +-------+-------+
| | |
+-------------------+-------------------+
| import client + types from libs/db
+---------------------------v-------------------------------+
| libs/db (shared Nx library) |
| |
| +-----------------+ +-----------------+ |
| | schema.prisma |---------------->| generated client| |
| +--------+--------+ prisma generate +--------+--------+ |
| | prisma migrate dev | |
| +--------v--------+ +--------v--------+ |
| | migrations/ | | index.ts | |
| | | | exports client | |
| | | | factory + types | |
| +--------+--------+ +-----------------+ |
+-----------+-----------------------------------------------+
| one ordered migration history
+---------v---------+
| shared database |
+-------------------+
Every backend app imports a configured client and model types from libs/db, which alone owns schema.prisma, the generated client and the single migration history applied to the shared database.
How do you lay out the library and control where the generated client goes?
Put everything Prisma owns inside the library so the schema, its history and the generated code move together. A typical layout is libs/db/prisma/schema.prisma, libs/db/prisma/migrations/ for the migration history, and libs/db/src/ for TypeScript. Keep the generated client in its own folder such as libs/db/src/generated/, and add that folder to .gitignore.
Set the generator's output explicitly, for example output = "../src/generated/client". Prisma resolves this path relative to the schema file, not the workspace root. Without an explicit output, the client can land in a shared node_modules location. Every app then depends on whichever generate ran last, and Nx cannot treat the client as an output of the library. Writing it inside libs/db makes the client a declared artifact that Nx can cache and invalidate when the schema changes.
libs/db/src/index.ts is the only public entry point. It re-exports the generated model types and enums, plus a createPrismaClient factory. Apps import from the alias, such as @acme/db, and never from generated/ directly. That leaves you free to move or regenerate the client without touching consumers.
The alias is defined in compilerOptions.paths in tsconfig.base.json and maps to libs/db/src/index.ts. tsc honours it, but other tools may not:
- Jest and Vitest need path mapping configured, or they fail at import time even though type-checking passes.
- Bundlers need the same mapping configured to resolve the alias.
- Editors can show stale types until the TypeScript server restarts after a regenerate.
When something compiles but won't run, check module resolution first.
// libs/db/src/index.ts: the only public entry point for @acme/db.
//
// Assumes libs/db/prisma/schema.prisma contains:
// generator client {
// provider = "prisma-client-js"
// output = "../src/generated/client" // relative to schema.prisma
// }
// so `prisma generate` writes the client into libs/db/src/generated/client.
import { PrismaClient, Prisma } from './generated/client';
// Re-export model types, enums and the Prisma namespace so apps never
// import from ./generated directly. The client can then move or be
// regenerated without changing any consumer.
export * from './generated/client';
// Apps call this factory instead of constructing PrismaClient themselves.
// Shared defaults (here, logging) live in one place, and callers can still
// override them per app.
export function createPrismaClient(
options: Prisma.PrismaClientOptions = {}
): PrismaClient {
return new PrismaClient({
log: ['warn', 'error'],
...options,
});
}
// Consumers resolve '@acme/db' through tsconfig.base.json:
// "paths": { "@acme/db": ["libs/db/src/index.ts"] }
// Jest, Vitest and bundlers each need the same mapping configured.
// Without it, imports can fail at runtime even though tsc type-checks.
The library's public entry point re-exports the client generated into libs/db/src/generated/client and wraps construction in a createPrismaClient factory, which apps reach through the @acme/db path alias.
How do you wire Prisma generate and migrate as cached Nx targets?
In the library's project.json, define the Prisma commands as targets using the nx:run-commands executor. Pass --schema explicitly on every command so the CLI never falls back to searching the workspace root. A typical set is generate (runs prisma generate), migrate-dev, migrate-deploy and validate. Only generate should be cacheable. Migrations change a database, which Nx cannot see, so set cache: false on those targets.
For generate, declare these:
- Inputs: the schema file, plus anything else that changes the output. That includes the generator block's settings, which live in the schema, and the Prisma version, which comes from the root
package.jsonor lockfile. Add those viaexternalDependenciesor a file input. - Outputs: the generated client directory.
Then add "dependsOn": ["^generate"] to each consuming app's build, test and serve targets. This makes Nx run or restore generate on the library before any of those targets start.
Apps import the library, so the project graph already links them to it. Editing schema.prisma therefore marks the library and every dependent app as affected, and nx affected -t test exercises all of them.
Missing inputs cause a quieter failure. Suppose you upgrade Prisma and the version is not an input. The hash stays the same, and Nx restores the old client from cache. That client may no longer match the runtime package.
| Approach | Pros | Cons |
|---|---|---|
| Commit generated client | Builds work without running generate; diffs show the client changes |
Noisy pull requests; easy to commit output that doesn't match the schema |
| Generate in CI | Single source of truth; small diffs | Every job depends on generate and on correct cache inputs |
Most teams ignore the output directory in git and rely on generate running before build and test, with the cache keeping repeat runs fast.
// libs/db/project.json (Nx accepts comments in project.json)
// Each consuming app adds: "build": { "dependsOn": ["^generate"] } (same for test/serve)
{
"name": "db",
"targets": {
"generate": {
"executor": "nx:run-commands",
"options": {
"command": "npx prisma generate --schema=libs/db/prisma/schema.prisma"
},
"cache": true,
// Schema covers models and generator settings; the Prisma packages cover version bumps
"inputs": [
"{projectRoot}/prisma/schema.prisma",
{ "externalDependencies": ["prisma", "@prisma/client"] }
],
// Must match the generator block's output path so cache restores the real client
"outputs": ["{projectRoot}/src/generated/client"]
},
"validate": {
"executor": "nx:run-commands",
"options": {
"command": "npx prisma validate --schema=libs/db/prisma/schema.prisma"
}
},
"migrate-dev": {
"executor": "nx:run-commands",
"options": {
"command": "npx prisma migrate dev --schema=libs/db/prisma/schema.prisma"
},
// Changes database state Nx cannot see, so never replay from cache
"cache": false
},
"migrate-deploy": {
"executor": "nx:run-commands",
"options": {
"command": "npx prisma migrate deploy --schema=libs/db/prisma/schema.prisma"
},
"cache": false
}
}
}
A library project.json where only generate is cached. Its inputs are the schema and the Prisma package versions, and its output is the generated client directory. Migration targets have caching turned off, and each app's targets declare dependsOn ^generate.
How should each app create and manage its PrismaClient?
The shared library should export a single factory, for example getPrismaClient(), rather than a ready-made instance created at import time. A factory lets each app decide when the client is built and lets tests swap in their own configuration. The factory reads its connection string from an environment variable such as DATABASE_URL. Each app's deployment then supplies its own credentials and pool settings while every app imports the same generated client.
Inside the factory, cache the instance in module scope so one process holds exactly one client. Each PrismaClient opens its own connection pool, so a second instance doubles the connections that process holds. Development servers with hot reload re-evaluate modules on every change, which resets module-scoped variables. To guard against this, store the client on globalThis when not in production and reuse it if it already exists. Without the guard, every file save can leave another pool's connections open until the database rejects new ones.
Pool pressure matters more once several services share one database. Prisma sizes its pool from the host's CPU count by default. That count says nothing about the database's limit, so set connection_limit explicitly in each service's connection string and budget the total across all services.
Illustrative estimate (assumed inputs): four services, three replicas each, pool size 10 gives 4 × 3 × 10 = 120 connections. That exceeds a PostgreSQL server left at its common default of max_connections = 100, before migrations or admin sessions connect at all. You have three options:
- Shrink the per-replica pools.
- Cap replica counts.
- Put an external connection pooler in transaction mode between the services and the database. The pooler multiplexes many client connections onto a small, fixed set of server connections.
// libs/data-access-db/src/lib/prisma-client.ts
// Shared factory: one PrismaClient per process, configured by env vars.
import { PrismaClient } from '@prisma/client';
// Survives module re-evaluation during dev hot reload.
const globalForPrisma = globalThis as unknown as {
prisma?: PrismaClient;
};
let client: PrismaClient | undefined;
export function getPrismaClient(): PrismaClient {
if (client) return client;
// Each deployment supplies its own URL and an explicit pool size, e.g.
// postgresql://app_user:changeme@db.internal:5432/app?connection_limit=10
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not set');
}
// In dev, reuse the instance left on globalThis by a previous reload
// instead of opening another connection pool.
client =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'production' ? ['error'] : ['warn', 'error'],
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = client;
}
return client;
}
// Call on shutdown so the pool's connections are released promptly.
export async function disconnectPrisma(): Promise<void> {
if (client) {
await client.$disconnect();
client = undefined;
globalForPrisma.prisma = undefined;
}
}
A shared-library factory that caches one PrismaClient per process, reads its connection string (including an explicit connection_limit) from DATABASE_URL, and reuses the instance stored on globalThis during development hot reload.
Bundling, query engines and deployment
Prisma's generated client is not pure JavaScript. Alongside the TypeScript code it writes a platform-specific query engine, a native library compiled for one operating system, CPU architecture, libc and OpenSSL version. The engine has to be in every app's build output, and it has to match the machine that will run it.
Configure binaryTargets for where code runs
By default the generator builds an engine only for the current machine (native). A developer on an ARM Mac gets a Darwin engine. Copy that output into a Debian or Alpine container and the client fails when it tries to load the engine, often at startup or on the first query. Nothing fails at compile time.
To fix it, list every target in the generator's binaryTargets. Keep native for local work and add the Linux variants your images use. Alpine (musl) and Debian (glibc) need different engines, and so do different OpenSSL major versions. Treat the base image and the binary target as a pair: if one changes, change the other in the same change set.
Make the bundler keep the engine
Webpack and esbuild follow JavaScript imports. They do not copy native files they cannot parse. You have two options:
- Mark the generated client as external and ship it next to the bundle.
- Use the app's asset configuration to copy the engine files into
dist.
Either way, check the built output directly and confirm the engine file is there.
Catch mismatches in CI
The Nx cache adds a specific risk. If a remote cache restores a prisma generate output produced on a Mac, a Linux CI job can reuse that wrong engine. You can prevent this by listing all binary targets so every cached output contains every engine, or by adding the runtime platform to the target's inputs.
Then build the real container image in CI. Inside it, run a smoke test that creates a client and runs SELECT 1 against a throwaway database.
Who should run migrations, and how do you enforce boundaries?
Give migrations exactly one owner: a migrate target on the database library that runs prisma migrate deploy, executed once by a CI or release step before any new app version rolls out. Do not run it from each service's startup. If five services each start three replicas, fifteen processes try to apply the same migration at the same moment. At best, most of them wait and slow the rollout. At worst, a failure halfway leaves some replicas serving traffic against a half-migrated schema. A single step also means only one credential needs DDL rights, so the apps' runtime users can be limited to reads and writes.
Because migrations run before the rollout, old and new app versions will share the same database for a while. Use expand-then-contract to keep both working:
- Expand. Add the new column or table as nullable or with a default, and deploy code that writes to both the old and new shapes.
- Backfill. Copy existing data into the new shape.
- Contract. Once no running version reads the old shape, drop it in a later migration.
Never rename or drop a column in the same release that stops using it.
To keep Prisma out of frontend bundles, tag projects in Nx. For example, tag backend apps and the db library platform:node and browser projects platform:web. Then add depConstraints to @nx/enforce-module-boundaries so that platform:web projects can depend only on platform:web or platform:shared. An accidental import from a React app now fails lint instead of reaching a build. You can also tag the db library type:db and allow only type:data-access libraries to import it, so apps go through repository code rather than calling the client directly.
When should you avoid a single shared schema, and what are the alternatives?
A shared schema is still a shared dependency, and its costs grow with the number of apps that import it. Every service is coupled to one database model, so a column rename in a table only one app uses still changes the generated client for all of them. Nx correctly marks every dependent project as affected, which means regeneration, retesting and often redeploys for services whose behavior did not change. Ownership also blurs. When any app can read and write any table, nobody can say which service owns invoices, and extracting that service later means first finding every cross-table query that crept in.
| Approach | Coupling | Main cost | Fits when |
|---|---|---|---|
| Single shared schema | All apps to one model | Broad rebuilds, unclear ownership | Few apps, one team, one database |
| Per-app schemas | None at the schema level | Duplicated models, drift between copies | Apps truly share no tables |
| One library per bounded context or database | Within each context | More libraries and targets to configure | Clear domains, possibly separate databases |
| Service owns data behind an API | Through an API contract | Network hops, API versioning | Independent deploys matter most |
If you split into several schemas, give each one its own generator block with a distinct output path inside its library. Otherwise every schema generates to the same default location, and whichever runs last overwrites the others' client.
The trade-off comes down to engineering time. One schema removes duplicated model work and the debugging that follows when copies drift apart. In exchange, teams spend more effort coordinating schema changes, and the more granular options add configuration and ownership overhead.
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.