How to use Prisma ORM in a pnpm workspaces monorepo
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 init
Next, create a pnpm-workspace.yaml
file to define your workspace structure and pin the Prisma version:
touch pnpm-workspace.yaml
Add the following configuration to pnpm-workspace.yaml
:
packages:
- "apps/*"
- "packages/*"
catalogs:
prisma:
prisma: latest
Finally, create directories for your applications and shared packages:
mkdir apps
mkdir -p packages/database
2. 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 init
Add Prisma as a development dependency in your package.json
using the pinned catalog
:
"devDependencies": {
"prisma": "catalog:prisma"
}
Then install Prisma:
pnpm install
Then, add additional dependencies:
pnpm add typescript tsx @types/node -D
Then install the Prisma Client extension required to use Prisma Postgres:
pnpm add @prisma/extension-accelerate
This guide uses Prisma Postgres. If you plan to use a different database, you can omit the @prisma/extension-accelerate package.
Initalize a tsconfig.json
file for your database
package:
pnpm tsc --init
2.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 --db
Enter 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 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
prisma
directory containing aschema.prisma
file for your database models. - Creates a
.env
file 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-js"
output = "../generated/client"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
Next, add helper scripts to your package.json
to simplify Prisma commands:
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"db:generate": "prisma generate --no-engine",
"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:migrate
When 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 the Accelerate extension:
import { PrismaClient } from "./generated/client";
import { withAccelerate } from '@prisma/extension-accelerate'
const prisma = new PrismaClient().$extends(withAccelerate())
const globalForPrisma = global as unknown as { prisma: typeof prisma }
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
export { 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 ../../apps
Create a new Next.js app named web
:
pnpm create next-app@latest web --yes
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 .
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
.
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 install
3.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>}
{!user?.name && <p>No user has been added to the database yet. </p>}
</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 dev
Open your browser at http://localhost:3000
to see your app in action.
3.5. (Optional) Add data to your database using Prisma Studio
Their 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.