pnpm workspaces
Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently.
Prisma is a powerful ORM for managing your database, and when combined with pnpm Workspaces, you can maintain a lean and modular monorepo architecture. In this guide, we’ll walk through setting up Prisma in its own package within a pnpm Workspaces monorepo, enabling maintainable type sharing and efficient database management across your apps.
What you'll learn:
- How to initialize a monorepo using pnpm Workspaces.
- Steps to integrate Prisma as a standalone package.
- How to generate and share the Prisma Client across packages.
- Integrating the Prisma package into an application within your workspace.
1. Prepare your project and configure pnpm workspaces
Before integrating Prisma, you need to set up your project structure. Start by creating a new directory for your project (for example, my-monorepo) and initialize a Node.js project:
mkdir my-monorepo
cd my-monorepo
pnpm initNext, create a pnpm-workspace.yaml file to define your workspace structure and pin the Prisma version:
touch pnpm-workspace.yamlAdd the following configuration to pnpm-workspace.yaml:
packages:
- "apps/*"
- "packages/*"
catalogs:
prisma:
prisma: latestFinally, create directories for your applications and shared packages:
mkdir apps
mkdir -p packages/database2. Setup the shared database package
This section covers creating a standalone database package that uses Prisma. The package will house all database models and the generated Prisma Client, making it reusable across your monorepo.
2.1. Initialize the package and install dependencies
Navigate to the packages/database directory and initialize a new package:
cd packages/database
pnpm initAdd Prisma as a development dependency in your package.json using the pinned catalog:
"devDependencies": {
"prisma": "catalog:prisma"
} Then install Prisma:
pnpm installThen, add additional dependencies:
pnpm add typescript tsx @types/node @types/pg -D
pnpm add @prisma/adapter-pg pgIf you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of @prisma/adapter-pg. For more information, see Database drivers.
Initalize a tsconfig.json file for your database package:
pnpm tsc --init2.2. Setup Prisma ORM in your database package
Initialize Prisma ORM with an instance of Prisma Postgres in the database package by running the following command:
pnpm prisma init --dbEnter a name for your project and choose a database region.
We're going to be using Prisma Postgres in this guide. If you're not using a Prisma Postgres database, you won't need to add the --db flag.
This command:
- Connects your CLI to your Prisma Data Platform account. If you're not logged in or don't have an account, your browser will open to guide you through creating a new account or signing into your existing one.
- Creates a
prismadirectory containing aschema.prismafile for your database models. - Creates a
.envfile with yourDATABASE_URL(e.g., for Prisma Postgres it should have something similar toDATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI...").
Edit the schema.prisma file to define a User model in your database and specify a custom output directory to generate the Prisma Client. This ensures that generated types are resolved correctly:
generator client {
provider = "prisma-client"
output = "../generated/client"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
} Now, create a prisma.config.ts file in the database package to configure Prisma:
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DATABASE_URL"),
},
}); You'll need to install the dotenv package to load environment variables from the .env file:
pnpm add dotenvNext, add helper scripts to your package.json to simplify Prisma commands:
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
"db:deploy": "prisma migrate deploy",
"db:studio": "prisma studio"
}
}Use Prisma Migrate to migrate your database changes:
pnpm run db:migrateWhen prompted by the CLI, enter a descriptive name for your migration.
Once the migration is successful, create a client.ts file to initialize Prisma Client with a driver adapter:
import { PrismaClient } from "./generated/client";
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
});
// Use globalThis for broader environment compatibility
const globalForPrisma = globalThis as typeof globalThis & {
prisma?: PrismaClient;
};
// Named export with global memoization
export const prisma: PrismaClient =
globalForPrisma.prisma ??
new PrismaClient({
adapter,
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
} Then, create an index.ts file to re-export the instance of Prisma Client and all generated types:
export { prisma } from "./client";
export * from "./generated/client"; At this point, your shared database package is fully configured and ready for use across your monorepo.
3. Set up and integrate your frontend application
Now that the database package is set up, create a frontend application (using Next.js) that uses the shared Prisma Client to interact with your database.
3.1. Bootstrap a Next.js application
Navigate to the apps directory:
cd ../../appsCreate a new Next.js app named web:
pnpm create next-app@latest web --yesimportant
The --yes flag uses default configurations to bootstrap the Next.js app (which in this guide uses the app router without a src/ directory and pnpm as the installer).
Additionally, the flag may automatically initialize a Git repository in the web folder. If that happens, please remove the .git directory by running rm -r .git.
Then, navigate into the web directory:
cd web/Copy the .env file from the database package to ensure the same environment variables are available:
cp ../../packages/database/.env .Open the package.json file of your Next.js app and add the shared database package as a dependency:
"dependencies": {
"database": "workspace:*",
// additional dependencies
// ...
}Run the following command to install the database package:
pnpm install3.2. Integrate the shared database package in your app code
Modify your Next.js application code to use Prisma Client from the database package. Update app/page.tsx as follows:
import { prisma } from "database";
export default async function Home() {
const user = await prisma.user.findFirst({
select: {
name: true,
},
});
return (
<div>
{" "}
{user?.name && <p>Hello from {user.name}</p>} // [!code ++]
{!user?.name && <p>No user has been added to the database yet. </p>} // [!code ++]
</div>
);
} This code demonstrates importing and using the shared Prisma Client to query your User model.
3.3. Add helper scripts and run your application
Add the following scripts to the root package.json of your monorepo. They ensure that database migrations, type generation, and app builds run in the proper order:
"scripts": {
"build": "pnpm --filter database db:deploy && pnpm --filter database db:generate && pnpm --filter web build",
"start": "pnpm --filter web start",
"dev": "pnpm --filter database db:generate && pnpm --filter web dev",
"studio": "pnpm --filter database db:studio"
}3.4. Run your application
Then head back to the root of the monorepo:
cd ../../Start your development server by executing:
pnpm run devOpen your browser at http://localhost:3000 to see your app in action.
3.5. (Optional) Add data to your database using Prisma Studio
There shouldn't be data in your database yet. You can execute pnpm run studio in your CLI to start a Prisma Studio in http://localhost:5555 to interact with your database and add data to it.
Next Steps
You have now created a monorepo that uses Prisma ORM effectively, with a shared database package integrated into a Next.js application.
For further exploration and to enhance your setup, consider reading the How to use Prisma ORM with Turborepo guide.