# Table of Contents
- [Search the documentation | Prisma Documentation](#search-the-documentation-prisma-documentation)
- [One doc tagged with "optimization" | Prisma Documentation](#one-doc-tagged-with-optimization-prisma-documentation)
- [One doc tagged with "workflows" | Prisma Documentation](#one-doc-tagged-with-workflows-prisma-documentation)
- [How to write guides for Prisma ORM | Prisma Documentation](#how-to-write-guides-for-prisma-orm-prisma-documentation)
- [How to use Prisma ORM with Cloudflare D1 | Prisma Documentation](#how-to-use-prisma-orm-with-cloudflare-d1-prisma-documentation)
- [How to provision preview databases with GitHub Actions and Prisma Postgres | Prisma Documentation](#how-to-provision-preview-databases-with-github-actions-and-prisma-postgres-prisma-documentation)
- [Partner Database Provisioning & User Claim Flow | Prisma Documentation](#partner-database-provisioning-user-claim-flow-prisma-documentation)
- [Get started with the Prisma Management API | Prisma Documentation](#get-started-with-the-prisma-management-api-prisma-documentation)
- [How to manage schema changes in a team with Prisma Migrate and Prisma ORM | Prisma Documentation](#how-to-manage-schema-changes-in-a-team-with-prisma-migrate-and-prisma-orm-prisma-documentation)
- [How to use Prisma in Docker | Prisma Documentation](#how-to-use-prisma-in-docker-prisma-documentation)
- [Datadog tracing with Prisma ORM | Prisma Documentation](#datadog-tracing-with-prisma-orm-prisma-documentation)
- [How to migrate from Mongoose to Prisma ORM | Prisma Documentation](#how-to-migrate-from-mongoose-to-prisma-orm-prisma-documentation)
- [How to migrate from Drizzle to Prisma ORM | Prisma Documentation](#how-to-migrate-from-drizzle-to-prisma-orm-prisma-documentation)
- [How to migrate data with Prisma ORM using the expand and contract pattern | Prisma Documentation](#how-to-migrate-data-with-prisma-orm-using-the-expand-and-contract-pattern-prisma-documentation)
- [How to migrate from Sequelize to Prisma ORM | Prisma Documentation](#how-to-migrate-from-sequelize-to-prisma-orm-prisma-documentation)
- [How to migrate from TypeORM to Prisma ORM | Prisma Documentation](#how-to-migrate-from-typeorm-to-prisma-orm-prisma-documentation)
- [How to use multiple databases in a single app | Prisma Documentation](#how-to-use-multiple-databases-in-a-single-app-prisma-documentation)
- [Set up PostgreSQL on Neon with Prisma Accelerate's Connection Pool | Prisma Documentation](#set-up-postgresql-on-neon-with-prisma-accelerate-s-connection-pool-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with Next.js 15 and Vercel | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-next-js-15-and-vercel-prisma-documentation)
- [Build a Nuxt app with Prisma ORM and Prisma Postgres | Prisma Documentation](#build-a-nuxt-app-with-prisma-orm-and-prisma-postgres-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with CPermit.io | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-cpermit-io-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with React Router 7 | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-react-router-7-prisma-documentation)
- [How to use Prisma Postgres with Shopify | Prisma Documentation](#how-to-use-prisma-postgres-with-shopify-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with SolidStart | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-solidstart-prisma-documentation)
- [Set up PostgreSQL on Supabase with Prisma Accelerate's Connection Pool | Prisma Documentation](#set-up-postgresql-on-supabase-with-prisma-accelerate-s-connection-pool-prisma-documentation)
- [Prisma Optimize | Prisma Documentation](#prisma-optimize-prisma-documentation)
- [Prisma Optimize: FAQ | Prisma Documentation](#prisma-optimize-faq-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with SvelteKit | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-sveltekit-prisma-documentation)
- [How to use Prisma ORM and Prisma Postgres with TanStack Start | Prisma Documentation](#how-to-use-prisma-orm-and-prisma-postgres-with-tanstack-start-prisma-documentation)
- [How to use Prisma ORM with Turborepo | Prisma Documentation](#how-to-use-prisma-orm-with-turborepo-prisma-documentation)
- [How to use Prisma ORM in a pnpm workspaces monorepo | Prisma Documentation](#how-to-use-prisma-orm-in-a-pnpm-workspaces-monorepo-prisma-documentation)
- [Optimize: Known limitations | Prisma Documentation](#optimize-known-limitations-prisma-documentation)
- [Optimize: Prisma AI | Prisma Documentation](#optimize-prisma-ai-prisma-documentation)
- [Getting started with Prisma Optimize | Prisma Documentation](#getting-started-with-prisma-optimize-prisma-documentation)
- [Optimize: Recordings | Prisma Documentation](#optimize-recordings-prisma-documentation)
---
# Search the documentation | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/search#__docusaurus_skipToContent_fallback)
Search the documentation
========================
[](https://www.algolia.com/)
---
# One doc tagged with "optimization" | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/tags/optimization#__docusaurus_skipToContent_fallback)
[Guides\
------](https://www.prisma.io/docs/guides)
Welcome to the Guides section! Here you'll find practical, step-by-step guides to help you accomplish specific tasks with Prisma products, including Prisma ORM, Prisma Accelerate, Prisma Postgres, and more.
---
# One doc tagged with "workflows" | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/tags/workflows#__docusaurus_skipToContent_fallback)
[Guides\
------](https://www.prisma.io/docs/guides)
Welcome to the Guides section! Here you'll find practical, step-by-step guides to help you accomplish specific tasks with Prisma products, including Prisma ORM, Prisma Accelerate, Prisma Postgres, and more.
---
# How to write guides for Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/making-guides#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/making-guides#introduction "Direct link to Introduction")
------------------------------------------------------------------------------------------------------------
This guide shows you how to write guides for Prisma ORM documentation. It covers the required structure, formatting, and style conventions to ensure consistency across all guides. You'll learn about frontmatter requirements, section organization, and writing style.
Prerequisites[](https://www.prisma.io/docs/guides/making-guides#prerequisites "Direct link to Prerequisites")
---------------------------------------------------------------------------------------------------------------
Before writing a guide, make sure you have:
* A clear understanding of the topic you're writing about
* Access to the Prisma documentation repository
* Familiarity with Markdown and MDX
* Knowledge of the target audience for your guide
Guide structure[](https://www.prisma.io/docs/guides/making-guides#guide-structure "Direct link to Guide structure")
---------------------------------------------------------------------------------------------------------------------
### Required frontmatter[](https://www.prisma.io/docs/guides/making-guides#required-frontmatter "Direct link to Required frontmatter")
Every guide must include the following frontmatter at the top of the file:
---title: 'How to [do something] with Prisma ORM'metaTitle: 'How to [do something] with Prisma ORM'description: 'Learn how to [do something] with Prisma ORM'sidebar_label: '[Concise Label]'image: '/img/guides/[guide-name]-cover.png'community_section: true---
* `title`: Should be action-oriented and start with "How to"
* `metaTitle`: Usually matches the title, used for SEO
* `description`: A one-sentence summary starting with "Learn how to", used for SEO
* `sidebar_label`: A concise label for the sidebar navigation
* `image`: A unique header image for social media sharing (coordinate with the design team)
All frontmatter fields should be in sentence case, except for `image`.
### Required sections[](https://www.prisma.io/docs/guides/making-guides#required-sections "Direct link to Required sections")
1. **Introduction**
* Brief overview of what the guide covers
* What the reader will learn/accomplish
* Link to any example repositories or related resources
2. **Prerequisites**
* Required software/tools with version numbers
* Required knowledge/experience
* Any necessary accounts or access
3. **Main content sections**
* Numbered steps for procedural guides (e.g., "1. Set up the project")
* Clear hierarchy with H2 (`##`) for main sections
* H3 (`###`) for subsections
* Each step should build on previous steps
4. **Next steps**
* What to do after completing the guide
* Related guides or documentation
* Links to additional resources
* Community resources (e.g., Discord)
Writing style and voice[](https://www.prisma.io/docs/guides/making-guides#writing-style-and-voice "Direct link to Writing style and voice")
---------------------------------------------------------------------------------------------------------------------------------------------
### General principles[](https://www.prisma.io/docs/guides/making-guides#general-principles "Direct link to General principles")
* Write in a clear, conversational tone
* Use active voice and present tense
* Address the reader directly using "you"
* Use first person plural ("we") when guiding the reader through steps
* Avoid jargon and explain technical terms
* Be concise but thorough
### Code examples[](https://www.prisma.io/docs/guides/making-guides#code-examples "Direct link to Code examples")
* Include complete, runnable code examples
* Use syntax highlighting with language specification
* Include file paths in code block metadata
* Use comments to explain complex parts
* Show both the problem and solution when applicable
Example:
src/index.ts
// Import required dependenciesimport { PrismaClient } from '@prisma/client'// Initialize Prisma Clientconst prisma = new PrismaClient()
### Formatting conventions[](https://www.prisma.io/docs/guides/making-guides#formatting-conventions "Direct link to Formatting conventions")
* Use backticks for:
* File names: \`schema.prisma\`
* Directory names: \`prisma/\`
* Code elements: \`PrismaClient\`
* Commands: \`npx prisma generate\`
* Use [admonitions](https://docusaurus.io/docs/markdown-features/admonitions)
for important notes, warnings, tips, etc.:
:::noteImportant information goes here:::
* Use proper heading hierarchy (never skip levels)
* Include line numbers in longer code blocks
* Use tabbed content for alternative approaches
Examples from existing guides[](https://www.prisma.io/docs/guides/making-guides#examples-from-existing-guides "Direct link to Examples from existing guides")
---------------------------------------------------------------------------------------------------------------------------------------------------------------
### Migration guide format[](https://www.prisma.io/docs/guides/making-guides#migration-guide-format "Direct link to Migration guide format")
Migration guides follow a specific pattern, as seen in guides like [Migrate from Sequelize](https://www.prisma.io/docs/guides/migrate-from-sequelize)
and [Migrate from Mongoose](https://www.prisma.io/docs/guides/migrate-from-mongoose)
:
1. Clear introduction explaining the migration path
2. Prerequisites specific to both ORMs
3. Step-by-step migration process
4. Code comparison between ORMs
5. Practical examples of common operations
### Integration guide format[](https://www.prisma.io/docs/guides/making-guides#integration-guide-format "Direct link to Integration guide format")
Integration guides, like [Using Prisma ORM with Cloudflare D1](https://www.prisma.io/docs/guides/cloudflare-d1)
, focus on:
1. Setup and configuration
2. Platform-specific considerations
3. Step-by-step implementation
4. Deployment instructions
5. Platform-specific best practices
Best practices[](https://www.prisma.io/docs/guides/making-guides#best-practices "Direct link to Best practices")
------------------------------------------------------------------------------------------------------------------
1. **Keep it focused**
* Each guide should cover one main topic
* Break complex topics into multiple guides
* Link to related guides instead of duplicating content
2. **Show don't tell**
* Include practical, real-world examples
* Provide complete, working code samples
* Explain why certain approaches are recommended
3. **Consider the context**
* Explain prerequisites clearly
* Don't assume prior knowledge
* Link to foundational concepts within or outside of our docs when needed
4. **Maintain consistency**
* Follow the established guide structure
* Use consistent terminology
* Match the style of existing guides
5. **Think about maintenance**
* Use version numbers where appropriate
* Avoid time-sensitive references
* Consider future updates when structuring content
Template[](https://www.prisma.io/docs/guides/making-guides#template "Direct link to Template")
------------------------------------------------------------------------------------------------
This is a template for a guide. It is to standarize the format of the guide, the prisma integration, and make it easier to write a guide.
Before you submit a PR, run through the checklist and make sure to read all Dev Note's and remove them.
To get the guide into the sidebar, you need to add the following to the `sidebars.ts` file:
sidebars.ts
{ type: "category", label: "Framework Guides", collapsed: false, collapsible: false, items: [ "guides/turborepo", "guides/nextjs", "guides/nuxt", "guides/tanstack-start", "guides/react-router-7", "guides/solid-start", "guides/sveltekit", "guides/__________", ].sort(),},
Copy and paste the template into a new `.mdx` file:
---title: 'How to use Prisma ORM with __________'metaTitle: 'How to use Prisma ORM and Prisma Postgres with __________'description: 'Learn how to use Prisma ORM in a __________ app'sidebar_label: '__________ with Prisma'image: '/img/guides/prisma-__________-cover.png'completion_time: '15 min'community_section: true---:::warningDEVELOPER CHECKLIST - Remove upon completion- [ ] `CTRL or CMD + F` to find 10 `_`'s and replace them with the framework name.- [ ] Provide a brief overview of the guide's purpose and the benefits of integrating Prisma ORM with the specified framework.- [ ] Link to the official documentation of the framework upon its first mention in the Introduction section.- [ ] List all necessary or recommended prerequisites, including specific software versions and any required accounts or services.- [ ] Name project *framework*-prisma (ie. *__________*-prisma)- [ ] Project creation options should be detailed in an info admonition in this format:```markdownmarkdown - *Which package manager would you like to use?* `npm` ```- [ ] Ensure the appropriate admonitions (note, warning, tip) are used for important information.- [ ] Include links to related guides and resources throughout the content.- [ ] Instead of using `we, we'll, ours, etc.` use `you, you'll, yours, etc.`- [ ] All lines ending before a code block should end with a colon (This one -> `:`):::## IntroductionPrisma ORM streamlines database access with type-safe queries, and when paired with [__________](https://example.com/), it creates a...:::warning***DEV NOTE:*** Above, briefly explain the benefits of using Prisma ORM with the specified framework after `it creates a...`:::In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in a __________ project from scratch. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/__________).## Prerequisites- [Node.js 18+](https://nodejs.org)## 1. Set up your project## 2. Install and Configure Prisma### 2.1. Install dependenciesTo get started with Prisma, you'll need to install a few dependencies:```terminalnpm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client``````terminalnpm install prisma tsx --save-devnpm install @prisma/client```Once installed, initialize Prisma in your project::::warning***DEV NOTE:*** Make sure you update the output path accordingly with the framework (ie. Next.js is `../app/generated/prisma`). and follow through with the proper import paths going forward. This template will be using `../generated/prisma`.:::```terminalnpx prisma init --db --output ../generated/prisma```:::infoYou'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My __________ Project":::This will create:- A `prisma` directory with a `schema.prisma` file.- A Prisma Postgres database.- A `.env` file containing the `DATABASE_URL` at the project root.- An `output` directory for the generated Prisma Client as `__________/generated/prisma`.### 2.2. Define your Prisma SchemaIn the `prisma/schema.prisma` file, add the following models::::warning***DEV NOTE:*** If using Vite, the generator client should not include `-js` in the provider:```prisma file=prisma/schema.prismagenerator client { //edit-next-line provider = "prisma-client" output = "../generated/prisma"}```In addition, update the text above this and add "*and change the generator to use the `prisma-client` provider*":::```prisma file=prisma/schema.prismagenerator client { provider = "prisma-client-js" output = "../generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}//add-startmodel User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}//add-end```This creates two models: `User` and `Post`, with a one-to-many relationship between them.### 2.3. Configure the Prisma Client generatorNow, run the following command to create the database tables and generate the Prisma Client:```terminalnpx prisma migrate dev --name init```### 2.4. Seed the databaseAdd some seed data to populate the database with sample users and posts.Create a new file called `seed.ts` in the `prisma/` directory:```typescript file=prisma/seed.tsimport { PrismaClient, Prisma } from "../generated/prisma";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();```Now, tell Prisma how to run this script by updating your `package.json`:```json file=package.json... rest of the file//add-start"prisma": { "seed": "tsx prisma/seed.ts"}//add-end... rest of the file```Run the seed script:```terminalnpx prisma db seed```And open Prisma Studio to inspect your data:```terminalnpx prisma studio```## 3. Integrate Prisma into __________### 3.1. Create a Prisma ClientCreate a `/lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance.Set up the Prisma client like this:```tsx file=src/lib/prisma.tsimport { PrismaClient } from "../generated/prisma";import { withAccelerate } from "@prisma/extension-accelerate";const prisma = new PrismaClient().$extends(withAccelerate());export default prisma;``````tsx file=src/lib/prisma.tsimport { PrismaClient } from "../generated/prisma";const prisma = new PrismaClient();export default prisma;```:::warningWe recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently.If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.:::### 3.2.:::warning***DEV NOTE:*** How do you implement prisma into the framework?:::You're done! You've just created a __________ app with Prisma ORM. Below are some next steps to explore, as well as some more resources to help you get started expanding your project.## Next StepsNow that you have a working __________ app connected to a Prisma Postgres database, you can:- Extend your Prisma schema with more models and relationships- Add create/update/delete routes and forms- Explore authentication and validation- Enable query caching with [Prisma Postgres](/postgres/database/caching) for better performance### More Info- [Prisma Documentation](/orm/overview/introduction)- [__________ Documentation](https://example.com/)
Next steps[](https://www.prisma.io/docs/guides/making-guides#next-steps "Direct link to Next steps")
------------------------------------------------------------------------------------------------------
After reading this guide, you can:
* Start writing your own guide using the provided structure
* Review existing guides for reference
* Request a unique header image for your guide
* Submit your guide for review
For more information:
* [Prisma documentation style guide](https://www.prisma.io/docs/about/style-guide)
* [Documentation components](https://www.prisma.io/docs/about/docs-components)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/making-guides%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/making-guides%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/making-guides%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/999-making-guides.mdx)
* [Introduction](https://www.prisma.io/docs/guides/making-guides#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/making-guides#prerequisites)
* [Guide structure](https://www.prisma.io/docs/guides/making-guides#guide-structure)
* [Required frontmatter](https://www.prisma.io/docs/guides/making-guides#required-frontmatter)
* [Required sections](https://www.prisma.io/docs/guides/making-guides#required-sections)
* [Writing style and voice](https://www.prisma.io/docs/guides/making-guides#writing-style-and-voice)
* [General principles](https://www.prisma.io/docs/guides/making-guides#general-principles)
* [Code examples](https://www.prisma.io/docs/guides/making-guides#code-examples)
* [Formatting conventions](https://www.prisma.io/docs/guides/making-guides#formatting-conventions)
* [Examples from existing guides](https://www.prisma.io/docs/guides/making-guides#examples-from-existing-guides)
* [Migration guide format](https://www.prisma.io/docs/guides/making-guides#migration-guide-format)
* [Integration guide format](https://www.prisma.io/docs/guides/making-guides#integration-guide-format)
* [Best practices](https://www.prisma.io/docs/guides/making-guides#best-practices)
* [Template](https://www.prisma.io/docs/guides/making-guides#template)
* [Next steps](https://www.prisma.io/docs/guides/making-guides#next-steps)
---
# How to use Prisma ORM with Cloudflare D1 | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/cloudflare-d1#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/cloudflare-d1#introduction "Direct link to Introduction")
------------------------------------------------------------------------------------------------------------
This guide shows you how to use Prisma ORM with Cloudflare D1, a serverless SQL database that runs on Cloudflare's edge network. You'll learn how to set up Prisma ORM with D1, handle migrations, and deploy your application to Cloudflare Workers. You can find a [deployment-ready example on GitHub](https://github.com/prisma/prisma-examples/blob/latest/deployment-platforms/edge/cloudflare-workers/with-d1)
.
Prerequisites[](https://www.prisma.io/docs/guides/cloudflare-d1#prerequisites "Direct link to Prerequisites")
---------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* A Cloudflare account
* Node.js installed (version 18 or higher)
* Wrangler CLI installed (version 3.39.0 or higher)
* Basic familiarity with Cloudflare Workers and D1
1\. Configure Prisma schema[](https://www.prisma.io/docs/guides/cloudflare-d1#1-configure-prisma-schema "Direct link to 1. Configure Prisma schema")
------------------------------------------------------------------------------------------------------------------------------------------------------
In your Prisma schema, add the `driverAdapters` Preview feature to the `generator` block and set the `provider` of the `datasource` to `sqlite`. If you just bootstrapped the Prisma schema with `prisma init`, also be sure to add the following `User` model to it:
schema.prisma
generator client { provider = "prisma-client-js" previewFeatures = ["driverAdapters"]}datasource db { provider = "sqlite" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String?}
2\. Install dependencies[](https://www.prisma.io/docs/guides/cloudflare-d1#2-install-dependencies "Direct link to 2. Install dependencies")
---------------------------------------------------------------------------------------------------------------------------------------------
Next, install the required packages:
npm install @prisma/adapter-d1
Also, be sure to use a version of the Wrangler CLI that's above [`wrangler@^3.39.0`](https://github.com/cloudflare/workers-sdk/releases/tag/wrangler%403.39.0)
, otherwise the `--remote` flag that's used in the next sections won't be available.
3\. Set up D1 database connection[](https://www.prisma.io/docs/guides/cloudflare-d1#3-set-up-d1-database-connection "Direct link to 3. Set up D1 database connection")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To connect your Workers with the D1 instance, add the following binding to your `wrangler.toml`:
wrangler.toml
name = "prisma-cloudflare-worker-example"main = "src/index.ts"compatibility_date = "2024-03-20"compatibility_flags = ["nodejs_compat"][[d1_databases]]binding = "DB" # i.e. available in your Worker on env.DBdatabase_name = "__YOUR_D1_DATABASE_NAME__" # to be replaceddatabase_id = "__YOUR_D1_DATABASE_ID__" # to be replaced
Note that `__YOUR_D1_DATABASE_NAME__` and `__YOUR_D1_DATABASE_ID__` in the snippet above are placeholders that should be replaced with the database name and ID of your own D1 instance.
If you weren't able to grab this ID from the terminal output, you can also find it in the Cloudflare Dashboard or by running `npx wrangler d1 list` and `npx wrangler d1 info __YOUR_D1_DATABASE_NAME__` in your terminal.
4\. Set up database migrations[](https://www.prisma.io/docs/guides/cloudflare-d1#4-set-up-database-migrations "Direct link to 4. Set up database migrations")
---------------------------------------------------------------------------------------------------------------------------------------------------------------
note
We recommend using `prisma migrate` in order to keep your data in D1 migrated. However, if you would prefer to use Cloudflare's migration system, [that workflow is also available](https://www.prisma.io/docs/orm/overview/databases/cloudflare-d1#using-the-wrangler-cli)
### 4.1 Add needed environment variables[](https://www.prisma.io/docs/guides/cloudflare-d1#41-add-needed-environment-variables "Direct link to 4.1 Add needed environment variables")
In order to use the Prisma D1 adapter, you'll need to add a few secrets to a `.env` file:
* `DATABASE_URL`: A path to your local D1 instance. Usually `"file:./prisma/db.sqlite"`.
* `CLOUDFLARE_ACCOUNT_ID`: Your Cloudflare account ID, fetched via `npx wrangler whoami`
* `CLOUDFLARE_DATABASE_ID`: The ID of your database, retrieved [during D1 database creation](https://www.prisma.io/docs/guides/cloudflare-d1#3-set-up-d1-database-connection)
.
* `CLOUDFLARE_D1_TOKEN`: This API token is used by Prisma ORM to communicate with your D1 instance directly. To create this, follow these steps:
1. Visit [https://dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens)
2. Click "Create Token"
3. Click "Custom token" template
4. Fill out the template: Make sure you use a recognizable name and add the `Account / D1 / Edit` permission.
5. Click "Continue to summary" and then "Create Token".
You can now store these secrets to be used by Prisma ORM. We recommend a `.env` file for local development, but any secret store will work.
.env
DATABASE_URL="file:./prisma/db.sqlite"CLOUDFLARE_ACCOUNT_ID="0773..."CLOUDFLARE_DATABASE_ID="01f30366-..."CLOUDFLARE_D1_TOKEN="F8Cg..."
### 4.2 Configure Prisma Config[](https://www.prisma.io/docs/guides/cloudflare-d1#42-configure-prisma-config "Direct link to 4.2 Configure Prisma Config")
Ensure that you have a `prisma.config.ts` file set up in the root of your project with a [migration driver adapter](https://www.prisma.io/docs/orm/reference/prisma-config-reference#adapter)
defined.
import path from 'node:path'import type { PrismaConfig } from 'prisma'import { PrismaD1 } from '@prisma/adapter-d1'// import your .env fileimport 'dotenv/config'type Env = { CLOUDFLARE_D1_TOKEN: string CLOUDFLARE_ACCOUNT_ID: string CLOUDFLARE_DATABASE_ID: string}export default { earlyAccess: true, schema: path.join('prisma', 'schema.prisma'), migrate: { async adapter(env) { return new PrismaD1({ CLOUDFLARE_D1_TOKEN: env.CLOUDFLARE_D1_TOKEN, CLOUDFLARE_ACCOUNT_ID: env.CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DATABASE_ID: env.CLOUDFLARE_DATABASE_ID, }) }, },} satisfies PrismaConfig
> **Note**: As of [Prisma ORM v6.11.0](https://github.com/prisma/prisma/releases/tag/6.11.0)
> , the D1 adapter has been renamed from `PrismaD1HTTP` to `PrismaD1`.
This will allow `prisma migrate` to interact with your D1 database.
### 4.3 Run your first migration[](https://www.prisma.io/docs/guides/cloudflare-d1#43-run-your-first-migration "Direct link to 4.3 Run your first migration")
You can now run `prisma migrate dev` to migrate your database to match your local schema:
npx prisma migrate dev --name init
Let's also create some dummy data that we can query once the Worker is running. This time, we'll use wrangler to run a SQL statement without storing it in a file:
# For the local databasenpx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES('jane@prisma.io', 'Jane Doe (Local)');" --local# For the remote databasenpx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES('jane@prisma.io', 'Jane Doe (Remote)');" --remote
5\. Implement the Worker[](https://www.prisma.io/docs/guides/cloudflare-d1#5-implement-the-worker "Direct link to 5. Implement the Worker")
---------------------------------------------------------------------------------------------------------------------------------------------
Before adding a Prisma Client query to your Worker, you need to generate Prisma Client with the following command:
npx prisma generate
In order to query your database from the Worker using Prisma ORM, you need to:
1. Add the `DB` binding to the `Env` interface. (Alternatively, you can run [`npx wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/#types)
to generate the `Env` type from the binding in a separate file called `worker-configuration.d.ts`.)
2. Instantiate `PrismaClient` using the `PrismaD1` driver adapter.
3. Send a query using Prisma Client and return the result.
Open `src/index.ts` and replace the entire content with the following:
src/index.ts
import { PrismaClient } from '@prisma/client'import { PrismaD1 } from '@prisma/adapter-d1'export interface Env { DB: D1Database}export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { const adapter = new PrismaD1(env.DB) const prisma = new PrismaClient({ adapter }) const users = await prisma.user.findMany() const result = JSON.stringify(users) return new Response(result) },}
6\. Run the Worker locally[](https://www.prisma.io/docs/guides/cloudflare-d1#6-run-the-worker-locally "Direct link to 6. Run the Worker locally")
---------------------------------------------------------------------------------------------------------------------------------------------------
With the database query in place and Prisma Client generated, you can go ahead and run the Worker locally:
npm run dev
Now you can open your browser at [`http://localhost:8787`](http://localhost:8787/)
to see the result of the database query:
;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Local)' }]
7\. Set the `DATABASE_URL` environment variable and deploy the Worker[](https://www.prisma.io/docs/guides/cloudflare-d1#7-set-the-database_url-environment-variable-and-deploy-the-worker "Direct link to 7-set-the-database_url-environment-variable-and-deploy-the-worker")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To deploy the Worker, run the the following command:
npm run deploy
Your deployed Worker is accessible via `https://prisma-d1-example.USERNAME.workers.dev`. If you navigate your browser to that URL, you should see the following data that's queried from your remote D1 database:
;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Remote)' }]
Next steps[](https://www.prisma.io/docs/guides/cloudflare-d1#next-steps "Direct link to Next steps")
------------------------------------------------------------------------------------------------------
Now that you've set up Prisma ORM with Cloudflare D1, you can:
* Add more complex queries using Prisma's powerful query API
* Set up Prisma Studio for database management
* Implement database monitoring
* Add automated tests
For more information:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
* [Cloudflare D1 documentation](https://developers.cloudflare.com/d1)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/cloudflare-d1%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/cloudflare-d1%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/cloudflare-d1%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/070-cloudflare-d1.mdx)
* [Introduction](https://www.prisma.io/docs/guides/cloudflare-d1#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/cloudflare-d1#prerequisites)
* [1\. Configure Prisma schema](https://www.prisma.io/docs/guides/cloudflare-d1#1-configure-prisma-schema)
* [2\. Install dependencies](https://www.prisma.io/docs/guides/cloudflare-d1#2-install-dependencies)
* [3\. Set up D1 database connection](https://www.prisma.io/docs/guides/cloudflare-d1#3-set-up-d1-database-connection)
* [4\. Set up database migrations](https://www.prisma.io/docs/guides/cloudflare-d1#4-set-up-database-migrations)
* [4.1 Add needed environment variables](https://www.prisma.io/docs/guides/cloudflare-d1#41-add-needed-environment-variables)
* [4.2 Configure Prisma Config](https://www.prisma.io/docs/guides/cloudflare-d1#42-configure-prisma-config)
* [4.3 Run your first migration](https://www.prisma.io/docs/guides/cloudflare-d1#43-run-your-first-migration)
* [5\. Implement the Worker](https://www.prisma.io/docs/guides/cloudflare-d1#5-implement-the-worker)
* [6\. Run the Worker locally](https://www.prisma.io/docs/guides/cloudflare-d1#6-run-the-worker-locally)
* [7\. Set the `DATABASE_URL` environment variable and deploy the Worker](https://www.prisma.io/docs/guides/cloudflare-d1#7-set-the-database_url-environment-variable-and-deploy-the-worker)
* [Next steps](https://www.prisma.io/docs/guides/cloudflare-d1#next-steps)
---
# How to provision preview databases with GitHub Actions and Prisma Postgres | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/github-actions#__docusaurus_skipToContent_fallback)
On this page
Overview[](https://www.prisma.io/docs/guides/github-actions#overview "Direct link to Overview")
-------------------------------------------------------------------------------------------------
This guide shows you how to automatically create and delete [Prisma Postgres](https://www.prisma.io/postgres)
databases using GitHub Actions and [the Prisma Postgres management API](https://api.prisma.io/v1/swagger-editor)
. The setup provisions a new database for every pull request, seeds it with sample data, and the `github-actions` bot leaves a comment with the database name and the status.

After the PR is closed, the database is automatically deleted. This allows you to test changes in isolation without affecting the main development database.
Prerequisites[](https://www.prisma.io/docs/guides/github-actions#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------
Make sure you have the following:
* Node.js 18 or later
* A account
* GitHub repository
1\. Set up your project[](https://www.prisma.io/docs/guides/github-actions#1-set-up-your-project "Direct link to 1. Set up your project")
-------------------------------------------------------------------------------------------------------------------------------------------
Initialize your project:
mkdir prisma-gha-demo && cd prisma-gha-demonpm init -y
2\. Install and configure Prisma[](https://www.prisma.io/docs/guides/github-actions#2-install-and-configure-prisma "Direct link to 2. Install and configure Prisma")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
In this section, you'll set up Prisma in your project and verify that it works locally before integrating it into GitHub Actions. This involves installing Prisma's dependencies, connecting to a Prisma Postgres database, defining your data models, applying your schema, and seeding the database with sample data.
By the end of this section, your project will be fully prepared to use Prisma both locally and in a CI workflow.
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/github-actions#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, install the required dependencies:
npm install @prisma/extension-accelerate @prisma/client
Install the development dependencies:
npm install prisma tsx dotenv --save-dev
Once installed, initialize Prisma:
npx prisma init --db --output ../src/generated/prisma
This creates:
* A `prisma/` directory with `schema.prisma`
* A `.env` file with `DATABASE_URL`
* A generated client in `src/generated/prisma`
### 2.2. Define your Prisma schema[](https://www.prisma.io/docs/guides/github-actions#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma schema")
Edit `prisma/schema.prisma` to:
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../src/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
### 2.3. Run initial migration and generate client[](https://www.prisma.io/docs/guides/github-actions#23-run-initial-migration-and-generate-client "Direct link to 2.3. Run initial migration and generate client")
npx prisma migrate dev --name init
This pushes your schema and prepares the client.
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/github-actions#24-seed-the-database "Direct link to 2.4. Seed the database")
Create a file at `src/seed.ts`:
src/seed.ts
import { withAccelerate } from "@prisma/extension-accelerate";import { PrismaClient } from "../src/generated/prisma/client";import "dotenv/config";const prisma = new PrismaClient().$extends(withAccelerate());const userData = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main() .catch(console.error) .finally(() => prisma.$disconnect());
Update your `package.json`:
package.json
{ { "name": "prisma-gha-demo", "version": "1.0.0", "description": "", "scripts": { "seed": "tsx src/seed.ts" }, // other configurations...}
Then run:
npm run seednpx prisma studio
Navigate to `http://localhost:5555` and verify that the database has been seeded with sample data. Now you're ready to automate this process with GitHub Actions.
3\. Add the GitHub Actions workflow[](https://www.prisma.io/docs/guides/github-actions#3-add-the-github-actions-workflow "Direct link to 3. Add the GitHub Actions workflow")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In this step, you will set up a GitHub Actions workflow that automatically provisions a Prisma Postgres database when a new pull request (PR) is opened. Once the PR is closed, the workflow will clean up the database.
### 3.1 Create the workflow file[](https://www.prisma.io/docs/guides/github-actions#31-create-the-workflow-file "Direct link to 3.1 Create the workflow file")
Start by creating the required directory and file:
mkdir -p .github/workflowstouch .github/workflows/prisma-postgres-management.yml
This file will contain the logic to manage databases on a per-PR basis. This GitHub Actions workflow:
* Provisions a temporary Prisma Postgres database when a PR is opened
* Seeds the database with test data
* Cleans up the database when the PR is closed
* Supports manual execution for both provisioning and cleanup
note
This workflow uses `us-east-1` as the default region for Prisma Postgres. You can change this to your preferred region by modifying the `region` parameter in the API calls, or even by adding a `region` input to the workflow.
### 3.2. Add the base configuration[](https://www.prisma.io/docs/guides/github-actions#32-add-the-base-configuration "Direct link to 3.2. Add the base configuration")
Paste the following into `.github/workflows/prisma-postgres-management.yml`. This sets up when the workflow runs and provides required environment variables.
.github/workflows/prisma-postgres-management.yml
name: Prisma Postgres Management API Workflowon: pull_request: types: [opened, reopened, closed] workflow_dispatch: inputs: action: description: "Action to perform" required: true default: "provision" type: choice options: - provision - cleanup database_name: description: "Database name (for testing, will be sanitized)" required: false type: stringenv: PRISMA_POSTGRES_SERVICE_TOKEN: ${{ secrets.PRISMA_POSTGRES_SERVICE_TOKEN }} PRISMA_PROJECT_ID: ${{ secrets.PRISMA_PROJECT_ID }} # Sanitize database name once at workflow level DB_NAME: ${{ github.event.pull_request.number != null && format('pr-{0}-{1}', github.event.pull_request.number, github.event.pull_request.head.ref) || (inputs.database_name != '' && inputs.database_name || format('test-{0}', github.run_number)) }}# Prevent concurrent runs of the same PRconcurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true
Now you will be adding the provision and cleanup jobs to this workflow. These jobs will handle the creation and deletion of Prisma Postgres databases based on the pull request events.
### 3.3. Add a provision job to the workflow[](https://www.prisma.io/docs/guides/github-actions#33-add-a-provision-job-to-the-workflow "Direct link to 3.3. Add a provision job to the workflow")
Now add a job to provision the database when the PR is opened or when triggered manually. The provision job:
* Installs dependencies
* Checks for existing databases
* Creates a new one if needed
* Seeds the database
* Comments on the PR with status
Append the following under the `jobs:` key in your workflow file:
.github/workflows/prisma-postgres-management.yml
jobs: provision-database: if: (github.event_name == 'pull_request' && github.event.action != 'closed') || (github.event_name == 'workflow_dispatch' && inputs.action == 'provision') runs-on: ubuntu-latest permissions: write-all timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: "22" cache: "npm" - name: Install Dependencies run: npm install - name: Validate Environment Variables run: | if [ -z "${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" ]; then echo "Error: PRISMA_POSTGRES_SERVICE_TOKEN secret is not set" exit 1 fi if [ -z "${{ env.PRISMA_PROJECT_ID }}" ]; then echo "Error: PRISMA_PROJECT_ID secret is not set" exit 1 fi - name: Sanitize Database Name run: | # Sanitize the database name to match Prisma's requirements DB_NAME="$(echo "${{ env.DB_NAME }}" | tr '/' '_' | tr '-' '_' | tr '[:upper:]' '[:lower:]')" echo "DB_NAME=$DB_NAME" >> $GITHUB_ENV - name: Check If Database Exists id: check-db run: | echo "Fetching all databases..." RESPONSE=$(curl -s -X GET \ -H "Authorization: Bearer ${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" \ -H "Content-Type: application/json" \ "https://api.prisma.io/v1/projects/${{ env.PRISMA_PROJECT_ID }}/databases") echo "Looking for database with name: ${{ env.DB_NAME }}" # Extract database ID using jq to properly parse JSON DB_EXISTS=$(echo "$RESPONSE" | jq -r ".data[]? | select(.name == \"${{ env.DB_NAME }}\") | .id") if [ ! -z "$DB_EXISTS" ] && [ "$DB_EXISTS" != "null" ]; then echo "Database ${{ env.DB_NAME }} exists with ID: $DB_EXISTS." echo "exists=true" >> $GITHUB_OUTPUT echo "db-id=$DB_EXISTS" >> $GITHUB_OUTPUT else echo "No existing database found with name ${{ env.DB_NAME }}" echo "exists=false" >> $GITHUB_OUTPUT fi - name: Create Database id: create-db if: steps.check-db.outputs.exists != 'true' run: | echo "Creating database ${{ env.DB_NAME }}..." RESPONSE=$(curl -s -X POST \ -H "Authorization: Bearer ${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" \ -H "Content-Type: application/json" \ -d "{\"name\": \"${{ env.DB_NAME }}\", \"region\": \"us-east-1\"}" \ "https://api.prisma.io/v1/projects/${{ env.PRISMA_PROJECT_ID }}/databases") # Check if response contains an id (success case) if echo "$RESPONSE" | grep -q '"id":'; then echo "Database created successfully" CONNECTION_STRING=$(echo "$RESPONSE" | jq -r '.data.connectionString') echo "connection-string=$CONNECTION_STRING" >> $GITHUB_OUTPUT else echo "Failed to create database" echo "$RESPONSE" exit 1 fi - name: Get Connection String for Existing Database id: get-connection if: steps.check-db.outputs.exists == 'true' run: | echo "Creating new connection string for existing database..." CONNECTION_RESPONSE=$(curl -s -X POST \ -H "Authorization: Bearer ${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" \ -H "Content-Type: application/json" \ -d '{"name":"read_write_key"}' \ "https://api.prisma.io/v1/databases/${{ steps.check-db.outputs.db-id }}/connections") CONNECTION_STRING=$(echo "$CONNECTION_RESPONSE" | jq -r '.data.connectionString') echo "connection-string=$CONNECTION_STRING" >> $GITHUB_OUTPUT - name: Setup Database Schema run: | # Get connection string from appropriate step if [ "${{ steps.check-db.outputs.exists }}" = "true" ]; then CONNECTION_STRING="${{ steps.get-connection.outputs.connection-string }}" else CONNECTION_STRING="${{ steps.create-db.outputs.connection-string }}" fi # Set the DATABASE_URL export DATABASE_URL="$CONNECTION_STRING" # Generate Prisma Client npx prisma generate # Push schema to database npx prisma db push - name: Seed Database run: | # Get connection string from appropriate step if [ "${{ steps.check-db.outputs.exists }}" = "true" ]; then CONNECTION_STRING="${{ steps.get-connection.outputs.connection-string }}" else CONNECTION_STRING="${{ steps.create-db.outputs.connection-string }}" fi # Set the DATABASE_URL environment variable for the seed script export DATABASE_URL="$CONNECTION_STRING" # Generate Prisma Client npx prisma generate # Run the seed script npm run seed - name: Comment PR if: success() && github.event_name == 'pull_request' uses: actions/github-script@v7 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `🗄️ Database provisioned successfully!\n\nDatabase name: ${{ env.DB_NAME }}\nStatus: Ready and seeded with sample data` }) - name: Output Database Info if: success() && github.event_name == 'workflow_dispatch' run: | echo "🗄️ Database provisioned successfully!" echo "Database name: ${{ env.DB_NAME }}" echo "Status: Ready and seeded with sample data"
### 3.4. Add a cleanup job to the workflow[](https://www.prisma.io/docs/guides/github-actions#34-add-a-cleanup-job-to-the-workflow "Direct link to 3.4. Add a cleanup job to the workflow")
When a pull request is closed, you can automatically remove the associated database by adding a cleanup job. The cleanup job:
* Finds the database by name
* Deletes it from the Prisma Postgres project
* Can also be triggered manually with `action: cleanup`
Append the following to your `jobs:` section, after the `provision-database` job:
.github/workflows/prisma-postgres-management.yml
cleanup-database: if: (github.event_name == 'pull_request' && github.event.action == 'closed') || (github.event_name == 'workflow_dispatch' && inputs.action == 'cleanup') runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout uses: actions/checkout@v4 - name: Validate Environment Variables run: | if [ -z "${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" ]; then echo "Error: PRISMA_POSTGRES_SERVICE_TOKEN secret is not set" exit 1 fi if [ -z "${{ env.PRISMA_PROJECT_ID }}" ]; then echo "Error: PRISMA_PROJECT_ID secret is not set" exit 1 fi - name: Sanitize Database Name run: | # Sanitize the database name DB_NAME="$(echo "${{ env.DB_NAME }}" | tr '/' '_' | tr '-' '_' | tr '[:upper:]' '[:lower:]')" echo "DB_NAME=$DB_NAME" >> $GITHUB_ENV - name: Delete Database run: | echo "Fetching all databases..." RESPONSE=$(curl -s -X GET \ -H "Authorization: Bearer ${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" \ -H "Content-Type: application/json" \ "https://api.prisma.io/v1/projects/${{ env.PRISMA_PROJECT_ID }}/databases") echo "Looking for database with name: ${{ env.DB_NAME }}" # Extract database ID using jq to properly parse JSON DB_EXISTS=$(echo "$RESPONSE" | jq -r ".data[]? | select(.name == \"${{ env.DB_NAME }}\") | .id") if [ ! -z "$DB_EXISTS" ] && [ "$DB_EXISTS" != "null" ]; then echo "Database ${{ env.DB_NAME }} exists with ID: $DB_EXISTS. Deleting..." DELETE_RESPONSE=$(curl -s -X DELETE \ -H "Authorization: Bearer ${{ env.PRISMA_POSTGRES_SERVICE_TOKEN }}" \ -H "Content-Type: application/json" \ "https://api.prisma.io/v1/databases/$DB_EXISTS") echo "Delete API Response: $DELETE_RESPONSE" if echo "$DELETE_RESPONSE" | grep -q '"error":'; then ERROR_MSG=$(echo "$DELETE_RESPONSE" | jq -r '.message // "Unknown error"') echo "Failed to delete database: $ERROR_MSG" exit 1 else echo "Database deletion initiated successfully" fi else echo "No existing database found with name ${{ env.DB_NAME }}" fi
This completes your Prisma Postgres management workflow setup. In the next step, you'll configure the required GitHub secrets to authenticate with the Prisma API.
4\. Store the code in GitHub[](https://www.prisma.io/docs/guides/github-actions#4-store-the-code-in-github "Direct link to 4. Store the code in GitHub")
----------------------------------------------------------------------------------------------------------------------------------------------------------
Initialize a git repository and push to [GitHub](https://github.com/)
:
If you don't have a repository in GitHub yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)
. Once the repository is ready, run the following commands:
git add .git commit -m "Initial commit with Prisma Postgres integration"git branch -M maingit remote add origin https://github.com//.gitgit push -u origin main
note
Replace `` and `` with your GitHub username and the name of your repository.
5\. Retrieve the secrets for the workflow[](https://www.prisma.io/docs/guides/github-actions#5-retrieve-the-secrets-for-the-workflow "Direct link to 5. Retrieve the secrets for the workflow")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 5.1. Retrieve your Prisma Postgres service token[](https://www.prisma.io/docs/guides/github-actions#51-retrieve-your-prisma-postgres-service-token "Direct link to 5.1. Retrieve your Prisma Postgres service token")
To manage Prisma Postgres databases, you also need a service token. Follow these steps to retrieve it:
1. Make sure you are in the same workspace where you created your project in the last step.
2. Click on **Integrations** in the left sidebar.
3. Click on **New service token** button.
4. In the popup, enter a descriptive name in the **Token name** field.
5. Click the **Create service token** button.
6. Copy the generated token and save it in your `.env` file as `PRISMA_POSTGRES_SERVICE_TOKEN`. This token is required for the next step's script and must also be added to your GitHub Actions secrets.
### 5.2 Retrieve the project ID where you want to provision Prisma Postgres databases[](https://www.prisma.io/docs/guides/github-actions#52-retrieve-the-project-id-where-you-want-to-provision-prisma-postgres-databases "Direct link to 5.2 Retrieve the project ID where you want to provision Prisma Postgres databases")
To avoid conflicts with your development databases, you'll now create a dedicated project specifically for CI workflows. Use the following curl command to create a new Prisma Postgres project using the Prisma Postgres Management API:
curl -X POST https://api.prisma.io/v1/projects \ -H "Authorization: Bearer $PRISMA_POSTGRES_SERVICE_TOKEN" \ -H "Content-Type: application/json" \ -d "{\"region\": \"us-east-1\", \"name\": \"$PROJECT_NAME\"}"
note
Make sure to replace the `$PRISMA_POSTGRES_SERVICE_TOKEN` variable with the service token you stored earlier.
Replace the $PRISMA\_POSTGRES\_SERVICE\_TOKEN with the service token and the `$PROJECT_NAME` with a name for your project (e.g., `my-gha-preview`). The script will create a new Prisma Postgres project in the `us-east-1` region.
The CLI output will then look like this:
{ "data": { "id": "$PRISMA_PROJECT_ID", "type": "project", "name": "$PROJECT_NAME", "createdAt": "2025-07-15T08:35:10.546Z", "workspace": { "id": "$PRISMA_WORKSPACE_ID", "name": "$PRISMA_WORKSPACE_NAME" } }}
Copy and store the `$PRISMA_PROJECT_ID` from the output. This is your Prisma project ID, which you will use in the next step.
6\. Add secrets in GitHub[](https://www.prisma.io/docs/guides/github-actions#6-add-secrets-in-github "Direct link to 6. Add secrets in GitHub")
-------------------------------------------------------------------------------------------------------------------------------------------------
To add secrets:
1. Go to your GitHub repository.
2. Navigate to **Settings**.
3. Click and expand the **Secrets and variables** section.
4. Click **Actions**.
5. Click **New repository secret**.
6. Add the following:
* `PRISMA_PROJECT_ID` - Your Prisma project ID from the Prisma Console.
* `PRISMA_POSTGRES_SERVICE_TOKEN` - Your service token.
These secrets will be accessed in the workflow file via `env`.
7\. Try the workflow[](https://www.prisma.io/docs/guides/github-actions#7-try-the-workflow "Direct link to 7. Try the workflow")
----------------------------------------------------------------------------------------------------------------------------------
You can test the setup in two ways:
**Option 1: Automatic trigger via PR**
1. Open a pull request on the repository.
2. GitHub Actions will provision a new Prisma Postgres database.
3. It will push your schema and seed the database.
4. A comment will be added to the PR confirming database creation.
5. When the PR is closed, the database will be deleted automatically.
**Option 2: Manual trigger**
1. Go to the **Actions** tab in your repository.
2. Select the **Prisma Postgres Management API Workflow** on the left sidebar.
3. Click the **Run workflow** dropdown
4. Choose `provision` as the action and optionally provide a custom database name. You can also choose `cleanup` to delete an _existing_ database.
5. Click **Run workflow**.
Next steps[](https://www.prisma.io/docs/guides/github-actions#next-steps "Direct link to Next steps")
-------------------------------------------------------------------------------------------------------
You now have a fully automated GitHub Actions setup for managing ephemeral Prisma Postgres databases.
This gives you:
* Isolated databases for every pull request.
* Automatic schema sync and seed.
* Cleanup of unused databases after merges.
This setup improves confidence in changes and reduces the risk of shared database conflicts. You can extend this by integrating test suites, or integrating it in your workflow.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/github-actions%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/github-actions%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/github-actions%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/330-github-actions.mdx)
* [Overview](https://www.prisma.io/docs/guides/github-actions#overview)
* [Prerequisites](https://www.prisma.io/docs/guides/github-actions#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/github-actions#1-set-up-your-project)
* [2\. Install and configure Prisma](https://www.prisma.io/docs/guides/github-actions#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/github-actions#21-install-dependencies)
* [2.2. Define your Prisma schema](https://www.prisma.io/docs/guides/github-actions#22-define-your-prisma-schema)
* [2.3. Run initial migration and generate client](https://www.prisma.io/docs/guides/github-actions#23-run-initial-migration-and-generate-client)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/github-actions#24-seed-the-database)
* [3\. Add the GitHub Actions workflow](https://www.prisma.io/docs/guides/github-actions#3-add-the-github-actions-workflow)
* [3.1 Create the workflow file](https://www.prisma.io/docs/guides/github-actions#31-create-the-workflow-file)
* [3.2. Add the base configuration](https://www.prisma.io/docs/guides/github-actions#32-add-the-base-configuration)
* [3.3. Add a provision job to the workflow](https://www.prisma.io/docs/guides/github-actions#33-add-a-provision-job-to-the-workflow)
* [3.4. Add a cleanup job to the workflow](https://www.prisma.io/docs/guides/github-actions#34-add-a-cleanup-job-to-the-workflow)
* [4\. Store the code in GitHub](https://www.prisma.io/docs/guides/github-actions#4-store-the-code-in-github)
* [5\. Retrieve the secrets for the workflow](https://www.prisma.io/docs/guides/github-actions#5-retrieve-the-secrets-for-the-workflow)
* [5.1. Retrieve your Prisma Postgres service token](https://www.prisma.io/docs/guides/github-actions#51-retrieve-your-prisma-postgres-service-token)
* [5.2 Retrieve the project ID where you want to provision Prisma Postgres databases](https://www.prisma.io/docs/guides/github-actions#52-retrieve-the-project-id-where-you-want-to-provision-prisma-postgres-databases)
* [6\. Add secrets in GitHub](https://www.prisma.io/docs/guides/github-actions#6-add-secrets-in-github)
* [7\. Try the workflow](https://www.prisma.io/docs/guides/github-actions#7-try-the-workflow)
* [Next steps](https://www.prisma.io/docs/guides/github-actions#next-steps)
---
# Partner Database Provisioning & User Claim Flow | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/management-api#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/management-api#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------
This guide walks you through how to use the Prisma Postgres Management API, to power experiences like the [`npx create-db`](https://create-db.prisma.io/)
command.
You'll learn how to provision a Prisma Postgres database on your workspace as a partner, and how to transfer it to another user's workspace so they can "claim" the database. We'll cover how the process is secured using OAuth2, and by the end, you'll understand the full flow and how to integrate it into your own product experience.
This guide references the actual implementation in the `npx create-db` CLI and Cloudflare Workers as real world examples. The repo for the `npx create-db` is [here](https://github.com/prisma/create-db)
, which can be used as a reference for how to use the Management API in your own projects.
How does this fit into your app?
The two Cloudflare Workers in this guide are just reference examples. You would typically build this logic into your own backend or serverless functions.
Similarly, the `npx create-db` CLI is a simple demo. In your product, you can trigger the same API calls from your own UI or onboarding flows to create a seamless experience for your users.
Core Concepts[](https://www.prisma.io/docs/guides/management-api#core-concepts "Direct link to Core Concepts")
----------------------------------------------------------------------------------------------------------------
Before diving into implementation, let's clarify the main concepts involved in the Management API integration:
* **Management API**: A set of endpoints that allow to programmatically provision and manage Prisma Postgres databases.
* **Projects vs Databases**: A project is a container that can hold multiple databases. You can use this to organize databases you create e.g. by user. Projects can then be transferred to users, including all databases they contain.
* **Authentication**: All API requests require authentication. As a partner, you use OAuth2 to obtain integration tokens (for your app) and facilitate secure transfers to your users.
* **Tokens**: There are two main types of tokens:
* **Integration Token**: Issued to your partner integration, scoped to provision and manage databases on your own workspace.
* **User Access Token**: Obtained via OAuth2 when a user authenticates with your app, scoped to the user's workspace and can be used to transfer database ownership to the user's workspace.
How to become a partner[](https://www.prisma.io/docs/guides/management-api#how-to-become-a-partner "Direct link to How to become a partner")
----------------------------------------------------------------------------------------------------------------------------------------------
To use the Prisma Postgres Management API, you first need to set up as a partner:
1. **Request access to the Management API**: Contact the Prisma team from the [Prisma Partners page](https://www.prisma.io/partners)
to request access to the Management API. You will be guided through the onboarding process.
2. **Obtain OAuth credentials**: Once approved, you will receive an OAuth client ID and client secret. These credentials are required to authenticate your integration and enable secure database transfers for your users.
For a complete list of available endpoints and details on request/response formats, see the [Prisma Management API documentation](https://www.prisma.io/docs/postgres/introduction/management-api)
.
Provisioning a Database as a Partner[](https://www.prisma.io/docs/guides/management-api#provisioning-a-database-as-a-partner "Direct link to Provisioning a Database as a Partner")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To provision a new Prisma Postgres database for your users as a partner, follow these steps:
1. **Gather required information**: Prepare the necessary details for provisioning, such as region, database name, and any other options your application requires. This information may come from user input or be determined by your application logic.
2. **Authenticate your integration**: Use your integration token (obtained via OAuth2) to authenticate API requests. This token authenticates your app as an approved partner.
3. **Send a database provisioning request**: Make a `POST` request to the Management API endpoint to create a new project with a default database. For example:
const prismaResponse = await fetch('https://api.prisma.io/v1/projects', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer `, }, body: JSON.stringify({ region, name }),});
4. **Handle the response**: If successful, the API will return the new project's details, including database connection strings and a `project_id`. Store these securely and display them to your user as needed.
5. **(Optional) Store project metadata**: You may want to associate the `project_id` with your user in your own database for future reference.
Database Claim Flow[](https://www.prisma.io/docs/guides/management-api#database-claim-flow "Direct link to Database Claim Flow")
----------------------------------------------------------------------------------------------------------------------------------
Once a database is provisioned, you may want to transfer ownership to your user at a later point so they can manage it in their own Prisma workspace and go beyond the free database usage limits. This is done via the claim flow, which consists of three main steps:
### Overview: How the Claim Flow Works[](https://www.prisma.io/docs/guides/management-api#overview-how-the-claim-flow-works "Direct link to Overview: How the Claim Flow Works")
When a user wants to claim a database, your app will:
1. Trigger the OAuth2 flow, redirecting the user to Prisma Auth. This is necessary, so your app will have the permissions to transfer the database into the user's workspace.
2. The user authenticates and selects a workspace.
3. Your backend receives an authorization code, exchanges it for a user access token, and calls the Management API transfer endpoint with both your integration token and the user's token.
This ensures the transfer is secure and only the intended user can claim the database.
### 1\. Triggering the Claim Flow[](https://www.prisma.io/docs/guides/management-api#1-triggering-the-claim-flow "Direct link to 1. Triggering the Claim Flow")
When your user wants to take ownership of a database you provisioned for them, they need to transfer it to their own Prisma Postgres workspace. This gives them full control over it.
To initiate this process, provide a button or link in your app (e.g., "Claim Database" or "Transfer to My Workspace"). When clicked, your backend should:
* Generate a secure `state` value to track the session and prevent CSRF attacks.
* Construct an OAuth2 authorization URL with your client ID, redirect URI, and required scopes.
* Redirect the user to this URL to begin the authentication flow.
Example:
const authParams = new URLSearchParams({ client_id: YOUR_CLIENT_ID, redirect_uri: 'https://your-app.com/auth/callback', // Your callback endpoint response_type: 'code', scope: 'workspace:admin', // The scope of the OAuth2 authorization state: generateState(), // Securely track the session});const authUrl = `https://auth.prisma.io/authorize?${authParams.toString()}`;// Redirect the user to authUrl
### 2\. Authenticating the User[](https://www.prisma.io/docs/guides/management-api#2-authenticating-the-user "Direct link to 2. Authenticating the User")
The user will be prompted to log in (if not already authenticated) and select the workspace where they want to claim the database. After successful authentication and workspace selection, Prisma Auth will redirect back to your callback endpoint with a `code` and `state` (and, in some cases, a `project_id`).
### 3\. Finishing the Claim Flow[](https://www.prisma.io/docs/guides/management-api#3-finishing-the-claim-flow "Direct link to 3. Finishing the Claim Flow")
Your backend should now:
1. **Exchange the authorization code for a user access token**:
const tokenResponse = await fetch('https://auth.prisma.io/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code: code, // The code received from the callback redirect_uri: 'https://your-app.com/auth/callback', // Must match the redirect_uri used in step 1 client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, }).toString(),});const tokenData = await tokenResponse.json();
2. **Call the Management API transfer endpoint** to move the project to the selected workspace. You will need the `project_id` and the user's access token:
const transferResponse = await fetch(`https://api.prisma.io/v1/projects/${project_id}/transfer`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${YOUR_INTEGRATION_TOKEN}`, }, body: JSON.stringify({ recipientAccessToken: tokenData.access_token }),});
If the transfer is successful, the database is now owned by the user's workspace.
Conclusion[](https://www.prisma.io/docs/guides/management-api#conclusion "Direct link to Conclusion")
-------------------------------------------------------------------------------------------------------
By following this guide, you have learned how to:
* Set up as a Prisma Postgres Partner and obtain the necessary credentials
* Provision a new database for your users using the Management API
* Implement a secure claim flow that allows users to claim ownership of a database in their own workspace using OAuth2
This flow enables you to integrate Prisma Postgres provisioning and transfer seamlessly into your own product, providing a smooth onboarding experience for your users.
For further details, see the [create-db](https://github.com/prisma/create-db)
repo for a reference implementation, or consult the [Prisma Management API documentation](https://www.prisma.io/docs/postgres/introduction/management-api)
.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/management-api%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/management-api%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/management-api%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/240-management-api.mdx)
* [Introduction](https://www.prisma.io/docs/guides/management-api#introduction)
* [Core Concepts](https://www.prisma.io/docs/guides/management-api#core-concepts)
* [How to become a partner](https://www.prisma.io/docs/guides/management-api#how-to-become-a-partner)
* [Provisioning a Database as a Partner](https://www.prisma.io/docs/guides/management-api#provisioning-a-database-as-a-partner)
* [Database Claim Flow](https://www.prisma.io/docs/guides/management-api#database-claim-flow)
* [Overview: How the Claim Flow Works](https://www.prisma.io/docs/guides/management-api#overview-how-the-claim-flow-works)
* [1\. Triggering the Claim Flow](https://www.prisma.io/docs/guides/management-api#1-triggering-the-claim-flow)
* [2\. Authenticating the User](https://www.prisma.io/docs/guides/management-api#2-authenticating-the-user)
* [3\. Finishing the Claim Flow](https://www.prisma.io/docs/guides/management-api#3-finishing-the-claim-flow)
* [Conclusion](https://www.prisma.io/docs/guides/management-api#conclusion)
---
# Get started with the Prisma Management API | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/management-api-basic#__docusaurus_skipToContent_fallback)
On this page
Overview[](https://www.prisma.io/docs/guides/management-api-basic#overview "Direct link to Overview")
-------------------------------------------------------------------------------------------------------
This guide walks you through setting up a basic TypeScript project that uses the [Prisma Postgres Management API](https://www.prisma.io/docs/postgres/introduction/management-api)
to create a new [Prisma Console project](https://www.prisma.io/docs/platform/about#project)
with a [Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/overview)
database, and print out all connection details.
You'll authenticate via a [service token](https://www.prisma.io/docs/postgres/introduction/management-api#bearer-tokens)
, set up your environment, and run a script to interact with the API.
OpenApi
The API reference is also available via an [OpenAPI 3.1. spec](https://api.prisma.io/v1/swagger-editor)
.
Prerequisites[](https://www.prisma.io/docs/guides/management-api-basic#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------------
* Node.js and `npm` installed
* A account
1\. Create a service token in Prisma Console[](https://www.prisma.io/docs/guides/management-api-basic#1-create-a-service-token-in-prisma-console "Direct link to 1. Create a service token in Prisma Console")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
First, you need to create a service token to be able to access the Management API:
1. Open the
2. Navigate to the **Integrations** page of your workspace
3. Click **Generate integration token**
4. Copy and save the generated service token securely, you'll use it in step 2.2.
2\. Set up your project directory[](https://www.prisma.io/docs/guides/management-api-basic#2-set-up-your-project-directory "Direct link to 2. Set up your project directory")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Create a basic TypeScript project[](https://www.prisma.io/docs/guides/management-api-basic#21-create-a-basic-typescript-project "Direct link to 2.1. Create a basic TypeScript project")
Open your terminal and run the following commands:
mkdir management-api-democd management-api-demo
Next, initialize npm and install dependencies required for using TypeScript:
npm init -ynpm install tsx typescript @types/node --save-devtouch index.ts
You now have an `index.ts` file that you can execute with `npx tsx index.ts`. It's still empty, you'll start writing code in step 3.
### 2.2. Configure service token environment variable[](https://www.prisma.io/docs/guides/management-api-basic#22-configure-service-token-environment-variable "Direct link to 2.2. Configure service token environment variable")
Create your `.env` file:
touch .env
Next, install the [`dotenv`](https://github.com/motdotla/dotenv)
library for loading environment variables from the `.env` file:
npm install dotenv
Finally, add your service token (from step 1.) to `.env`:
PRISMA_SERVICE_TOKEN="ey..."
### 2.3. Install the `axios` library for HTTP request[](https://www.prisma.io/docs/guides/management-api-basic#23-install-the-axios-library-for-http-request "Direct link to 23-install-the-axios-library-for-http-request")
You're going to use [`axios`](https://github.com/axios/axios/tree/main)
as your HTTP client to interact with the Management API. Install it as follows:
npm install axios
You're all set, let's write some code to create a project and provision a Prisma Postgres database!
3\. Programmatically create a new project with a database[](https://www.prisma.io/docs/guides/management-api-basic#3-programmatically-create-a-new-project-with-a-database "Direct link to 3. Programmatically create a new project with a database")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Paste the following code into `index.ts`:
import axios from 'axios';import dotenv from 'dotenv';// Load environment variablesdotenv.config();const API_URL = 'https://api.prisma.io/v1';const SERVICE_TOKEN = process.env.PRISMA_SERVICE_TOKEN;if (!SERVICE_TOKEN) { throw new Error('PRISMA_SERVICE_TOKEN is not set in the environment');}// Set HTTP headers to be used in this scriptconst headers = { Authorization: `Bearer ${SERVICE_TOKEN}`, 'Content-Type': 'application/json',};async function main() { // Create a new project in your Prisma Console workspace const projectName = `demo-project-${Date.now()}`; const region = 'us-east-1'; const createProjectRes = await axios.post( `${API_URL}/projects`, { name: projectName, region }, { headers } ); const project = createProjectRes.data; console.log('Created project: \n', project); // Log the database details const apiKeys = project.databases[0].apiKeys || []; for (const key of apiKeys) { console.log(`\nDatabase details`); console.log(`- ID: ${key.id}`); console.log(`- Created at: ${key.createdAt}`); console.log(`- API key: ${key.apiKey}`); console.log(`- Prisma Postgres connection string: ${key.connectionString}`); if (key.ppgDirectConnection) { console.log(`- Direct TCP connection: ${key.ppgDirectConnection.host}`); console.log(` - Host: ${key.ppgDirectConnection.host}`); console.log(` - Username: ${key.ppgDirectConnection.user}`); console.log(` - Password: ${key.ppgDirectConnection.pass}`); } }}main().catch((e) => { console.error(e.response?.data || e); process.exit(1);});
You can run your script with the following command:
npx tsx index.ts
Show CLI results
Created project: { createdAt: '2025-07-09T11:52:15.341Z', id: 'cmcvwftgs00v5zq0vh3kp7pms', name: 'demo-project-1752061932800', databases: [ { createdAt: '2025-07-09T11:52:15.341Z', id: 'cmcvwftgs00v1zq0v0qrtrg8t', name: 'demo-project-1752061932800', connectionString: 'prisma+postgres://accelerate.prisma-data.net/?api_key=', region: 'us-east-1', status: 'ready', apiKeys: [Array], isDefault: true } ]}Database details- ID: cmcvwftgs00v2zq0vj3v0104j- Created at: 2025-07-09T11:52:15.341Z- API key: ey...- Prisma Postgres connection string: prisma+postgres://accelerate.prisma-data.net/?api_key=ey...- Direct TCP connection: db.prisma.io:5432 - Host: db.prisma.io:5432 - Username: - Password:
Your output of the command should look similar to the output above.
Conclusion[](https://www.prisma.io/docs/guides/management-api-basic#conclusion "Direct link to Conclusion")
-------------------------------------------------------------------------------------------------------------
You have now set up a TypeScript project that interacts with the Prisma Management API, creates a new project and database, and prints out all connection strings. You can extend this script to manage more resources or automate other tasks using the Management API.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/management-api-basic%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/management-api-basic%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/management-api-basic%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/330-management-api-basic.mdx)
* [Overview](https://www.prisma.io/docs/guides/management-api-basic#overview)
* [Prerequisites](https://www.prisma.io/docs/guides/management-api-basic#prerequisites)
* [1\. Create a service token in Prisma Console](https://www.prisma.io/docs/guides/management-api-basic#1-create-a-service-token-in-prisma-console)
* [2\. Set up your project directory](https://www.prisma.io/docs/guides/management-api-basic#2-set-up-your-project-directory)
* [2.1. Create a basic TypeScript project](https://www.prisma.io/docs/guides/management-api-basic#21-create-a-basic-typescript-project)
* [2.2. Configure service token environment variable](https://www.prisma.io/docs/guides/management-api-basic#22-configure-service-token-environment-variable)
* [2.3. Install the `axios` library for HTTP request](https://www.prisma.io/docs/guides/management-api-basic#23-install-the-axios-library-for-http-request)
* [3\. Programmatically create a new project with a database](https://www.prisma.io/docs/guides/management-api-basic#3-programmatically-create-a-new-project-with-a-database)
* [Conclusion](https://www.prisma.io/docs/guides/management-api-basic#conclusion)
---
# How to manage schema changes in a team with Prisma Migrate and Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/implementing-schema-changes#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/implementing-schema-changes#introduction "Direct link to Introduction")
--------------------------------------------------------------------------------------------------------------------------
When working in a team, managing database schema changes can be challenging. This guide shows you how to effectively collaborate on schema changes using Prisma Migrate, ensuring that all team members can safely contribute to and incorporate schema changes.
Prerequisites[](https://www.prisma.io/docs/guides/implementing-schema-changes#prerequisites "Direct link to Prerequisites")
-----------------------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* Node.js installed (version 18 or higher)
* A Prisma project set up with migrations
* A relational database (PostgreSQL, MySQL, SQLite, SQL Server, etc.)
* Basic understanding of Git
* Basic familiarity with Prisma Migrate
warning
This guide **does not apply for MongoDB**.
Instead of `migrate dev`, [`db push`](https://www.prisma.io/docs/orm/prisma-migrate/workflows/prototyping-your-schema)
is used for [MongoDB](https://www.prisma.io/docs/orm/overview/databases/mongodb)
.
1\. Understand migration basics[](https://www.prisma.io/docs/guides/implementing-schema-changes#1-understand-migration-basics "Direct link to 1. Understand migration basics")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 1.1. Migration order[](https://www.prisma.io/docs/guides/implementing-schema-changes#11-migration-order "Direct link to 1.1. Migration order")
Migrations are **applied in the same order as they were created**. The creation date is part of the migration subfolder name - for example, `20210316081837-updated-fields` was created on `2021-03-16-08:18:37`.
### 1.2. Source control requirements[](https://www.prisma.io/docs/guides/implementing-schema-changes#12-source-control-requirements "Direct link to 1.2. Source control requirements")
You should commit the following files to source control:
* The contents of the `.prisma/migrations` folder, including the `migration_lock.toml` file
* The Prisma Schema (`schema.prisma`)
Source-controlling the `schema.prisma` file is not enough - you must include your migration history because:
* Customized migrations contain information that cannot be represented in the Prisma schema
* The `prisma migrate deploy` command only runs migration files
2\. Incorporate team changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#2-incorporate-team-changes "Direct link to 2. Incorporate team changes")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Pull latest changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#21-pull-latest-changes "Direct link to 2.1. Pull latest changes")
To incorporate changes from collaborators:
1. Pull the changed Prisma schema and `./prisma/migrations` folder
2. Run the migrate command:
npx prisma migrate dev
### 2.2. Example scenario[](https://www.prisma.io/docs/guides/implementing-schema-changes#22-example-scenario "Direct link to 2.2. Example scenario")
Let's walk through a sample scenario with three developers sharing schema changes:
* Before
* After
schema.prisma
model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int?}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}
schema.prisma
model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int?}model User { id Int @id @default(autoincrement()) email String @unique name String? favoriteColor String? // Added by Ania bestPacmanScore Int? // Added by you posts Post[]}// Added by Javiermodel Tag { tagName String @id tagCategory Category}
3\. Handle concurrent changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#3-handle-concurrent-changes "Direct link to 3. Handle concurrent changes")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Developer A's changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#31-developer-as-changes "Direct link to 3.1. Developer A's changes")
Ania adds a new field:
model User { /* ... */ favoriteColor String?}
And generates a migration:
npx prisma migrate dev --name new-field
### 3.2. Developer B's changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#32-developer-bs-changes "Direct link to 3.2. Developer B's changes")
Javier adds a new model:
model Tag { tagName String @id tagCategory Category}
And generates a migration:
npx prisma migrate dev --name new-model
### 3.3. Merge changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#33-merge-changes "Direct link to 3.3. Merge changes")
The migration history now has two new migrations:

4\. Integrate your changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#4-integrate-your-changes "Direct link to 4. Integrate your changes")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
### 4.1. Pull team changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#41-pull-team-changes "Direct link to 4.1. Pull team changes")
1. Pull the most recent changes:
* Two new migrations
* Updated schema file
2. Review the merged schema:
model User { /* ... */ favoriteColor String? bestPacmanScore Int?}model Tag { tagName String @id tagCategory Category posts Post[]}
### 4.2. Generate your migration[](https://www.prisma.io/docs/guides/implementing-schema-changes#42-generate-your-migration "Direct link to 4.2. Generate your migration")
Run the migrate command:
npx prisma migrate dev
This will:
1. Apply your team's migrations
2. Create a new migration for your changes
3. Apply your new migration
### 4.3. Commit changes[](https://www.prisma.io/docs/guides/implementing-schema-changes#43-commit-changes "Direct link to 4.3. Commit changes")
Commit:
* The merged `schema.prisma`
* Your new migration file
Next steps[](https://www.prisma.io/docs/guides/implementing-schema-changes#next-steps "Direct link to Next steps")
--------------------------------------------------------------------------------------------------------------------
Now that you understand team schema management, you can:
* Learn about [customizing migrations](https://www.prisma.io/docs/orm/prisma-migrate/workflows/customizing-migrations)
* Explore [deployment workflows](https://www.prisma.io/docs/orm/prisma-migrate/workflows/development-and-production)
For more information:
* [Prisma Migrate documentation](https://www.prisma.io/docs/orm/prisma-migrate)
* [Team development workflows](https://www.prisma.io/docs/orm/prisma-migrate/workflows/team-development)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/implementing-schema-changes%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/implementing-schema-changes%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/implementing-schema-changes%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/020-implementing-schema-changes.mdx)
* [Introduction](https://www.prisma.io/docs/guides/implementing-schema-changes#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/implementing-schema-changes#prerequisites)
* [1\. Understand migration basics](https://www.prisma.io/docs/guides/implementing-schema-changes#1-understand-migration-basics)
* [1.1. Migration order](https://www.prisma.io/docs/guides/implementing-schema-changes#11-migration-order)
* [1.2. Source control requirements](https://www.prisma.io/docs/guides/implementing-schema-changes#12-source-control-requirements)
* [2\. Incorporate team changes](https://www.prisma.io/docs/guides/implementing-schema-changes#2-incorporate-team-changes)
* [2.1. Pull latest changes](https://www.prisma.io/docs/guides/implementing-schema-changes#21-pull-latest-changes)
* [2.2. Example scenario](https://www.prisma.io/docs/guides/implementing-schema-changes#22-example-scenario)
* [3\. Handle concurrent changes](https://www.prisma.io/docs/guides/implementing-schema-changes#3-handle-concurrent-changes)
* [3.1. Developer A's changes](https://www.prisma.io/docs/guides/implementing-schema-changes#31-developer-as-changes)
* [3.2. Developer B's changes](https://www.prisma.io/docs/guides/implementing-schema-changes#32-developer-bs-changes)
* [3.3. Merge changes](https://www.prisma.io/docs/guides/implementing-schema-changes#33-merge-changes)
* [4\. Integrate your changes](https://www.prisma.io/docs/guides/implementing-schema-changes#4-integrate-your-changes)
* [4.1. Pull team changes](https://www.prisma.io/docs/guides/implementing-schema-changes#41-pull-team-changes)
* [4.2. Generate your migration](https://www.prisma.io/docs/guides/implementing-schema-changes#42-generate-your-migration)
* [4.3. Commit changes](https://www.prisma.io/docs/guides/implementing-schema-changes#43-commit-changes)
* [Next steps](https://www.prisma.io/docs/guides/implementing-schema-changes#next-steps)
---
# How to use Prisma in Docker | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/docker#__docusaurus_skipToContent_fallback)
On this page
This guide walks you through setting up a Prisma ORM application within a Docker environment. You'll learn how to configure a Node.js project, integrate Prisma for database management, and orchestrate the application using Docker Compose. By the end, you'll have a fully functional Prisma application running in a Docker container.
Prerequisites[](https://www.prisma.io/docs/guides/docker#prerequisites "Direct link to Prerequisites")
--------------------------------------------------------------------------------------------------------
* [Docker](https://docs.docker.com/)
and [Docker Compose](https://docs.docker.com/compose/)
installed
* Node.js version: A [compatible Node.js version](https://www.prisma.io/docs/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-6#minimum-supported-nodejs-versions)
, required for Prisma 6.
Before starting, ensure that no PostgreSQL services are running locally, and that the following ports are free to avoid conflicts: `5432` (PostgreSQL), `3000` (application server) or `5555` (Prisma Studio server).
To stop existing PostgreSQL services, use:
sudo systemctl stop postgresql # Linuxbrew services stop postgresql # macOSnet stop postgresql # Windows (Run as Administrator)
To stop all running Docker containers and free up ports:
docker ps -q | xargs docker stop
1\. Set up your Node.js and Prisma application[](https://www.prisma.io/docs/guides/docker#1-set-up-your-nodejs-and-prisma-application "Direct link to 1. Set up your Node.js and Prisma application")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Let's start by creating a simple Node.js application with Prisma ORM and [Express.js](https://expressjs.com/)
.
### 1.1. Initialize your project[](https://www.prisma.io/docs/guides/docker#11-initialize-your-project "Direct link to 1.1. Initialize your project")
First, create a new project directory and initialize a Node.js project:
mkdir docker-testcd docker-testnpm init -y
This will generate a `package.json` file:
package.json
{ "name": "docker-test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {}, "keywords": [], "author": "", "license": "ISC"}
### 1.2. Install required dependencies[](https://www.prisma.io/docs/guides/docker#12-install-required-dependencies "Direct link to 1.2. Install required dependencies")
Next, install the Prisma CLI as a development dependency and Express.js for the server:
npm install prisma --save-dev && npm install @prisma/clientnpm install express
### 1.3. Set up Prisma ORM[](https://www.prisma.io/docs/guides/docker#13-set-up-prisma-orm "Direct link to 1.3. Set up Prisma ORM")
Now, initialize Prisma to generate the necessary files:
npx prisma init --output ../generated/prisma
This creates:
* A `prisma` folder containing `schema.prisma`, where you will define your database schema.
* An `.env` file in the project root, which stores environment variables.
Add a `User` model to the `schema.prisma` file located in the `prisma/schema.prisma` folder:
prisma/schema.prisma
datasource db { provider = "postgresql" url = env("DATABASE_URL")}generator client { provider = "prisma-client-js" output = "../generated/prisma_client"}model User { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) email String @unique name String?}
note
In the `schema.prisma` file, we specify a [custom `output` path](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
where Prisma will generate its types. This ensures Prisma's types are resolved correctly across different package managers and can be accessed by application consistently inside the container without any permission issues. In this guide, the types will be generated in the `./generated/prisma_client` directory.
### 1.4. Create an Express.js server[](https://www.prisma.io/docs/guides/docker#14-create-an-expressjs-server "Direct link to 1.4. Create an Express.js server")
With the Prisma schema in place, let's create an Express.js server to interact with the database. Start by creating an `index.js` file:
touch index.js
Add the following code to set up a basic Express server:
index.js
const express = require("express");const { PrismaClient } = require("./generated/prisma_client");const app = express();const prisma = new PrismaClient();app.use(express.json());// Get all usersapp.get("/", async (req, res) => { const userCount = await prisma.user.count(); res.json( userCount == 0 ? "No users have been added yet." : "Some users have been added to the database." );});const PORT = 3000;app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`);});
Update the `package.json` scripts to include commands for running the server and deploying migrations:
package.json
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "node index.js", "db:deploy": "npx prisma migrate deploy && npx prisma generate"}
Now that the application is set up, let's move on to configuring a PostgreSQL database using Docker Compose.
2\. Set up a PostgreSQL database with Docker Compose[](https://www.prisma.io/docs/guides/docker#2-set-up-a-postgresql-database-with-docker-compose "Direct link to 2. Set up a PostgreSQL database with Docker Compose")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To perform database migrations, we'll create a standalone PostgreSQL database using Docker Compose.
### 2.1. Create a Docker Compose file for PostgreSQL[](https://www.prisma.io/docs/guides/docker#21-create-a-docker-compose-file-for-postgresql "Direct link to 2.1. Create a Docker Compose file for PostgreSQL")
Create a `docker-compose.postgres.yml` file in the root directory:
docker-compose.postgres.yml
version: '3.7'services: postgres: image: postgres:15 restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=prisma ports: - "5432:5432" networks: - prisma-network healthcheck: test: ["CMD-SHELL", "pg_isready -U prisma -d postgres"] interval: 5s timeout: 2s retries: 20 volumes: - postgres_data:/var/lib/postgresql/data command: postgres -c listen_addresses='*' logging: options: max-size: "10m" max-file: "3"networks: prisma-network:volumes: postgres_data:
### 2.2. Start the PostgreSQL container[](https://www.prisma.io/docs/guides/docker#22-start-the-postgresql-container "Direct link to 2.2. Start the PostgreSQL container")
Run the following command to start the database:
docker compose -f docker-compose.postgres.yml up -d
### 2.3. Perform database migrations[](https://www.prisma.io/docs/guides/docker#23-perform-database-migrations "Direct link to 2.3. Perform database migrations")
With the database running, update the `.env` file with the following database connection url:
.env
DATABASE_URL="postgresql://postgres:prisma@localhost:5432/postgres?schema=public"
Run the migration to create the database schema:
npx prisma migrate dev --name init
This should generate a `migrations` folder in the `prisma` folder.
### 2.4. Test the application[](https://www.prisma.io/docs/guides/docker#24-test-the-application "Direct link to 2.4. Test the application")
Start the server and verify it works:
npm run dev
Visit [`http://localhost:3000`](http://localhost:3000/)
to see the message:
No users have been added yet.
Stop the local server.
### 2.5. Clean up the standalone database[](https://www.prisma.io/docs/guides/docker#25-clean-up-the-standalone-database "Direct link to 2.5. Clean up the standalone database")
Once testing is complete, remove the standalone PostgreSQL container:
docker compose -f docker-compose.postgres.yml down --remove-orphans
This command will:
* Stop running containers.
* Remove containers.
* Remove the default network created by Docker Compose.
* Remove associated volumes (if not named explicitly).
Now that we've tested the application locally, let's containerize it using Docker.
3\. Run the app and database together with Docker Compose[](https://www.prisma.io/docs/guides/docker#3-run-the-app-and-database-together-with-docker-compose "Direct link to 3. Run the app and database together with Docker Compose")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
We'll now containerize the application using Docker, ensuring it can run in any environment.
To do that create a `Dockerfile` in project root:
touch Dockerfile
For the next step, you'll need to choose between two options for the base image: `node:alpine` (lightweight) or `node:slim` (stable). Both options are fully supported by Prisma ORM, but may have to be configured differently.
### 3.1. Option 1: Use Linux Alpine (`node:alpine`) as a base image[](https://www.prisma.io/docs/guides/docker#31-option-1-use-linux-alpine-nodealpine-as-a-base-image "Direct link to 31-option-1-use-linux-alpine-nodealpine-as-a-base-image")
The node:alpine image is based on Alpine Linux, a lightweight Linux distribution that uses the `musl` C standard library. It's perfect if you want to keep your container small and efficient. Prisma supports Alpine on `amd64` out of the box, and supports it on `arm64` since `prisma@4.10.0`.
Add the following content to the `Dockerfile`:
Dockerfile
FROM node:lts-alpine3.17WORKDIR /usr/src/appCOPY package.json package-lock.json ./RUN npm ciCOPY . .CMD ["sh", "-c", "npm run db:deploy && npm run dev"]
note
When running on Linux Alpine, Prisma downloads engines that are compiled for the `musl` C standard library. Please don't install `glibc` on Alpine (e.g., via the `libc6-compat` package), as that would prevent Prisma from running successfully.
Related Docker images:
* `node:lts-alpine`
* `node:16-alpine`
* `node:14-alpine`
### 3.1. Option 2: Use Linux Debian (`node:slim`) as a base image[](https://www.prisma.io/docs/guides/docker#31-option-2-use-linux-debian-nodeslim-as-a-base-image "Direct link to 31-option-2-use-linux-debian-nodeslim-as-a-base-image")
The `node:slim` image is based on Linux Debian, a stable and widely supported distribution that uses the `glibc` C standard library. It is mostly supported out of the box on `amd64` and `arm64`, making it a good choice if you're running into compatibility issues with Alpine or need a more production-ready environment. However, some older versions of this image may come without `libssl` installed, so it's sometimes necessary to install it manually.
Add the following content to the `Dockerfile`:
Dockerfile
FROM node:slimRUN apt-get update -y \&& apt-get install -y opensslWORKDIR /usr/src/appCOPY package.json package-lock.json ./RUN npm ciCOPY . .CMD ["sh", "-c", "npm run db:deploy && npm run dev"]
Related Docker images:
* `node:lts-slim`
* `node:bullseye-slim`
* `node:buster-slim`
* `node:stretch-slim`
### 3.2. Create and configure a Docker Compose file[](https://www.prisma.io/docs/guides/docker#32-create-and-configure-a-docker-compose-file "Direct link to 3.2. Create and configure a Docker Compose file")
Now that the `Dockerfile` is ready, we'll use Docker Compose to manage both the app and the database together. This makes it easy to start, stop, and manage the entire setup.
Create a `docker-compose.yml` file in your project folder:
touch docker-compose.yml
Add the following configuration to the file:
docker-compose.yml
version: '3.7'services: postgres_db: image: postgres:15 hostname: postgres_db container_name: postgres_db restart: always environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: prisma ports: - '5432:5432' networks: - prisma-network healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] interval: 5s timeout: 2s retries: 20 server: build: context: . dockerfile: Dockerfile ports: - '3000:3000' stdin_open: true tty: true # Keeps the container running for debugging depends_on: postgres_db: condition: service_healthy env_file: - .env.prod networks: - prisma-networknetworks: prisma-network: name: prisma-network
### 3.3. Configure environment variable for the container[](https://www.prisma.io/docs/guides/docker#33-configure-environment-variable-for-the-container "Direct link to 3.3. Configure environment variable for the container")
Before running the app, we need to configure the environment variables. Create a `.env.prod` file:
touch .env.prod
Add the following database connection url to the `.env.prod` file:
.env.prod
DATABASE_URL="postgresql://postgres:prisma@postgres_db:5432/postgres?schema=public"
### 3.4. Build and run the application[](https://www.prisma.io/docs/guides/docker#34-build-and-run-the-application "Direct link to 3.4. Build and run the application")
With everything set up, it's time to build and run the app using Docker Compose. Run the following command:
docker compose -f docker-compose.yml up --build -d
Visit `http://localhost:3000` to see your app running with the message:
No users have been added yet.
### 3.5. Bonus: Add Prisma Studio for database management[](https://www.prisma.io/docs/guides/docker#35-bonus-add-prisma-studio-for-database-management "Direct link to 3.5. Bonus: Add Prisma Studio for database management")
[Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
offers a graphical user interface (GUI) that allows you to view and manage your database directly in the browser. It's a great tool for debugging and managing your data during development.
To add Prisma Studio to your Docker setup, update the `docker-compose.yml` file:
docker.compose.yml
version: '3.7'services: postgres_db: image: postgres:15 hostname: postgres_db container_name: postgres_db restart: always environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: prisma ports: - '5432:5432' networks: - prisma-network healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] interval: 5s timeout: 2s retries: 20 server: build: context: . dockerfile: Dockerfile ports: - '3000:3000' stdin_open: true tty: true # Keeps the container running for debugging depends_on: postgres_db: condition: service_healthy env_file: - .env.prod networks: - prisma-network prisma-studio: image: node:lts-alpine3.17 working_dir: /usr/src/app volumes: - .:/usr/src/app command: npx prisma studio --port 5555 --browser none ports: - "5555:5555" env_file: - .env.prod networks: - prisma-network depends_on: postgres_db: condition: service_healthy server: condition: service_startednetworks: prisma-network: name: prisma-network
This will start Prisma Studio at [`http://localhost:5555`](http://localhost:5555/)
alongside the main app at [`http://localhost:3000`](http://localhost:3000/)
. You can use Prisma Studio to manage your database with a GUI.
Run the following command to start everything:
docker compose -f docker-compose.yml up --build -d
By following this guide, you've successfully containerized your Prisma app and database using Docker Compose.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/docker%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/docker%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/docker%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/130-docker.mdx)
* [Prerequisites](https://www.prisma.io/docs/guides/docker#prerequisites)
* [1\. Set up your Node.js and Prisma application](https://www.prisma.io/docs/guides/docker#1-set-up-your-nodejs-and-prisma-application)
* [1.1. Initialize your project](https://www.prisma.io/docs/guides/docker#11-initialize-your-project)
* [1.2. Install required dependencies](https://www.prisma.io/docs/guides/docker#12-install-required-dependencies)
* [1.3. Set up Prisma ORM](https://www.prisma.io/docs/guides/docker#13-set-up-prisma-orm)
* [1.4. Create an Express.js server](https://www.prisma.io/docs/guides/docker#14-create-an-expressjs-server)
* [2\. Set up a PostgreSQL database with Docker Compose](https://www.prisma.io/docs/guides/docker#2-set-up-a-postgresql-database-with-docker-compose)
* [2.1. Create a Docker Compose file for PostgreSQL](https://www.prisma.io/docs/guides/docker#21-create-a-docker-compose-file-for-postgresql)
* [2.2. Start the PostgreSQL container](https://www.prisma.io/docs/guides/docker#22-start-the-postgresql-container)
* [2.3. Perform database migrations](https://www.prisma.io/docs/guides/docker#23-perform-database-migrations)
* [2.4. Test the application](https://www.prisma.io/docs/guides/docker#24-test-the-application)
* [2.5. Clean up the standalone database](https://www.prisma.io/docs/guides/docker#25-clean-up-the-standalone-database)
* [3\. Run the app and database together with Docker Compose](https://www.prisma.io/docs/guides/docker#3-run-the-app-and-database-together-with-docker-compose)
* [3.1. Option 1: Use Linux Alpine (`node:alpine`) as a base image](https://www.prisma.io/docs/guides/docker#31-option-1-use-linux-alpine-nodealpine-as-a-base-image)
* [3.1. Option 2: Use Linux Debian (`node:slim`) as a base image](https://www.prisma.io/docs/guides/docker#31-option-2-use-linux-debian-nodeslim-as-a-base-image)
* [3.2. Create and configure a Docker Compose file](https://www.prisma.io/docs/guides/docker#32-create-and-configure-a-docker-compose-file)
* [3.3. Configure environment variable for the container](https://www.prisma.io/docs/guides/docker#33-configure-environment-variable-for-the-container)
* [3.4. Build and run the application](https://www.prisma.io/docs/guides/docker#34-build-and-run-the-application)
* [3.5. Bonus: Add Prisma Studio for database management](https://www.prisma.io/docs/guides/docker#35-bonus-add-prisma-studio-for-database-management)
---
# Datadog tracing with Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/data-dog#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/data-dog#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------
In this guide, you'll learn how to set up Datadog tracing for a new Prisma project. By combining the `@prisma/instrumentation` package with Prisma Client extensions, you can capture detailed spans for every database query. These spans are enriched with query metadata and sent to Datadog [using `dd-trace`](https://www.npmjs.com/package/dd-trace)
, Datadog's official APM library for Node.js, enabling you to monitor, analyze, and gain visibility into your application's database activity.
### What are spans and tracing?[](https://www.prisma.io/docs/guides/data-dog#what-are-spans-and-tracing "Direct link to What are spans and tracing?")
* **Spans** are the individual operations or units of work within a distributed system or complex application. Each database query, service call, or external request is represented by a span.
* **Tracing** ties these spans together to form a complete, end-to-end picture of a request’s lifecycle. With tracing, you can visualize bottlenecks, identify problematic queries, and pinpoint where errors occur from your queries.
### Why use Datadog with Prisma ORM?[](https://www.prisma.io/docs/guides/data-dog#why-use-datadog-with-prisma-orm "Direct link to Why use Datadog with Prisma ORM?")
[Datadog](https://www.datadoghq.com/)
provides application performance monitoring (APM), metrics, logs, and dashboards to help you observe and debug production systems.
While Prisma ORM abstracts away SQL and boosts developer productivity, it can obscure query performance without proper instrumentation. By integrating Datadog with Prisma using `@prisma/instrumentation` and [`dd-trace`](https://www.npmjs.com/package/dd-trace)
, you can automatically capture spans for every database query.
This enables you to:
* Measure latency per query.
* Inspect query arguments and raw SQL.
* Trace Prisma operations in the context of application-level requests.
* Identify bottlenecks related to database access.
This integration provides runtime visibility into Prisma queries with minimal effort, helping you catch slow queries and errors in real time.
Prerequisites[](https://www.prisma.io/docs/guides/data-dog#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------
Before you begin, ensure you have the following:
* **Node.js** installed (v18+ recommended).
* A local or hosted **PostgreSQL** database.
* A **Datadog** account. If you do not have one, [sign up here](https://www.datadoghq.com/)
.
* The **Datadog Agent** installed and running on your machine or server where this application will run. You can follow the [Datadog Agent installation docs](https://docs.datadoghq.com/agent/)
to set it up.
1\. Create a new project[](https://www.prisma.io/docs/guides/data-dog#1-create-a-new-project "Direct link to 1. Create a new project")
----------------------------------------------------------------------------------------------------------------------------------------
We will start by creating a new Node.js project to demonstrate tracing with Datadog and Prisma ORM. This will be a minimal, standalone setup focused on running and tracing Prisma queries, to understand the instrumentation flow in isolation.
If you're integrating tracing into an existing Prisma project, you can skip this step and directly follow from [the setup tracing section](https://www.prisma.io/docs/guides/data-dog#4-set-up-datadog-tracing)
. Just make sure you apply the changes in your project's equivalent folder structure.
mkdir prisma-datadog-tracingcd prisma-datadog-tracingnpm init -y
In this setup, you'll:
* Define a Prisma schema with basic models.
* Connect to a Postgres database (Prisma Postgres or your own).
* Configure Datadog tracing for all queries using `@prisma/instrumentation` and `dd-trace`.
* Run a sample script that executes Prisma operations and sends spans to Datadog.
2\. Set up Prisma ORM[](https://www.prisma.io/docs/guides/data-dog#2-set-up-prisma-orm "Direct link to 2. Set up Prisma ORM")
-------------------------------------------------------------------------------------------------------------------------------
In this section, you will install Prisma, create your schema, and generate the Prisma Client. This prepares your application to run database queries—queries that you will trace with Datadog.
### 2.1. Install and initialize Prisma ORM[](https://www.prisma.io/docs/guides/data-dog#21-install-and-initialize-prisma-orm "Direct link to 2.1. Install and initialize Prisma ORM")
Run the following commands to install Prisma and a minimal TypeScript runner:
npm install -D prisma tsx
Then initialize Prisma:
note
You can use the `--db` flag to create a [new Prisma Postgres](https://www.prisma.io/docs/postgres)
instance when initializing Prisma in your project.
* Prisma Postgres (recommended)
* Your own database
npx prisma init --db --output ../src/generated/prisma
note
You will be prompted to name your database and select the closest region. For clarity, choose a memorable name (e.g., `My Datadog Project`).
npx prisma init --output ../src/generated/prisma
This command does the following:
* Creates a `prisma` directory with a `schema.prisma` file.
* Generates the Prisma Client in the `/src/generated/prisma` directory (as specified in the `--output` flag).
* Creates a `.env` file at the project root with your database connection string (`DATABASE_URL`).
If you did not use the `--db` flag, replace the placeholder database URL in the `.env` file:
* Prisma Postgres
* Your own database
.env
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=..."
.env
# Placeholder url you have to replace DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample"
If you're using Prisma Postgres, also install:
npm i @prisma/extension-accelerate
This extension enables you to [cache your Prisma queries](https://www.prisma.io/docs/postgres/database/caching)
.
### 2.2. Define models[](https://www.prisma.io/docs/guides/data-dog#22-define-models "Direct link to 2.2. Define models")
Now, open `prisma/schema.prisma` and update your generator block and models. Replace the `generator` block with the following, and add a `User` and a `Post` model:
prisma/schema.prisma
generator client { provider = "prisma-client-js" output = "../src/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
### 2.3. Generate the Prisma Client and run migrations[](https://www.prisma.io/docs/guides/data-dog#23-generate-the-prisma-client-and-run-migrations "Direct link to 2.3. Generate the Prisma Client and run migrations")
Generate the Prisma Client and apply your schema to your database:
npx prisma generatenpx prisma migrate dev --name "init"
This creates the tables according to your schema in the Postgres database and generates a client for you to interact with the database.
3\. Install required dependencies for tracing[](https://www.prisma.io/docs/guides/data-dog#3-install-required-dependencies-for-tracing "Direct link to 3. Install required dependencies for tracing")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In addition to Prisma, you will need the following packages for Datadog tracing:
npm install @prisma/instrumentation \ dd-trace
Also ensure you have development dependencies for TypeScript:
npm install -D typescript
Here's a quick overview:
* **`@prisma/instrumentation`**: Instruments Prisma queries so they appear as spans in your tracer.
* **`dd-trace`**: Official Node.js tracing library from Datadog.
4\. Set up Datadog tracing[](https://www.prisma.io/docs/guides/data-dog#4-set-up-datadog-tracing "Direct link to 4. Set up Datadog tracing")
----------------------------------------------------------------------------------------------------------------------------------------------
Create a `tracer.ts` file in the `src` folder to instantiate your tracing logic:
touch src/tracer.ts
### 4.1. Configure the tracer[](https://www.prisma.io/docs/guides/data-dog#41-configure-the-tracer "Direct link to 4.1. Configure the tracer")
Open `src/tracer.ts` and add the following code:
src/tracer.ts
import Tracer from "dd-trace";import { PrismaInstrumentation, registerInstrumentations,} from "@prisma/instrumentation";const tracer = Tracer.init({ apmTracingEnabled: true, service: "prisma-datadog-tracing", version: "1.0.0", profiling: true});const provider = new tracer.TracerProvider();// Register the provider globallyprovider.register();registerInstrumentations({ instrumentations: [ new PrismaInstrumentation({ enabled: true, }), ], tracerProvider: provider,});export { tracer };
note
If you encounter a linting error on the line `traceProvider: provider` due to incompatible types, it's likely caused by a version mismatch in the `@opentelemetry/api` package.
To resolve this, add the following override to your package.json:
"overrides": { "@opentelemetry/api": "1.8.0"}
This is necessary because [`dd-trace` does not yet support version `1.9.0` or above of `@opentelemetry/api`](https://github.com/DataDog/dd-trace-js#datadog-with-opentelemetery)
.
After updating the `package.json`, reinstall your dependencies:
npm i
This should resolve the linting error.
#### Explanation[](https://www.prisma.io/docs/guides/data-dog#explanation "Direct link to Explanation")
* **`Tracer.init`** configures `dd-trace` with a `service` name. This name appears in Datadog under your `APM` > `Services` list.
* **`@prisma/instrumentation`** automatically logs each Prisma query as a Datadog span.
* The `middleware: true` option ensures that each query is intercepted for instrumentation.
5\. Instantiate Prisma and run queries[](https://www.prisma.io/docs/guides/data-dog#5-instantiate-prisma-and-run-queries "Direct link to 5. Instantiate Prisma and run queries")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 5.1. Create the Prisma Client instance[](https://www.prisma.io/docs/guides/data-dog#51-create-the-prisma-client-instance "Direct link to 5.1. Create the Prisma Client instance")
Create a `src/client.ts` to hold your Prisma Client instantiation:
* Prisma Postgres (recommended)
* Your own database
src/client.ts
import { tracer } from "./tracer";import { withAccelerate } from "@prisma/extension-accelerate";import { PrismaClient } from "./generated/prisma";const prisma = new PrismaClient({ log: [{ emit: "event", level: "query" }],}) .$on("query", (e) => { const span = tracer.startSpan(`prisma_raw_query`, { childOf: tracer.scope().active() || undefined, tags: { "prisma.rawquery": e.query, }, }); span.finish(); }) .$extends({ query: { async $allOperations({ operation, model, args, query }) { const span = tracer.startSpan( `prisma_query_${model?.toLowerCase()}_${operation}`, { tags: { "prisma.operation": operation, "prisma.model": model, "prisma.args": JSON.stringify(args), "prisma.rawQuery": query, }, childOf: tracer.scope().active() || undefined, } ); try { const result = await query(args); span.finish(); return result; } catch (error) { span.setTag("error", error); span.finish(); throw error; } }, }, }) .$extends(withAccelerate());export { prisma };
src/client.ts
import { tracer } from "./tracer";import { withAccelerate } from "@prisma/extension-accelerate";import { PrismaClient } from "./generated/prisma";const prisma = new PrismaClient({ log: [{ emit: "event", level: "query" }],}) .$on("query", (e) => { const span = tracer.startSpan(`prisma_raw_query`, { childOf: tracer.scope().active() || undefined, tags: { "prisma.rawquery": e.query, }, }); span.finish(); }) .$extends({ query: { async $allOperations({ operation, model, args, query }) { const span = tracer.startSpan( `prisma_query_${model?.toLowerCase()}_${operation}`, { tags: { "prisma.operation": operation, "prisma.model": model, "prisma.args": JSON.stringify(args), "prisma.rawQuery": query, }, childOf: tracer.scope().active() || undefined, } ); try { const result = await query(args); span.finish(); return result; } catch (error) { span.setTag("error", error); span.finish(); throw error; } }, }, });export { prisma };
The setup above gives you more control over how queries are traced:
* Tracing is initialized as early as possible by importing the `tracer` before creating the Prisma Client.
* The `$on("query")` hook captures raw SQL queries and sends them as standalone spans.
* The `$allOperations` extension wraps all Prisma operations in custom spans, allowing you to tag them with metadata like the model, operation type, and arguments.
Unlike the `@prisma/instrumentation` package, which offers automatic tracing out of the box, this manual setup gives you full control over how each span is structured and tagged. It's helpful when you need custom span names, additional metadata, a simpler setup, or when working around limitations or compatibility issues in the OpenTelemetry ecosystem. It also allows you to adapt tracing behavior based on query context, which can be especially useful in complex applications.
### 5.2. Add a script that performs queries[](https://www.prisma.io/docs/guides/data-dog#52-add-a-script-that-performs-queries "Direct link to 5.2. Add a script that performs queries")
Create a `src/index.ts` file and add code to perform queries to your database and send traces to Datadog:
src/index.ts
import { prisma } from "./client";async function main() { const user1Email = `alice${Date.now()}@prisma.io`; const user2Email = `bob${Date.now()}@prisma.io`; let alice, bob; // 1. Create users concurrently try { [alice, bob] = await Promise.all([ prisma.user.create({ data: { email: user1Email, name: "Alice", posts: { create: { title: "Join the Prisma community on Discord", content: "https://pris.ly/discord", published: true, }, }, }, include: { posts: true }, }), prisma.user.create({ data: { email: user2Email, name: "Bob", posts: { create: [ { title: "Check out Prisma on YouTube", content: "https://pris.ly/youtube", published: true, }, { title: "Follow Prisma on Twitter", content: "https://twitter.com/prisma/", published: false, }, ], }, }, include: { posts: true }, }), ]); console.log( `✅ Created users: ${alice.name} (${alice.posts.length} post) and ${bob.name} (${bob.posts.length} posts)` ); } catch (err) { console.error("❌ Error creating users:", err); return; } // 2. Fetch all published posts try { const publishedPosts = await prisma.post.findMany({ where: { published: true }, }); console.log(`✅ Retrieved ${publishedPosts.length} published post(s).`); } catch (err) { console.error("❌ Error fetching published posts:", err); } // 3. Create & publish a post for Alice let post; try { post = await prisma.post.create({ data: { title: "Join the Prisma Discord community", content: "https://pris.ly/discord", published: false, author: { connect: { email: user1Email } }, }, }); console.log(`✅ Created draft post for Alice (ID: ${post.id})`); } catch (err) { console.error("❌ Error creating draft post for Alice:", err); return; } try { post = await prisma.post.update({ where: { id: post.id }, data: { published: true }, }); console.log("✅ Published Alice’s post:", post); } catch (err) { console.error("❌ Error publishing Alice's post:", err); } // 4. Fetch all posts by Alice try { const alicePosts = await prisma.post.findMany({ where: { author: { email: user1Email } }, }); console.log( `✅ Retrieved ${alicePosts.length} post(s) by Alice.`, alicePosts ); } catch (err) { console.error("❌ Error fetching Alice's posts:", err); }}// Entrypointmain() .catch((err) => { console.error("❌ Unexpected error:", err); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); console.log("🔌 Disconnected from database."); });
6\. Run your queries and see the traces[](https://www.prisma.io/docs/guides/data-dog#6-run-your-queries-and-see-the-traces "Direct link to 6. Run your queries and see the traces")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Run the queries:
npx tsx src/index.ts
This executes your script, which:
* Registers the Datadog tracer.
* Performs multiple Prisma queries.
* Logs the result of each operation.
Then, confirm the traces in Datadog:
* Open your [Datadog APM page](https://docs.datadoghq.com/tracing/)
.
* Navigate to **APM > Traces > Explorer** in the side panel.
* Explore the list of traces and spans, each representing a Prisma query (e.g. `prisma:query`).
info
Depending on your Datadog setup, it may take a minute or two for new data to appear. Refresh or wait briefly if you do not see traces right away.
Next steps[](https://www.prisma.io/docs/guides/data-dog#next-steps "Direct link to Next steps")
-------------------------------------------------------------------------------------------------
You have successfully:
* Created a Prisma ORM project with [Prisma Postgres](https://www.prisma.io/docs/postgres)
.
* Set up Datadog tracing using `@prisma/instrumentation` and `dd-trace`.
* Verified that database operations show up as spans in Datadog.
To improve your observability further:
* Add more instrumentation for your HTTP server or other services (e.g., Express, Fastify).
* [Create Dashboards to view](https://docs.datadoghq.com/dashboards/)
key metrics from your data.
For additional guidance, check out:
* [Datadog APM documentation](https://docs.datadoghq.com/tracing/)
.
* [Prisma tracing docs](https://www.prisma.io/docs/orm/prisma-client/observability-and-logging/opentelemetry-tracing)
.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/data-dog%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/data-dog%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/data-dog%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/190-data-dog.mdx)
* [Introduction](https://www.prisma.io/docs/guides/data-dog#introduction)
* [What are spans and tracing?](https://www.prisma.io/docs/guides/data-dog#what-are-spans-and-tracing)
* [Why use Datadog with Prisma ORM?](https://www.prisma.io/docs/guides/data-dog#why-use-datadog-with-prisma-orm)
* [Prerequisites](https://www.prisma.io/docs/guides/data-dog#prerequisites)
* [1\. Create a new project](https://www.prisma.io/docs/guides/data-dog#1-create-a-new-project)
* [2\. Set up Prisma ORM](https://www.prisma.io/docs/guides/data-dog#2-set-up-prisma-orm)
* [2.1. Install and initialize Prisma ORM](https://www.prisma.io/docs/guides/data-dog#21-install-and-initialize-prisma-orm)
* [2.2. Define models](https://www.prisma.io/docs/guides/data-dog#22-define-models)
* [2.3. Generate the Prisma Client and run migrations](https://www.prisma.io/docs/guides/data-dog#23-generate-the-prisma-client-and-run-migrations)
* [3\. Install required dependencies for tracing](https://www.prisma.io/docs/guides/data-dog#3-install-required-dependencies-for-tracing)
* [4\. Set up Datadog tracing](https://www.prisma.io/docs/guides/data-dog#4-set-up-datadog-tracing)
* [4.1. Configure the tracer](https://www.prisma.io/docs/guides/data-dog#41-configure-the-tracer)
* [5\. Instantiate Prisma and run queries](https://www.prisma.io/docs/guides/data-dog#5-instantiate-prisma-and-run-queries)
* [5.1. Create the Prisma Client instance](https://www.prisma.io/docs/guides/data-dog#51-create-the-prisma-client-instance)
* [5.2. Add a script that performs queries](https://www.prisma.io/docs/guides/data-dog#52-add-a-script-that-performs-queries)
* [6\. Run your queries and see the traces](https://www.prisma.io/docs/guides/data-dog#6-run-your-queries-and-see-the-traces)
* [Next steps](https://www.prisma.io/docs/guides/data-dog#next-steps)
---
# How to migrate from Mongoose to Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/migrate-from-mongoose#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/migrate-from-mongoose#introduction "Direct link to Introduction")
--------------------------------------------------------------------------------------------------------------------
This guide shows you how to migrate your application from Mongoose to Prisma ORM. We'll use an extended version of the [Mongoose Express example](https://github.com/Automattic/mongoose/tree/master/examples/express)
as a [sample project](https://github.com/prisma/migrate-from-mongoose-to-prisma)
to demonstrate the migration steps.
You can learn how Prisma ORM compares to Mongoose on the [Prisma ORM vs Mongoose](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-mongoose)
page.
Prerequisites[](https://www.prisma.io/docs/guides/migrate-from-mongoose#prerequisites "Direct link to Prerequisites")
-----------------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* A Mongoose project you want to migrate
* Node.js installed (version 18 or higher)
* MongoDB database
* Basic familiarity with Mongoose and Express.js
1\. Prepare for migration[](https://www.prisma.io/docs/guides/migrate-from-mongoose#1-prepare-for-migration "Direct link to 1. Prepare for migration")
--------------------------------------------------------------------------------------------------------------------------------------------------------
### 1.1. Understand the migration process[](https://www.prisma.io/docs/guides/migrate-from-mongoose#11-understand-the-migration-process "Direct link to 1.1. Understand the migration process")
The steps for migrating from Mongoose to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
1. Install the Prisma CLI
2. Introspect your database
3. Install and generate Prisma Client
4. Gradually replace your Mongoose queries with Prisma Client
These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses Mongoose for database access.
### 1.2. Set up Prisma configuration[](https://www.prisma.io/docs/guides/migrate-from-mongoose#12-set-up-prisma-configuration "Direct link to 1.2. Set up Prisma configuration")
Create a new Prisma schema file:
npx prisma init --datasource-provider mongodb --output ../generated/prisma
This command creates:
* A new directory called `prisma` that contains a `schema.prisma` file; your Prisma schema specifies your database connection and models
* `.env`: A [`dotenv`](https://github.com/motdotla/dotenv)
file at the root of your project (if it doesn't already exist), used to configure your database connection URL as an environment variable
The Prisma schema currently looks as follows:
prisma/schema.prisma
// This is your Prisma schema file,// learn more about it in the docs: https://pris.ly/d/prisma-schemadatasource db { provider = "mongodb" url = env("DATABASE_URL")}generator client { provider = "prisma-client-js"}
tip
For an optimal development experience when working with Prisma ORM, refer to [editor setup](https://www.prisma.io/docs/orm/more/development-environment/editor-setup)
to learn about syntax highlighting, formatting, auto-completion, and many more cool features.
Update the `DATABASE_URL` in the `.env` file with your MongoDB connection string:
DATABASE_URL="mongodb://USER:PASSWORD@HOST:PORT/DATABASE"
2\. Migrate the database schema[](https://www.prisma.io/docs/guides/migrate-from-mongoose#2-migrate-the-database-schema "Direct link to 2. Migrate the database schema")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Introspect your database[](https://www.prisma.io/docs/guides/migrate-from-mongoose#21-introspect-your-database "Direct link to 2.1. Introspect your database")
warning
MongoDB is a _schemaless_ database. To incrementally adopt Prisma ORM in your project, ensure your database is populated with sample data. Prisma ORM introspects a MongoDB schema by sampling data stored and inferring the schema from the data in the database.
Run Prisma's introspection to create the Prisma schema from your existing database:
npx prisma db pull
This will create a `schema.prisma` file with your database schema.
prisma/schema.prisma
type UsersProfile { bio String}model categories { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") name String}model posts { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") author String @db.ObjectId categories String[] @db.ObjectId content String published Boolean title String}model users { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") email String @unique(map: "email_1") name String profile UsersProfile?}
### 2.2. Update relations[](https://www.prisma.io/docs/guides/migrate-from-mongoose#22-update-relations "Direct link to 2.2. Update relations")
MongoDB doesn't support relations between different collections. However, you can create references between documents using the [`ObjectId`](https://www.prisma.io/docs/orm/overview/databases/mongodb#using-objectid)
field type or from one document to many using an array of `ObjectIds` in the collection. The reference will store id(s) of the related document(s). You can use the `populate()` method that Mongoose provides to populate the reference with the data of the related document.
Update the 1-n relationship between `posts` <-> `users` as follows:
* Rename the existing `author` reference in the `posts` model to `authorId` and add the `@map("author")` attribute
* Add the `author` relation field in the `posts` model and it's `@relation` attribute specifying the `fields` and `references`
* Add the `posts` relation in the `users` model
Your schema should now look like this:
schema.prisma
type UsersProfile { bio String}model categories { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") name String}model posts { id String @id @default(auto()) @map("_id") @db.ObjectId title String content String published Boolean v Int @map("__v") author String @db.ObjectId author users @relation(fields: [authorId], references: [id]) authorId String @map("author") @db.ObjectId categories String[] @db.ObjectId}model users { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") email String @unique(map: "email_1") name String profile UsersProfile? posts posts[]}
Then, update the m-n between `posts` <-> `categories` references as follows:
* Rename the `categories` field to `categoryIds` and map it using `@map("categories")` in the `posts` model
* Add a new `categories` relation field in the `posts` model
* Add the `postIds` scalar list field in the `categories` model
* Add the `posts` relation in the `categories` model
* Add a [relation scalar](https://www.prisma.io/docs/orm/prisma-schema/data-model/relations#annotated-relation-fields)
on both models
* Add the `@relation` attribute specifying the `fields` and `references` arguments on both sides
Your schema should now look like this:
schema.prisma
type UsersProfile { bio String}model categories { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") name String posts posts[] @relation(fields: [postIds], references: [id]) postIds String[] @db.ObjectId}model posts { id String @id @default(auto()) @map("_id") @db.ObjectId title String content String published Boolean v Int @map("__v") author users @relation(fields: [authorId], references: [id]) authorId String @map("author") @db.ObjectId categories String[] @db.ObjectId categories categories[] @relation(fields: [categoryIds], references: [id]) categoryIds String[] @map("categories") @db.ObjectId}model users { id String @id @default(auto()) @map("_id") @db.ObjectId v Int @map("__v") email String @unique(map: "email_1") name String profile UsersProfile? posts posts[]}
3\. Update your application code[](https://www.prisma.io/docs/guides/migrate-from-mongoose#3-update-your-application-code "Direct link to 3. Update your application code")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Install Prisma Client[](https://www.prisma.io/docs/guides/migrate-from-mongoose#31-install-prisma-client "Direct link to 3.1. Install Prisma Client")
Install the Prisma Client package:
npm install @prisma/client
After installing the Prisma Client package, generate Prisma Client:
npx prisma generate
### 3.2. Replace Mongoose queries[](https://www.prisma.io/docs/guides/migrate-from-mongoose#32-replace-mongoose-queries "Direct link to 3.2. Replace Mongoose queries")
Start replacing your Mongoose queries with Prisma Client. Here's an example of how to convert some common queries:
* Mongoose
* Prisma Client
// Find oneconst user = await User.findById(id);// Createconst user = await User.create({ email: 'alice@prisma.io', name: 'Alice'});// Updateawait User.findByIdAndUpdate(id, { name: 'New name' });// Deleteawait User.findByIdAndDelete(id);
// Find oneconst user = await prisma.user.findUnique({ where: { id } });// Createconst user = await prisma.user.create({ data: { email: 'alice@prisma.io', name: 'Alice' }});// Updateawait prisma.user.update({ where: { id }, data: { name: 'New name' }});// Deleteawait prisma.user.delete({ where: { id }});
### 3.3. Update your controllers[](https://www.prisma.io/docs/guides/migrate-from-mongoose#33-update-your-controllers "Direct link to 3.3. Update your controllers")
Update your Express controllers to use Prisma Client. For example, here's how to update a user controller:
import { prisma } from '../client'export class UserController { async create(req: Request, res: Response) { const { email, name } = req.body const result = await prisma.user.create({ data: { email, name, }, }) return res.json(result) }}
Next steps[](https://www.prisma.io/docs/guides/migrate-from-mongoose#next-steps "Direct link to Next steps")
--------------------------------------------------------------------------------------------------------------
Now that you've migrated to Prisma ORM, you can:
* Add more complex queries using Prisma's powerful query API
* Set up Prisma Studio for database management
* Implement database monitoring
* Add automated tests using Prisma's testing utilities
For more information:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/migrate-from-mongoose%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/migrate-from-mongoose%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/migrate-from-mongoose%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/050-migrate-from-mongoose.mdx)
* [Introduction](https://www.prisma.io/docs/guides/migrate-from-mongoose#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/migrate-from-mongoose#prerequisites)
* [1\. Prepare for migration](https://www.prisma.io/docs/guides/migrate-from-mongoose#1-prepare-for-migration)
* [1.1. Understand the migration process](https://www.prisma.io/docs/guides/migrate-from-mongoose#11-understand-the-migration-process)
* [1.2. Set up Prisma configuration](https://www.prisma.io/docs/guides/migrate-from-mongoose#12-set-up-prisma-configuration)
* [2\. Migrate the database schema](https://www.prisma.io/docs/guides/migrate-from-mongoose#2-migrate-the-database-schema)
* [2.1. Introspect your database](https://www.prisma.io/docs/guides/migrate-from-mongoose#21-introspect-your-database)
* [2.2. Update relations](https://www.prisma.io/docs/guides/migrate-from-mongoose#22-update-relations)
* [3\. Update your application code](https://www.prisma.io/docs/guides/migrate-from-mongoose#3-update-your-application-code)
* [3.1. Install Prisma Client](https://www.prisma.io/docs/guides/migrate-from-mongoose#31-install-prisma-client)
* [3.2. Replace Mongoose queries](https://www.prisma.io/docs/guides/migrate-from-mongoose#32-replace-mongoose-queries)
* [3.3. Update your controllers](https://www.prisma.io/docs/guides/migrate-from-mongoose#33-update-your-controllers)
* [Next steps](https://www.prisma.io/docs/guides/migrate-from-mongoose#next-steps)
---
# How to migrate from Drizzle to Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/migrate-from-drizzle#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/migrate-from-drizzle#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------------
This guide shows you how to migrate your application from Drizzle to Prisma ORM. We'll use a sample project based off of the [Drizzle Next.js example](https://orm.drizzle.team/docs/tutorials/drizzle-nextjs-neon)
to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-drizzle-to-prisma)
.
You can learn how Prisma ORM compares to Drizzle on the [Prisma ORM vs Drizzle](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-drizzle)
page.
Prerequisites[](https://www.prisma.io/docs/guides/migrate-from-drizzle#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* A Drizzle project you want to migrate
* Node.js installed (version 16 or higher)
* PostgreSQL or another supported database
* Basic familiarity with Drizzle and Next.js
note
this migration guide uses Neon PostgreSQL as the example database, but it equally applies to any other relational database that are [supported by Prisma ORM](https://www.prisma.io/docs/orm/reference/supported-databases)
.
You can learn how Prisma ORM compares to Drizzle on the [Prisma ORM vs Drizzle](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-drizzle)
page.
Overview of the migration process[](https://www.prisma.io/docs/guides/migrate-from-drizzle#overview-of-the-migration-process "Direct link to Overview of the migration process")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Note that the steps for migrating from Drizzle to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
1. Install the Prisma CLI
2. Introspect your database
3. Create a baseline migration
4. Install Prisma Client
5. Gradually replace your Drizzle queries with Prisma Client
These steps apply, no matter if you're building a REST API (e.g. with Express, koa or NestJS), a GraphQL API (e.g. with Apollo Server, TypeGraphQL or Nexus) or any other kind of application that uses Drizzle for database access.
Prisma ORM lends itself really well for **incremental adoption**. This means, you don't have migrate your entire project from Drizzle to Prisma ORM at once, but rather you can _step-by-step_ move your database queries from Drizzle to Prisma ORM.
Step 1. Install the Prisma CLI[](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-1-install-the-prisma-cli "Direct link to Step 1. Install the Prisma CLI")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The first step to adopt Prisma ORM is to [install the Prisma CLI](https://www.prisma.io/docs/orm/tools/prisma-cli#installation)
in your project:
npm install prisma --save-dev && npm install @prisma/client
Step 2. Introspect your database[](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-2-introspect-your-database "Direct link to Step 2. Introspect your database")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Set up Prisma ORM[](https://www.prisma.io/docs/guides/migrate-from-drizzle#21-set-up-prisma-orm "Direct link to 2.1. Set up Prisma ORM")
Before you can introspect your database, you need to set up your [Prisma schema](https://www.prisma.io/docs/orm/prisma-schema)
and connect Prisma to your database. Run the following command in the root of your project to create a basic Prisma schema file:
npx prisma init --output ../generated/prisma
This command created a new directory called `prisma` with the following files for you:
* `schema.prisma`: Your Prisma schema that specifies your database connection and models
* `.env`: A [`dotenv`](https://github.com/motdotla/dotenv)
to configure your database connection URL as an environment variable
note
You may already have a `.env` file. If so, the `prisma init` command will append lines to it rather than creating a new file.
The Prisma schema currently looks as follows:
prisma/schema.prisma
// This is your Prisma schema file,// learn more about it in the docs: https://pris.ly/d/prisma-schemadatasource db { provider = "postgresql" url = env("DATABASE_URL")}generator client { provider = "prisma-client-js"}
tip
If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma)
for syntax highlighting, formatting, auto-completion and a lot more cool features.
### 2.2. Connect your database[](https://www.prisma.io/docs/guides/migrate-from-drizzle#22-connect-your-database "Direct link to 2.2. Connect your database")
If you're not using PostgreSQL, you need to adjust the `provider` field on the `datasource` block to the database you currently use:
* PostgreSQL
* MySQL
* Microsoft SQL Server
* SQLite
schema.prisma
datasource db { provider = "postgresql" url = env("DATABASE_URL")}
schema.prisma
datasource db { provider = "mysql" url = env("DATABASE_URL")}
schema.prisma
datasource db { provider = "sqlserver" url = env("DATABASE_URL")}
schema.prisma
datasource db { provider = "sqlite" url = env("DATABASE_URL")}
Once that's done, you can configure your [database connection URL](https://www.prisma.io/docs/orm/reference/connection-urls)
in the `.env` file. Drizzle and Prisma ORM use the same format for connection URLs, so your existing connection URL should work fine.
### 2.3. Introspect your database using Prisma ORM[](https://www.prisma.io/docs/guides/migrate-from-drizzle#23-introspect-your-database-using-prisma-orm "Direct link to 2.3. Introspect your database using Prisma ORM")
With your connection URL in place, you can [introspect](https://www.prisma.io/docs/orm/prisma-schema/introspection)
your database to generate your Prisma models:
npx prisma db pull
If you're using the [sample project](https://github.com/prisma/migrate-from-drizzle-to-prisma)
the following model would be created:
prisma/schema.prisma
model todo { id Int @id text String done Boolean @default(false)}
The generated Prisma model represents a database table. Prisma models are the foundation for your programmatic Prisma Client API which allows you to send queries to your database.
### 2.4. Create a baseline migration[](https://www.prisma.io/docs/guides/migrate-from-drizzle#24-create-a-baseline-migration "Direct link to 2.4. Create a baseline migration")
To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](https://www.prisma.io/docs/orm/prisma-migrate/getting-started)
.
First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:
mkdir -p prisma/migrations/0_init
Next, generate the migration file with `prisma migrate diff`. Use the following arguments:
* `--from-empty`: assumes the data model you're migrating from is empty
* `--to-schema-datamodel`: the current database state using the URL in the `datasource` block
* `--script`: output a SQL script
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
Review the generated migration to ensure everything is correct.
Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument.
npx prisma migrate resolve --applied 0_init
The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.
You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.
### 2.5. Adjust the Prisma schema (optional)[](https://www.prisma.io/docs/guides/migrate-from-drizzle#25-adjust-the-prisma-schema-optional "Direct link to 2.5. Adjust the Prisma schema (optional)")
Models that are generated via introspection currently _exactly_ map to your database tables. In this section, you'll learn how you can adjust the naming of the Prisma models to adhere to [Prisma ORM's naming conventions](https://www.prisma.io/docs/orm/reference/prisma-schema-reference#naming-conventions)
.
All of these adjustment are entirely optional and you are free to skip to the next step already if you don't want to adjust anything for now. You can go back and make the adjustments at any later point.
As opposed to the current camelCase notation of Drizzle models, Prisma ORM's naming conventions are:
* PascalCase for model names
* camelCase for field names
You can adjust the naming by _mapping_ the Prisma model and field names to the existing table and column names in the underlying database using `@@map` and `@map`.
Here's an example on how you could modify the model above:
prisma/schema.prisma
model Todo { id Int @id text String done Boolean @default(false) @@map("todo")}
Step 3. Install and generate Prisma Client[](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-3-install-and-generate-prisma-client "Direct link to Step 3. Install and generate Prisma Client")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Drizzle:
npm install @prisma/client
After installing, you need to run `generate` in order to have your schema reflected in TypeScript types and autocomplete.
npx prisma generate
Step 4. Replace your Drizzle queries with Prisma Client[](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-4-replace-your-drizzle-queries-with-prisma-client "Direct link to Step 4. Replace your Drizzle queries with Prisma Client")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In this section, we'll show a few sample queries that are being migrated from Drizzle to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Drizzle, check out the [comparison page](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-drizzle)
.
First, to set up the `PrismaClient` instance that you'll use to send database queries from the various route handlers. Create a new file named `prisma.ts` in the `db` directory:
touch db/prisma.ts
Now, instantiate `PrismaClient` and export it from the file so you can use it in your route handlers later:
db/prisma.ts
import { PrismaClient } from '@prisma/client'export const prisma = new PrismaClient()
### 4.1. Replacing `getData` queries[](https://www.prisma.io/docs/guides/migrate-from-drizzle#41-replacing-getdata-queries "Direct link to 41-replacing-getdata-queries")
The fullstack Next.js app has several `actions` including `getData`.
The `getData` action is currently implemented as follows:
actions/todoActions.ts
import db from "@/db/drizzle";import { todo } from "@/db/schema";export const getData = async () => { const data = await db.select().from(todo); return data;};
Here is the same action implemented using Prisma Client:
src/controllers/FeedAction.ts
import { prisma } from "@/db/prisma";export const getData = async () => { const data = await prisma.todo.findMany(); return data;};
### 4.2. Replacing queries in `POST` requests[](https://www.prisma.io/docs/guides/migrate-from-drizzle#42-replacing-queries-in-post-requests "Direct link to 42-replacing-queries-in-post-requests")
The [sample project](https://github.com/prisma/migrate-from-drizzle-to-prisma)
has four actions that are utilized during `POST` requests:
* `addTodo`: Creates a new `Todo` record
* `deleteTodo`: Deletes an existing `Todo` record
* `toggleTodo`: Toggles the boolean `done` field on an existing `Todo` record
* `editTodo`: Edits the `text` field on an existing `Todo` record
#### `addTodo`[](https://www.prisma.io/docs/guides/migrate-from-drizzle#addtodo "Direct link to addtodo")
The `addTodo` action is currently implemented as follows:
actions/todoActions.ts
import { revalidatePath } from "next/cache";import db from "@/db/drizzle";import { todo } from "@/db/schema";export const addTodo = async (id: number, text: string) => { await db.insert(todo).values({ id: id, text: text, }); revalidatePath("/");};
Here is the same action implemented using Prisma Client:
actions/todoActions.ts
import { revalidatePath } from "next/cache";import { prisma } from "@/db/prisma";export const addTodo = async (id: number, text: string) => { await prisma.todo.create({ data: { id, text }, }) revalidatePath("/");};
#### `deleteTodo`[](https://www.prisma.io/docs/guides/migrate-from-drizzle#deletetodo "Direct link to deletetodo")
The `deleteTodo` action is currently implemented as follows:
actions/todoActions.ts
import { eq } from "drizzle-orm";import { revalidatePath } from "next/cache";import db from "@/db/drizzle";import { todo } from "@/db/schema";export const deleteTodo = async (id: number) => { await db.delete(todo).where(eq(todo.id, id)); revalidatePath("/");};
Here is the same action implemented using Prisma Client:
actions/todoActions.ts
import { revalidatePath } from "next/cache";import { prisma } from "@/db/prisma";export const deleteTodo = async (id: number) => { await prisma.todo.delete({ where: { id } }); revalidatePath("/");};
#### `toggleTodo`[](https://www.prisma.io/docs/guides/migrate-from-drizzle#toggletodo "Direct link to toggletodo")
The `ToggleTodo` action is currently implemented as follows:
actions/todoActions.ts
import { eq, not } from "drizzle-orm";import { revalidatePath } from "next/cache";import db from "@/db/drizzle";import { todo } from "@/db/schema";export const toggleTodo = async (id: number) => { await db .update(todo) .set({ done: not(todo.done), }) .where(eq(todo.id, id)); revalidatePath("/");};
Here is the same action implemented using Prisma Client:
actions/todoActions.ts
import { revalidatePath } from "next/cache";import { prisma } from "@/db/prisma";export const toggleTodo = async (id: number) => { const todo = await prisma.todo.findUnique({ where: { id } }); if (todo) { await prisma.todo.update({ where: { id: todo.id }, data: { done: !todo.done }, }) revalidatePath("/"); }};
Note that Prisma ORM does not have the ability to edit a boolean field "in place", so the record must be fetched before hand.
#### `editTodo`[](https://www.prisma.io/docs/guides/migrate-from-drizzle#edittodo "Direct link to edittodo")
The `editTodo` action is currently implemented as follows:
actions/todoActions.ts
import { eq } from "drizzle-orm";import { revalidatePath } from "next/cache";import db from "@/db/drizzle";import { todo } from "@/db/schema";export const editTodo = async (id: number, text: string) => { await db .update(todo) .set({ text: text, }) .where(eq(todo.id, id)); revalidatePath("/");};
Here is the same action implemented using Prisma Client:
actions/todoActions.ts
import { revalidatePath } from "next/cache";import { prisma } from "@/db/prisma";export const editTodo = async (id: number, text: string) => { await prisma.todo.update({ where: { id }, data: { text }, }) revalidatePath("/");};
More[](https://www.prisma.io/docs/guides/migrate-from-drizzle#more "Direct link to More")
-------------------------------------------------------------------------------------------
### Implicit many-to-many relations[](https://www.prisma.io/docs/guides/migrate-from-drizzle#implicit-many-to-many-relations "Direct link to Implicit many-to-many relations")
Unlike Drizzle, Prisma ORM allows you to [model many-to-many relations _implicitly_](https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations)
. That is, a many-to-many relation where you do not have to manage the [relation table](https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables)
(also sometimes called JOIN table) _explicitly_ in your schema. Here is an example comparing Drizzle with Prisma ORM:
schema.ts
import { boolean, integer, pgTable, serial, text } from "drizzle-orm/pg-core";export const posts = pgTable('post', { id: serial('serial').primaryKey(), title: text('title').notNull(), content: text('content'), published: boolean('published').default(false).notNull(),});export const categories = pgTable('category', { id: serial('serial').primaryKey(), name: text('name').notNull(),});export const postsToCategories = pgTable('posts_to_categories', { postId: integer('post_id').notNull().references(() => users.id), categoryId: integer('category_id').notNull().references(() => chatGroups.id),});
This schema is equivalent to the following Prisma schema:
schema.prisma
model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) postsToCategories PostToCategories[] @@map("post")}model Category { id Int @id @default(autoincrement()) name String postsToCategories PostToCategories[] @@map("category")}model PostToCategories { postId Int categoryId Int category Category @relation(fields: [categoryId], references: [id]) post Post @relation(fields: [postId], references: [id]) @@id([postId, categoryId]) @@index([postId]) @@index([categoryId]) @@map("posts_to_categories")}
In this Prisma schema, the many-to-many relation is modeled _explicitly_ via the relation table `PostToCategories`.
By instead adhering to the conventions for Prisma ORM relation tables, the relation could look as follows:
schema.prisma
model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) categories Category[]}model Category { id Int @id @default(autoincrement()) name String posts Post[]}
This would also result in a more ergonomic and less verbose Prisma Client API to modify the records in this relation, because you have a direct path from `Post` to `Category` (and the other way around) instead of needing to traverse the `PostToCategories` model first.
warning
If your database provider requires tables to have primary keys then you have to use explicit syntax, and manually create the join model with a primary key. This is because relation tables (JOIN tables) created by Prisma ORM (expressed via `@relation`) for many-to-many relations using implicit syntax do not have primary keys.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/migrate-from-drizzle%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/migrate-from-drizzle%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/migrate-from-drizzle%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/060-migrate-from-drizzle.mdx)
* [Introduction](https://www.prisma.io/docs/guides/migrate-from-drizzle#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/migrate-from-drizzle#prerequisites)
* [Overview of the migration process](https://www.prisma.io/docs/guides/migrate-from-drizzle#overview-of-the-migration-process)
* [Step 1. Install the Prisma CLI](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-1-install-the-prisma-cli)
* [Step 2. Introspect your database](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-2-introspect-your-database)
* [2.1. Set up Prisma ORM](https://www.prisma.io/docs/guides/migrate-from-drizzle#21-set-up-prisma-orm)
* [2.2. Connect your database](https://www.prisma.io/docs/guides/migrate-from-drizzle#22-connect-your-database)
* [2.3. Introspect your database using Prisma ORM](https://www.prisma.io/docs/guides/migrate-from-drizzle#23-introspect-your-database-using-prisma-orm)
* [2.4. Create a baseline migration](https://www.prisma.io/docs/guides/migrate-from-drizzle#24-create-a-baseline-migration)
* [2.5. Adjust the Prisma schema (optional)](https://www.prisma.io/docs/guides/migrate-from-drizzle#25-adjust-the-prisma-schema-optional)
* [Step 3. Install and generate Prisma Client](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-3-install-and-generate-prisma-client)
* [Step 4. Replace your Drizzle queries with Prisma Client](https://www.prisma.io/docs/guides/migrate-from-drizzle#step-4-replace-your-drizzle-queries-with-prisma-client)
* [4.1. Replacing `getData` queries](https://www.prisma.io/docs/guides/migrate-from-drizzle#41-replacing-getdata-queries)
* [4.2. Replacing queries in `POST` requests](https://www.prisma.io/docs/guides/migrate-from-drizzle#42-replacing-queries-in-post-requests)
* [More](https://www.prisma.io/docs/guides/migrate-from-drizzle#more)
* [Implicit many-to-many relations](https://www.prisma.io/docs/guides/migrate-from-drizzle#implicit-many-to-many-relations)
---
# How to migrate data with Prisma ORM using the expand and contract pattern | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/data-migration#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/data-migration#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------
When making changes to your database schema in production, it's crucial to ensure data consistency and avoid downtime. This guide shows you how to use the expand and contract pattern to safely migrate data between columns. We'll walk through a practical example of replacing a boolean field with an enum field while preserving existing data.
Prerequisites[](https://www.prisma.io/docs/guides/data-migration#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* Node.js installed (version 18 or higher)
* A Prisma ORM project with an existing schema
* A supported database (PostgreSQL, MySQL, SQLite, SQL Server, etc.)
* Access to both development and production databases
* Basic understanding of Git branching
* Basic familiarity with TypeScript
1\. Set up your environment[](https://www.prisma.io/docs/guides/data-migration#1-set-up-your-environment "Direct link to 1. Set up your environment")
-------------------------------------------------------------------------------------------------------------------------------------------------------
### 1.1. Review initial schema[](https://www.prisma.io/docs/guides/data-migration#11-review-initial-schema "Direct link to 1.1. Review initial schema")
Start with a basic schema containing a Post model:
generator client { provider = "prisma-client-js"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false)}
### 1.2. Create a development branch[](https://www.prisma.io/docs/guides/data-migration#12-create-a-development-branch "Direct link to 1.2. Create a development branch")
Create a new branch for your changes:
git checkout -b create-status-field
2\. Expand the schema[](https://www.prisma.io/docs/guides/data-migration#2-expand-the-schema "Direct link to 2. Expand the schema")
-------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Add new column[](https://www.prisma.io/docs/guides/data-migration#21-add-new-column "Direct link to 2.1. Add new column")
Update your schema to add the new Status enum and field:
model Post { id Int @id @default(autoincrement()) title String content String? published Boolean? @default(false) status Status @default(Unknown)}enum Status { Unknown Draft InProgress InReview Published}
### 2.2. Create migration[](https://www.prisma.io/docs/guides/data-migration#22-create-migration "Direct link to 2.2. Create migration")
Generate the migration:
npx prisma migrate dev --name add-status-column
3\. Migrate the data[](https://www.prisma.io/docs/guides/data-migration#3-migrate-the-data "Direct link to 3. Migrate the data")
----------------------------------------------------------------------------------------------------------------------------------
### 3.1. Create migration script[](https://www.prisma.io/docs/guides/data-migration#31-create-migration-script "Direct link to 3.1. Create migration script")
Create a new TypeScript file for the data migration:
import { PrismaClient } from '@prisma/client'const prisma = new PrismaClient()async function main() { await prisma.$transaction(async (tx) => { const posts = await tx.post.findMany() for (const post of posts) { await tx.post.update({ where: { id: post.id }, data: { status: post.published ? 'Published' : 'Unknown', }, }) } })}main() .catch(async (e) => { console.error(e) process.exit(1) }) .finally(async () => await prisma.$disconnect())
### 3.2. Set up migration script[](https://www.prisma.io/docs/guides/data-migration#32-set-up-migration-script "Direct link to 3.2. Set up migration script")
Add the migration script to your package.json:
{ "scripts": { "data-migration:add-status-column": "tsx ./prisma/migrations//data-migration.ts" }}
### 3.3. Execute migration[](https://www.prisma.io/docs/guides/data-migration#33-execute-migration "Direct link to 3.3. Execute migration")
1. Update your DATABASE\_URL to point to the production database
2. Run the migration script:
npm run data-migration:add-status-column
4\. Contract the schema[](https://www.prisma.io/docs/guides/data-migration#4-contract-the-schema "Direct link to 4. Contract the schema")
-------------------------------------------------------------------------------------------------------------------------------------------
### 4.1. Create cleanup branch[](https://www.prisma.io/docs/guides/data-migration#41-create-cleanup-branch "Direct link to 4.1. Create cleanup branch")
Create a new branch for removing the old column:
git checkout -b drop-published-column
### 4.2. Remove old column[](https://www.prisma.io/docs/guides/data-migration#42-remove-old-column "Direct link to 4.2. Remove old column")
Update your schema to remove the published field:
model Post { id Int @id @default(autoincrement()) title String content String? status Status @default(Unknown)}enum Status { Draft InProgress InReview Published}
### 4.3. Generate cleanup migration[](https://www.prisma.io/docs/guides/data-migration#43-generate-cleanup-migration "Direct link to 4.3. Generate cleanup migration")
Create and run the final migration:
npx prisma migrate dev --name drop-published-column
5\. Deploy to production[](https://www.prisma.io/docs/guides/data-migration#5-deploy-to-production "Direct link to 5. Deploy to production")
----------------------------------------------------------------------------------------------------------------------------------------------
### 5.1. Set up deployment[](https://www.prisma.io/docs/guides/data-migration#51-set-up-deployment "Direct link to 5.1. Set up deployment")
Add the following command to your CI/CD pipeline:
npx prisma migrate deploy
### 5.2. Monitor deployment[](https://www.prisma.io/docs/guides/data-migration#52-monitor-deployment "Direct link to 5.2. Monitor deployment")
Watch for any errors in your logs and monitor your application's behavior after deployment.
Troubleshooting[](https://www.prisma.io/docs/guides/data-migration#troubleshooting "Direct link to Troubleshooting")
----------------------------------------------------------------------------------------------------------------------
### Common issues and solutions[](https://www.prisma.io/docs/guides/data-migration#common-issues-and-solutions "Direct link to Common issues and solutions")
1. **Migration fails due to missing default**
* Ensure you've added a proper default value
* Check that all existing records can be migrated
2. **Data loss prevention**
* Always backup your database before running migrations
* Test migrations on a copy of production data first
3. **Transaction rollback**
* If the data migration fails, the transaction will automatically rollback
* Fix any errors and retry the migration
Next steps[](https://www.prisma.io/docs/guides/data-migration#next-steps "Direct link to Next steps")
-------------------------------------------------------------------------------------------------------
Now that you've completed your first expand and contract migration, you can:
* Learn more about [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate)
* Explore [schema prototyping](https://www.prisma.io/docs/orm/prisma-migrate/workflows/prototyping-your-schema)
* Understand [customizing migrations](https://www.prisma.io/docs/orm/prisma-migrate/workflows/customizing-migrations)
For more information:
* [Expand and Contract Pattern Documentation](https://www.prisma.io/dataguide/types/relational/expand-and-contract-pattern)
* [Prisma Migrate Workflows](https://www.prisma.io/docs/orm/prisma-migrate/workflows)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/data-migration%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/data-migration%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/data-migration%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/010-data-migration.mdx)
* [Introduction](https://www.prisma.io/docs/guides/data-migration#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/data-migration#prerequisites)
* [1\. Set up your environment](https://www.prisma.io/docs/guides/data-migration#1-set-up-your-environment)
* [1.1. Review initial schema](https://www.prisma.io/docs/guides/data-migration#11-review-initial-schema)
* [1.2. Create a development branch](https://www.prisma.io/docs/guides/data-migration#12-create-a-development-branch)
* [2\. Expand the schema](https://www.prisma.io/docs/guides/data-migration#2-expand-the-schema)
* [2.1. Add new column](https://www.prisma.io/docs/guides/data-migration#21-add-new-column)
* [2.2. Create migration](https://www.prisma.io/docs/guides/data-migration#22-create-migration)
* [3\. Migrate the data](https://www.prisma.io/docs/guides/data-migration#3-migrate-the-data)
* [3.1. Create migration script](https://www.prisma.io/docs/guides/data-migration#31-create-migration-script)
* [3.2. Set up migration script](https://www.prisma.io/docs/guides/data-migration#32-set-up-migration-script)
* [3.3. Execute migration](https://www.prisma.io/docs/guides/data-migration#33-execute-migration)
* [4\. Contract the schema](https://www.prisma.io/docs/guides/data-migration#4-contract-the-schema)
* [4.1. Create cleanup branch](https://www.prisma.io/docs/guides/data-migration#41-create-cleanup-branch)
* [4.2. Remove old column](https://www.prisma.io/docs/guides/data-migration#42-remove-old-column)
* [4.3. Generate cleanup migration](https://www.prisma.io/docs/guides/data-migration#43-generate-cleanup-migration)
* [5\. Deploy to production](https://www.prisma.io/docs/guides/data-migration#5-deploy-to-production)
* [5.1. Set up deployment](https://www.prisma.io/docs/guides/data-migration#51-set-up-deployment)
* [5.2. Monitor deployment](https://www.prisma.io/docs/guides/data-migration#52-monitor-deployment)
* [Troubleshooting](https://www.prisma.io/docs/guides/data-migration#troubleshooting)
* [Common issues and solutions](https://www.prisma.io/docs/guides/data-migration#common-issues-and-solutions)
* [Next steps](https://www.prisma.io/docs/guides/data-migration#next-steps)
---
# How to migrate from Sequelize to Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/migrate-from-sequelize#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/migrate-from-sequelize#introduction "Direct link to Introduction")
---------------------------------------------------------------------------------------------------------------------
This guide shows you how to migrate your application from Sequelize to Prisma ORM. We'll use an extended version of the [Sequelize Express example](https://github.com/sequelize/express-example)
as a [sample project](https://github.com/prisma/migrate-from-sequelize-to-prisma)
to demonstrate the migration steps.
This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma ORM](https://www.prisma.io/docs/orm/reference/supported-databases)
. You can learn how Prisma ORM compares to Sequelize on the [Prisma ORM vs Sequelize](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-sequelize)
page.
Prerequisites[](https://www.prisma.io/docs/guides/migrate-from-sequelize#prerequisites "Direct link to Prerequisites")
------------------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* A Sequelize project you want to migrate
* Node.js installed (version 18 or higher)
* PostgreSQL or another supported database
* Basic familiarity with Sequelize and Express.js
1\. Prepare for migration[](https://www.prisma.io/docs/guides/migrate-from-sequelize#1-prepare-for-migration "Direct link to 1. Prepare for migration")
---------------------------------------------------------------------------------------------------------------------------------------------------------
### 1.1. Understand the migration process[](https://www.prisma.io/docs/guides/migrate-from-sequelize#11-understand-the-migration-process "Direct link to 1.1. Understand the migration process")
The steps for migrating from Sequelize to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
1. Install the Prisma CLI
2. Introspect your database
3. Create a baseline migration
4. Install Prisma Client
5. Gradually replace your Sequelize queries with Prisma Client
These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses Sequelize for database access.
### 1.2. Set up Prisma configuration[](https://www.prisma.io/docs/guides/migrate-from-sequelize#12-set-up-prisma-configuration "Direct link to 1.2. Set up Prisma configuration")
Create a new Prisma schema file:
npx prisma init --output ../generated/prisma
This command created a new directory called `prisma` with the following files for you:
* `schema.prisma`: Your Prisma schema that specifies your database connection and models
* `.env`: A [`dotenv`](https://github.com/motdotla/dotenv)
to configure your database connection URL as an environment variable
The Prisma schema currently looks as follows:
prisma/schema.prisma
// This is your Prisma schema file,// learn more about it in the docs: https://pris.ly/d/prisma-schemadatasource db { provider = "postgresql" url = env("DATABASE_URL")}generator client { provider = "prisma-client-js"}
tip
If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma)
for syntax highlighting, formatting, auto-completion and a lot more cool features.
Update the `DATABASE_URL` in the `.env` file with your database connection string:
DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
2\. Migrate the database schema[](https://www.prisma.io/docs/guides/migrate-from-sequelize#2-migrate-the-database-schema "Direct link to 2. Migrate the database schema")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Introspect your database[](https://www.prisma.io/docs/guides/migrate-from-sequelize#21-introspect-your-database "Direct link to 2.1. Introspect your database")
Run Prisma's introspection to create the Prisma schema from your existing database:
npx prisma db pull
This will create a `schema.prisma` file with your database schema.
### 2.2. Create a baseline migration[](https://www.prisma.io/docs/guides/migrate-from-sequelize#22-create-a-baseline-migration "Direct link to 2.2. Create a baseline migration")
To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](https://www.prisma.io/docs/orm/prisma-migrate/getting-started)
.
First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:
mkdir -p prisma/migrations/0_init
Next, generate the migration file with `prisma migrate diff`. Use the following arguments:
* `--from-empty`: assumes the data model you're migrating from is empty
* `--to-schema-datamodel`: the current database state using the URL in the `datasource` block
* `--script`: output a SQL script
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sqlnpx prisma migrate resolve --applied 0_init
The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.
You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.
3\. Update your application code[](https://www.prisma.io/docs/guides/migrate-from-sequelize#3-update-your-application-code "Direct link to 3. Update your application code")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Install Prisma Client[](https://www.prisma.io/docs/guides/migrate-from-sequelize#31-install-prisma-client "Direct link to 3.1. Install Prisma Client")
As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Sequelize:
npm install @prisma/client
After installing Prisma Client, you can generate the Prisma Client code:
npx prisma generate
### 3.2. Replace Sequelize queries[](https://www.prisma.io/docs/guides/migrate-from-sequelize#32-replace-sequelize-queries "Direct link to 3.2. Replace Sequelize queries")
In this section, we'll show a few sample queries that are being migrated from Sequelize to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Sequelize, check out the [API comparison](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-sequelize#api-comparison)
page.
* Sequelize
* Prisma Client
// Find oneconst user = await User.findOne({ where: { id: 1 } });// Createconst user = await User.create({ email: 'alice@prisma.io', name: 'Alice'});// Updateawait User.update({ name: 'New name' }, { where: { id: 1 } });// Deleteawait User.destroy({ where: { id: 1 }});
// Find oneconst user = await prisma.user.findUnique({ where: { id: 1 } });// Createconst user = await prisma.user.create({ data: { email: 'alice@prisma.io', name: 'Alice' }});// Updateawait prisma.user.update({ where: { id: 1 }, data: { name: 'New name' }});// Deleteawait prisma.user.delete({ where: { id: 1 }});
### 3.3. Update your controllers[](https://www.prisma.io/docs/guides/migrate-from-sequelize#33-update-your-controllers "Direct link to 3.3. Update your controllers")
Update your Express controllers to use Prisma Client. For example, here's how to update a user controller:
import { prisma } from '../client'export class UserController { async create(req: Request, res: Response) { const { email, name } = req.body const result = await prisma.user.create({ data: { email, name, }, }) return res.json(result) }}
Next steps[](https://www.prisma.io/docs/guides/migrate-from-sequelize#next-steps "Direct link to Next steps")
---------------------------------------------------------------------------------------------------------------
Now that you've migrated to Prisma ORM, you can:
* Add more complex queries using Prisma's powerful query API
* Set up Prisma Studio for database management
* Implement database monitoring
* Add automated tests using Prisma's testing utilities
For more information:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/migrate-from-sequelize%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/migrate-from-sequelize%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/migrate-from-sequelize%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/040-migrate-from-sequelize.mdx)
* [Introduction](https://www.prisma.io/docs/guides/migrate-from-sequelize#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/migrate-from-sequelize#prerequisites)
* [1\. Prepare for migration](https://www.prisma.io/docs/guides/migrate-from-sequelize#1-prepare-for-migration)
* [1.1. Understand the migration process](https://www.prisma.io/docs/guides/migrate-from-sequelize#11-understand-the-migration-process)
* [1.2. Set up Prisma configuration](https://www.prisma.io/docs/guides/migrate-from-sequelize#12-set-up-prisma-configuration)
* [2\. Migrate the database schema](https://www.prisma.io/docs/guides/migrate-from-sequelize#2-migrate-the-database-schema)
* [2.1. Introspect your database](https://www.prisma.io/docs/guides/migrate-from-sequelize#21-introspect-your-database)
* [2.2. Create a baseline migration](https://www.prisma.io/docs/guides/migrate-from-sequelize#22-create-a-baseline-migration)
* [3\. Update your application code](https://www.prisma.io/docs/guides/migrate-from-sequelize#3-update-your-application-code)
* [3.1. Install Prisma Client](https://www.prisma.io/docs/guides/migrate-from-sequelize#31-install-prisma-client)
* [3.2. Replace Sequelize queries](https://www.prisma.io/docs/guides/migrate-from-sequelize#32-replace-sequelize-queries)
* [3.3. Update your controllers](https://www.prisma.io/docs/guides/migrate-from-sequelize#33-update-your-controllers)
* [Next steps](https://www.prisma.io/docs/guides/migrate-from-sequelize#next-steps)
---
# How to migrate from TypeORM to Prisma ORM | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/migrate-from-typeorm#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/migrate-from-typeorm#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------------
This guide shows you how to migrate your application from TypeORM to Prisma ORM. We'll use an extended version of the [TypeORM Express example](https://github.com/typeorm/typescript-express-example/)
as a [sample project](https://github.com/prisma/migrate-from-typeorm-to-prisma)
to demonstrate the migration steps.
This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma ORM](https://www.prisma.io/docs/orm/reference/supported-databases)
. You can learn how Prisma ORM compares to TypeORM on the [Prisma ORM vs TypeORM](https://www.prisma.io/docs/orm/more/comparisons/prisma-and-typeorm)
page.
Prerequisites[](https://www.prisma.io/docs/guides/migrate-from-typeorm#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------------
Before starting this guide, make sure you have:
* A TypeORM project you want to migrate
* Node.js installed (version 16 or higher)
* PostgreSQL or another supported database
* Basic familiarity with TypeORM and Express.js
2\. Prepare for migration[](https://www.prisma.io/docs/guides/migrate-from-typeorm#2-prepare-for-migration "Direct link to 2. Prepare for migration")
-------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Understand the migration process[](https://www.prisma.io/docs/guides/migrate-from-typeorm#21-understand-the-migration-process "Direct link to 2.1. Understand the migration process")
The steps for migrating from TypeORM to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
1. Install the Prisma CLI
2. Introspect your database
3. Create a baseline migration
4. Install Prisma Client
5. Gradually replace your TypeORM queries with Prisma Client
These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses TypeORM for database access.
### 2.2. Set up Prisma configuration[](https://www.prisma.io/docs/guides/migrate-from-typeorm#22-set-up-prisma-configuration "Direct link to 2.2. Set up Prisma configuration")
Create a new Prisma schema file:
npx prisma init --output ../generated/prisma
Update the `DATABASE_URL` in the `.env` file with your database connection string:
DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
3\. Migrate the database schema[](https://www.prisma.io/docs/guides/migrate-from-typeorm#3-migrate-the-database-schema "Direct link to 3. Migrate the database schema")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Introspect your database[](https://www.prisma.io/docs/guides/migrate-from-typeorm#31-introspect-your-database "Direct link to 3.1. Introspect your database")
Run Prisma's introspection to create the Prisma schema from your existing database:
npx prisma db pull
This will create a `schema.prisma` file with your database schema.
### 3.2. Create a baseline migration[](https://www.prisma.io/docs/guides/migrate-from-typeorm#32-create-a-baseline-migration "Direct link to 3.2. Create a baseline migration")
Create and apply a baseline migration to mark the current state of your database:
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > baseline.sqlnpx prisma migrate resolve --applied "baseline"
4\. Update your application code[](https://www.prisma.io/docs/guides/migrate-from-typeorm#4-update-your-application-code "Direct link to 4. Update your application code")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 4.1. Install Prisma Client[](https://www.prisma.io/docs/guides/migrate-from-typeorm#41-install-prisma-client "Direct link to 4.1. Install Prisma Client")
Install the Prisma Client package:
npm install @prisma/client
Generate Prisma Client:
npx prisma generate
### 4.2. Replace TypeORM queries[](https://www.prisma.io/docs/guides/migrate-from-typeorm#42-replace-typeorm-queries "Direct link to 4.2. Replace TypeORM queries")
Start replacing your TypeORM queries with Prisma Client. Here's an example of how to convert some common queries:
* TypeORM
* Prisma Client
// Find oneconst user = await userRepository.findOne({ where: { id: 1 } });// Createconst user = await userRepository.save({ email: 'alice@prisma.io', name: 'Alice'});// Updateawait userRepository.update(1, { name: 'New name' });// Deleteawait userRepository.delete(1);
// Find oneconst user = await prisma.user.findUnique({ where: { id: 1 } });// Createconst user = await prisma.user.create({ data: { email: 'alice@prisma.io', name: 'Alice' }});// Updateawait prisma.user.update({ where: { id: 1 }, data: { name: 'New name' }});// Deleteawait prisma.user.delete({ where: { id: 1 }});
### 4.3. Update your controllers[](https://www.prisma.io/docs/guides/migrate-from-typeorm#43-update-your-controllers "Direct link to 4.3. Update your controllers")
Update your Express controllers to use Prisma Client. For example, here's how to update the `CreateUserAction`:
import { prisma } from '../client'export class CreateUserAction { async run(req: Request, res: Response) { const { email, name } = req.body const result = await prisma.user.create({ data: { email, name, }, }) return res.json(result) }}
5\. Test and deploy[](https://www.prisma.io/docs/guides/migrate-from-typeorm#5-test-and-deploy "Direct link to 5. Test and deploy")
-------------------------------------------------------------------------------------------------------------------------------------
### 5.1. Test your changes[](https://www.prisma.io/docs/guides/migrate-from-typeorm#51-test-your-changes "Direct link to 5.1. Test your changes")
Test all migrated endpoints to ensure they work as expected:
npm test
### 5.2. Deploy your changes[](https://www.prisma.io/docs/guides/migrate-from-typeorm#52-deploy-your-changes "Direct link to 5.2. Deploy your changes")
1. Deploy your schema changes:
npx prisma migrate deploy
2. Deploy your application code with the updated dependencies.
Next steps[](https://www.prisma.io/docs/guides/migrate-from-typeorm#next-steps "Direct link to Next steps")
-------------------------------------------------------------------------------------------------------------
Now that you've migrated to Prisma ORM, you can:
* Add more complex queries using Prisma's powerful query API
* Set up Prisma Studio for database management
* Implement database monitoring
* Add automated tests using Prisma's testing utilities
For more information:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/migrate-from-typeorm%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/migrate-from-typeorm%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/migrate-from-typeorm%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/030-migrate-from-typeorm.mdx)
* [Introduction](https://www.prisma.io/docs/guides/migrate-from-typeorm#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/migrate-from-typeorm#prerequisites)
* [2\. Prepare for migration](https://www.prisma.io/docs/guides/migrate-from-typeorm#2-prepare-for-migration)
* [2.1. Understand the migration process](https://www.prisma.io/docs/guides/migrate-from-typeorm#21-understand-the-migration-process)
* [2.2. Set up Prisma configuration](https://www.prisma.io/docs/guides/migrate-from-typeorm#22-set-up-prisma-configuration)
* [3\. Migrate the database schema](https://www.prisma.io/docs/guides/migrate-from-typeorm#3-migrate-the-database-schema)
* [3.1. Introspect your database](https://www.prisma.io/docs/guides/migrate-from-typeorm#31-introspect-your-database)
* [3.2. Create a baseline migration](https://www.prisma.io/docs/guides/migrate-from-typeorm#32-create-a-baseline-migration)
* [4\. Update your application code](https://www.prisma.io/docs/guides/migrate-from-typeorm#4-update-your-application-code)
* [4.1. Install Prisma Client](https://www.prisma.io/docs/guides/migrate-from-typeorm#41-install-prisma-client)
* [4.2. Replace TypeORM queries](https://www.prisma.io/docs/guides/migrate-from-typeorm#42-replace-typeorm-queries)
* [4.3. Update your controllers](https://www.prisma.io/docs/guides/migrate-from-typeorm#43-update-your-controllers)
* [5\. Test and deploy](https://www.prisma.io/docs/guides/migrate-from-typeorm#5-test-and-deploy)
* [5.1. Test your changes](https://www.prisma.io/docs/guides/migrate-from-typeorm#51-test-your-changes)
* [5.2. Deploy your changes](https://www.prisma.io/docs/guides/migrate-from-typeorm#52-deploy-your-changes)
* [Next steps](https://www.prisma.io/docs/guides/migrate-from-typeorm#next-steps)
---
# How to use multiple databases in a single app | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/multiple-databases#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/multiple-databases#introduction "Direct link to Introduction")
-----------------------------------------------------------------------------------------------------------------
This guide shows you how to use multiple databases using Prisma ORM in a single [Next.js app](https://nextjs.org/)
. You will learn how to connect to two different Prisma Postgres databases, manage migrations, and deploy your application to Vercel. This approach is useful for multi-tenant applications or when you need to separate concerns when managing connections to multiple databases.
Prerequisites[](https://www.prisma.io/docs/guides/multiple-databases#prerequisites "Direct link to Prerequisites")
--------------------------------------------------------------------------------------------------------------------
Before you begin, make sure that you have the following:
* Node.js 18+ installed.
* A [Prisma Data Platform account](https://pris.ly/pdp?utm_campaign=multi-client&utm_source=docs)
.
* A Vercel account (if you plan to deploy your application).
1\. Set up a Next.js project[](https://www.prisma.io/docs/guides/multiple-databases#1-set-up-a-nextjs-project "Direct link to 1. Set up a Next.js project")
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Create a new Next.js app using `create-next-app` from your desired directory:
npx create-next-app@latest my-multi-client-app
You will be prompted to answer a few questions about your project. Select all of the defaults.
info
For completeness, those are:
* TypeScript
* ESLint
* Tailwind CSS
* No `src` directory
* App Router
* Turbopack
* Default custom import alias: `@/*`
Then, navigate to the project directory:
cd my-multi-client-app
2\. Set up your databases and Prisma Clients[](https://www.prisma.io/docs/guides/multiple-databases#2-set-up-your-databases-and-prisma-clients "Direct link to 2. Set up your databases and Prisma Clients")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In this section, you will create two separate Prisma Postgres instances—one for user data and one for post data. You will also configure the Prisma schema and environment variables for each.
First, install Prisma as a development dependency:
npm install -D prisma
Install the [Prisma Client extension](https://www.npmjs.com/package/@prisma/extension-accelerate)
that is required to use Prisma Postgres:
npm install @prisma/extension-accelerate
info
If you are not using a Prisma Postgres database, you won't need the `@prisma/extension-accelerate` package.
You have installed the required dependencies for the project.
### 2.1. Create a Prisma Postgres instance to contain user data[](https://www.prisma.io/docs/guides/multiple-databases#21-create-a-prisma-postgres-instance-to-contain-user-data "Direct link to 2.1. Create a Prisma Postgres instance to contain user data")
Initialize Prisma with a [Prisma Postgres](https://www.prisma.io/docs/postgres)
instance by running:
npx prisma@latest init --db
info
If you are not using a Prisma Postgres database, do not use the `--db` flag. Instead, create two PostgreSQL database instances and add their connection URLs to the `.env` file as `PPG_USER_DATABASE_URL` and `PPG_POST_DATABASE_URL`.
Follow the prompts to name your project and choose a database region.
The `prisma@latest init --db` command:
* Connects your CLI to your account. If you are not logged in or do not 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 a `schema.prisma` file for your database models.
* Creates a `.env` file with your `DATABASE_URL` (e.g., for Prisma Postgres it should have something similar to `DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."`).
Rename the `prisma` folder to `prisma-user-database`:
mv prisma prisma-user-database
Edit your `.env` file to rename `DATABASE_URL` to `PPG_USER_DATABASE_URL`:
.env
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI...PPG_USER_DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI...
Open `prisma-user-database/schema.prisma` file and update it to define a `User` model. Also, set the environment variable and specify a [custom `output` directory](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
for the generated Prisma Client:
prisma-user-database/schema.prisma
generator client { provider = "prisma-client-js" output = "../prisma-user-database/user-database-client-types"}datasource db { provider = "postgresql" url = env("DATABASE_URL") url = env("PPG_USER_DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String?}
Your user database schema is now ready.
### 2.2. Create a Prisma Postgres instance for post data[](https://www.prisma.io/docs/guides/multiple-databases#22-create-a-prisma-postgres-instance-for-post-data "Direct link to 2.2. Create a Prisma Postgres instance for post data")
Repeat the initialization for the post database:
npx prisma init --db
After following the prompts, rename the new `prisma` folder to `prisma-post-database`:
mv prisma prisma-post-database
Rename the `DATABASE_URL` variable in `.env` to `PPG_POST_DATABASE_URL`:
.env
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI...PPG_POST_DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI...
Edit the `prisma-post-database/schema.prisma` file to define a `Post` model. Also, update the datasource URL and set a [custom `output` directory](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
:
prisma-post-database/schema.prisma
generator client { provider = "prisma-client-js" output = "../prisma-post-database/post-database-client-types"}datasource db { provider = "postgresql" url = env("DATABASE_URL") url = env("PPG_POST_DATABASE_URL")}model Post { id Int @id @default(autoincrement()) title String content String?}
Your post database schema is now set.
### 2.3. Add helper scripts and migrate the schemas[](https://www.prisma.io/docs/guides/multiple-databases#23-add-helper-scripts-and-migrate-the-schemas "Direct link to 2.3. Add helper scripts and migrate the schemas")
To simplify your workflow, add helper scripts to your `package.json` file that run Prisma commands for both databases:
package.json
"script":{ "dev": "next dev --turbopack", "build": "next build", "start": "next start", "lint": "next lint", "postinstall": "npx prisma generate --schema ./prisma-user-database/schema.prisma --no-engine && npx prisma generate --schema ./prisma-post-database/schema.prisma --no-engine", "generate": "npx prisma generate --schema ./prisma-user-database/schema.prisma --no-engine && npx prisma generate --schema ./prisma-post-database/schema.prisma --no-engine", "migrate": "npx prisma migrate dev --schema ./prisma-user-database/schema.prisma && npx prisma migrate dev --schema ./prisma-post-database/schema.prisma", "deploy": "npx prisma migrate deploy --schema ./prisma-user-database/schema.prisma && npx prisma migrate deploy --schema ./prisma-post-database/schema.prisma", "studio": "npx prisma studio --schema ./prisma-user-database/schema.prisma --port 5555 & npx prisma studio --schema ./prisma-post-database/schema.prisma --port 5556"}
info
If you are not using a Prisma Postgres database, remove the `--no-engine` flag from the custom scripts above.
Here is an explanation of the custom scripts:
* `postinstall`: Runs immediately after installing dependencies to generate Prisma Clients for both the user and post databases using their respective schema files.
* `generate`: Manually triggers the generation of Prisma Clients for both schemas, ensuring your client code reflects the latest models.
* `migrate`: Applies pending migrations in development mode for both databases using [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate)
, updating their schemas based on changes in your Prisma files.
* `deploy`: Executes migrations in a production environment, synchronizing your live databases with your Prisma schemas.
* `studio`: Opens Prisma Studio for both databases simultaneously on different ports (`5555` for the user database and `5556` for the post database) for visual data management.
Run the migrations:
npm run migrate
When prompted, name the migration for each database accordingly.
3\. Prepare the application to use multiple Prisma Clients[](https://www.prisma.io/docs/guides/multiple-databases#3-prepare-the-application-to-use-multiple-prisma-clients "Direct link to 3. Prepare the application to use multiple Prisma Clients")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Next, create a `lib` folder to store helper files for instantiating and exporting your Prisma Clients:
mkdir -p lib && touch lib/user-prisma-client.ts lib/post-prisma-client.ts
### 3.1. Instantiate and export the Prisma Client for the user database[](https://www.prisma.io/docs/guides/multiple-databases#31-instantiate-and-export-the-prisma-client-for-the-user-database "Direct link to 3.1. Instantiate and export the Prisma Client for the user database")
In `lib/user-prisma-client.ts`, add the following code:
lib/user-prisma-client.ts
import { PrismaClient } from "../prisma-user-database/user-database-client-types";import { withAccelerate } from "@prisma/extension-accelerate"const getPrisma = () => new PrismaClient().$extends(withAccelerate());const globalForUserDBPrismaClient = global as unknown as { userDBPrismaClient: ReturnType;};export const userDBPrismaClient = globalForUserDBPrismaClient.userDBPrismaClient || getPrisma();if (process.env.NODE_ENV !== "production") globalForUserDBPrismaClient.userDBPrismaClient = userDBPrismaClient;
info
If you are not using a Prisma Postgres database, do not extend `PrismaClient` with the `withAccelerate` client extension.
### 3.2. Instantiate and export the Prisma Client for the post database[](https://www.prisma.io/docs/guides/multiple-databases#32-instantiate-and-export-the-prisma-client-for-the-post-database "Direct link to 3.2. Instantiate and export the Prisma Client for the post database")
In `lib/post-prisma-client.ts`, add this code:
lib/post-prisma-client.ts
import { PrismaClient } from "../prisma-post-database/post-database-client-types";import { withAccelerate } from "@prisma/extension-accelerate"const getPrisma = () => new PrismaClient().$extends(withAccelerate());const globalForPostDBPrismaClient = global as unknown as { postDBPrismaClient: ReturnType;};export const postDBPrismaClient = globalForPostDBPrismaClient.postDBPrismaClient || getPrisma();if (process.env.NODE_ENV !== "production") globalForPostDBPrismaClient.postDBPrismaClient = postDBPrismaClient;
info
If you are not using a Prisma Postgres database, do not extend `PrismaClient` with the `withAccelerate` client extension.
4\. Integrate multiple Prisma Clients in your Next.js app[](https://www.prisma.io/docs/guides/multiple-databases#4-integrate-multiple-prisma-clients-in-your-nextjs-app "Direct link to 4. Integrate multiple Prisma Clients in your Next.js app")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Modify your application code to fetch data from both databases. Update the `app/page.tsx` file as follows:
app/page.tsx
import { postDBPrismaClient } from "@/lib/post-prisma-client";import { userDBPrismaClient } from "@/lib/user-prisma-client";export default async function Home() { const user = await userDBPrismaClient.user.findFirst(); const post = await postDBPrismaClient.post.findFirst(); return (
Multi-DB Showcase
Data fetched from two distinct databases.
User Data
{user ? JSON.stringify(user, null, 2) : "No user data available."}
Post Data
{post ? JSON.stringify(post, null, 2) : "No post data available."}
);}
### 4.1. Populate your databases with data[](https://www.prisma.io/docs/guides/multiple-databases#41-populate-your-databases-with-data "Direct link to 4.1. Populate your databases with data")
In a separate terminal window, open two instances of [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
to add data to your databases by running the script:
npm run studio
This will open up two browser windows, one in `http://localhost:5555` and one in `http://localhost:5556`. Navigate to those windows and add sample data to both databases.
### 4.2. Run the development server[](https://www.prisma.io/docs/guides/multiple-databases#42-run-the-development-server "Direct link to 4.2. Run the development server")
Before starting the development server, note that if you are using Next.js `v15.2.0`, do not use Turbopack as there is a known [issue](https://github.com/vercel/next.js/issues/76497)
. Remove Turbopack from your dev script by updating your `package.json`:
package.json
"script":{ "dev": "next dev --turbopack", "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "postinstall": "npx prisma generate --schema ./prisma-user-database/schema.prisma --no-engine && npx prisma generate --schema ./prisma-post-database/schema.prisma --no-engine", "generate": "npx prisma generate --schema ./prisma-user-database/schema.prisma --no-engine && npx prisma generate --schema ./prisma-post-database/schema.prisma --no-engine", "migrate": "npx prisma migrate dev --schema ./prisma-user-database/schema.prisma && npx prisma migrate dev --schema ./prisma-post-database/schema.prisma", "deploy": "npx prisma migrate deploy --schema ./prisma-user-database/schema.prisma && npx prisma migrate deploy --schema ./prisma-post-database/schema.prisma", "studio": "npx prisma studio --schema ./prisma-user-database/schema.prisma --port 5555 & npx prisma studio --schema ./prisma-post-database/schema.prisma --port 5556"}
In a separate terminal window, start the development server by running:
npm run dev
Navigate to `http://localhost:3000` to see your Next.js app display data from both databases:

Congratulations, you have a Next.js app running with two Prisma Client instances querying different databases.
5\. Deploy your Next.js app using multiple databases to Vercel[](https://www.prisma.io/docs/guides/multiple-databases#5-deploy-your-nextjs-app-using-multiple-databases-to-vercel "Direct link to 5. Deploy your Next.js app using multiple databases to Vercel")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Deploy your app by following these steps:
1. Ensure your project is version-controlled and pushed to a GitHub repository. If you do not have a repository yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)
. Once the repository is ready, run the following commands:
git add .git commit -m "Initial commit with Prisma Postgres integration"git branch -M maingit remote add origin https://github.com//.gitgit push -u origin main
note
Replace `` and `` with your GitHub username and the name of your repository.
2. Log in to [Vercel](https://vercel.com/)
and navigate to your [Dashboard](https://vercel.com/docs/dashboard-features)
.
3. Create a new project. Follow Vercel's [Import an existing project](https://vercel.com/docs/getting-started-with-vercel/import)
guide, but stop at [step 3](https://vercel.com/docs/getting-started-with-vercel/import#optionally-configure-any-settings)
where you will configure environment variables _before_ clicking **Deploy**.
4. Configure the `DATABASE_URL` environment variable:
1. Expand the **Environment variables** section.
2. Add the `PPG_USER_DATABASE_URL` environment variable:
* **Key**: `PPG_USER_DATABASE_URL`
* **Value**: Paste your user database connection URL, e.g. by copying it from the `.env` file in your project.
3. Add the `PPG_POST_DATABASE_URL` environment variable:
* **Key**: `PPG_POST_DATABASE_URL`
* **Value**: Paste your post database connection URL, e.g. by copying it from the `.env` file in your project.
warning
Do not deploy without setting the environment variables. Your deployment will fail if the application cannot connect to the databases.
5. Click the **Deploy** button. Vercel will build your project and deploy it to a live URL.
Open the live URL provided by Vercel and verify that your application is working.
Congratulations! You have deployed an application that uses multiple Prisma Clients to query two different databases, and it is now live and fully operational on Vercel.
Next steps[](https://www.prisma.io/docs/guides/multiple-databases#next-steps "Direct link to Next steps")
-----------------------------------------------------------------------------------------------------------
In this guide, you learned how to use multiple databases using Prisma ORM in a single Next.js app by:
* Setting up separate Prisma schemas for user and post databases.
* Configuring custom output directories and environment variables.
* Creating helper scripts to generate and migrate each schema.
* Instantiating and integrating multiple Prisma Clients into your application.
* Deploying your multi-database application to Vercel.
This approach allows you to maintain a clear separation of data models and simplifies multi-tenant or multi-database scenarios.
For further improvements in managing your project, consider using a monorepo setup. Check out our related guides:
* [How to use Prisma ORM in a pnpm workspaces monorepo](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces)
* [How to use Prisma ORM with Turborepo](https://www.prisma.io/docs/guides/turborepo)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/multiple-databases%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/multiple-databases%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/multiple-databases%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/150-multiple-databases.mdx)
* [Introduction](https://www.prisma.io/docs/guides/multiple-databases#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/multiple-databases#prerequisites)
* [1\. Set up a Next.js project](https://www.prisma.io/docs/guides/multiple-databases#1-set-up-a-nextjs-project)
* [2\. Set up your databases and Prisma Clients](https://www.prisma.io/docs/guides/multiple-databases#2-set-up-your-databases-and-prisma-clients)
* [2.1. Create a Prisma Postgres instance to contain user data](https://www.prisma.io/docs/guides/multiple-databases#21-create-a-prisma-postgres-instance-to-contain-user-data)
* [2.2. Create a Prisma Postgres instance for post data](https://www.prisma.io/docs/guides/multiple-databases#22-create-a-prisma-postgres-instance-for-post-data)
* [2.3. Add helper scripts and migrate the schemas](https://www.prisma.io/docs/guides/multiple-databases#23-add-helper-scripts-and-migrate-the-schemas)
* [3\. Prepare the application to use multiple Prisma Clients](https://www.prisma.io/docs/guides/multiple-databases#3-prepare-the-application-to-use-multiple-prisma-clients)
* [3.1. Instantiate and export the Prisma Client for the user database](https://www.prisma.io/docs/guides/multiple-databases#31-instantiate-and-export-the-prisma-client-for-the-user-database)
* [3.2. Instantiate and export the Prisma Client for the post database](https://www.prisma.io/docs/guides/multiple-databases#32-instantiate-and-export-the-prisma-client-for-the-post-database)
* [4\. Integrate multiple Prisma Clients in your Next.js app](https://www.prisma.io/docs/guides/multiple-databases#4-integrate-multiple-prisma-clients-in-your-nextjs-app)
* [4.1. Populate your databases with data](https://www.prisma.io/docs/guides/multiple-databases#41-populate-your-databases-with-data)
* [4.2. Run the development server](https://www.prisma.io/docs/guides/multiple-databases#42-run-the-development-server)
* [5\. Deploy your Next.js app using multiple databases to Vercel](https://www.prisma.io/docs/guides/multiple-databases#5-deploy-your-nextjs-app-using-multiple-databases-to-vercel)
* [Next steps](https://www.prisma.io/docs/guides/multiple-databases#next-steps)
---
# Set up PostgreSQL on Neon with Prisma Accelerate's Connection Pool | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/neon-accelerate#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/neon-accelerate#introduction "Direct link to Introduction")
--------------------------------------------------------------------------------------------------------------
This guides teaches you how to add connection pooling to a PostgreSQL database hosted on [Neon](https://neon.tech/)
using [Prisma Accelerate](https://www.prisma.io/docs/accelerate)
.
Prisma Accelerate is a robust and mature connection pooler enabling your database to function properly during traffic spikes and high load scenarios. Check out this [video](https://www.youtube.com/watch?v=cnL75if6Aq0)
demonstrating how it performs in a load test or [learn why connection pooling is important](https://www.prisma.io/blog/saving-black-friday-with-connection-pooling)
.
Prerequisites[](https://www.prisma.io/docs/guides/neon-accelerate#prerequisites "Direct link to Prerequisites")
-----------------------------------------------------------------------------------------------------------------
To successfully complete this guide, you need **a connection string for a PostgreSQL instance hosted on Neon**. It typically looks similar to this:
postgresql://neondb_owner:[YOUR-PASSWORD]@ep-lingering-hat-a2e7tkt3.eu-central-1.aws.neon.tech/neondb?sslmode=require
If you already have a project using Prisma ORM, you can skip the first two steps and jump ahead to [Step 3. Install the Accelerate extension](https://www.prisma.io/docs/guides/neon-accelerate#3-install-the-accelerate-extension)
.
1\. Set up Prisma ORM[](https://www.prisma.io/docs/guides/neon-accelerate#1-set-up-prisma-orm "Direct link to 1. Set up Prisma ORM")
--------------------------------------------------------------------------------------------------------------------------------------
Start by installing the Prisma CLI in your project:
npm install prisma --save-dev
Then, run the following command to initialize a new project:
npx prisma init
This will create a new `prisma` directory with a `schema.prisma` file and add a `.env` file with the `DATABASE_URL` environment variable.
Update the file and set the `DATABASE_URL` to your Neon connection string:
.env
DATABASE_URL="postgresql://neondb_owner:[YOUR-PASSWORD]@ep-lingering-hat-a2e7tkt3.eu-central-1.aws.neon.tech/neondb?sslmode=require"
2\. Introspect your database[](https://www.prisma.io/docs/guides/neon-accelerate#2-introspect-your-database "Direct link to 2. Introspect your database")
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Next, run the following command to introspect your database and create your data model:
npx prisma db pull
This command reads your database schema and creates new models in your `schema.prisma` file that match the tables in your database.
note
If you want to use Prisma Migrate in the future, you also need to [baseline your database](https://www.prisma.io/docs/orm/prisma-migrate/workflows/baselining)
.
3\. Install the Accelerate extension[](https://www.prisma.io/docs/guides/neon-accelerate#3-install-the-accelerate-extension "Direct link to 3. Install the Accelerate extension")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Install the Prisma Client extension for Accelerate:
npm install @prisma/extension-accelerate
This is needed to access Prisma Accelerate's connection pool.
4\. Set up Accelerate in the Prisma Console[](https://www.prisma.io/docs/guides/neon-accelerate#4-set-up-accelerate-in-the-prisma-console "Direct link to 4. Set up Accelerate in the Prisma Console")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To set up Accelerate in the Prisma Console, follow these steps:
1. Log into the .
2. Select **New project**
3. Choose a **Name** for your project
4. In the **Choose your starting product** section, find the **Accelerate** card and click **Get started**
5. In the field for your **Database connection string**, paste your Neon connection string
6. Select the **Region** that's closest to your database
7. Click **Create project**
8. On the next screen, click **Enable Accelerate**
Once you went through these steps, you'll be redirected to another page where you need to the click the **Generate API key** button.
You'll then be shown a new connection URL which enables you to connect to Prisma Accelerate's connection pool. This needs to be set as the new `DATABASE_URL` in your `.env` file:
.env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=ey..."
note
If you want to use Prisma Migrate with Prisma Accelerate, you can set the `directUrl` field on the `datasource` block:
schema.prisma
datasource db { url = env("DATABASE_URL") // points to the connection pool for queries directUrl = env("DIRECT_URL") // points to the database for migrations}
Accordingly, you'll need to set the `DIRECT_URL` in your `.env` file:
.env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=ey..."DIRECT_URL="postgresql://neondb_owner:[YOUR-PASSWORD]@ep-lingering-hat-a2e7tkt3.eu-central-1.aws.neon.tech/neondb?sslmode=require"
5\. Generate Prisma Client[](https://www.prisma.io/docs/guides/neon-accelerate#5-generate-prisma-client "Direct link to 5. Generate Prisma Client")
-----------------------------------------------------------------------------------------------------------------------------------------------------
With your Prisma schema in place, you can go ahead and generate Prisma Client:
npx prisma generate --no-engine
The `--no-engine` option is used to omit the [query engine](https://www.prisma.io/docs/orm/more/under-the-hood/engines)
in the generated Prisma Client library. The query engine manages Prisma ORM's internal connection pool and is not needed when using Prisma Accelerate.
6\. Send queries through the connection pool[](https://www.prisma.io/docs/guides/neon-accelerate#6-send-queries-through-the-connection-pool "Direct link to 6. Send queries through the connection pool")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In your application code, you now need to apply the Accelerate extension to your Prisma Client instance:
import { PrismaClient } from "./generated/prisma"import { withAccelerate } from "@prisma/extension-accelerate"const prisma = new PrismaClient().$extends(withAccelerate())
At this point, you can now start sending queries which will be routed through the connection pool to your database.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/neon-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/neon-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/neon-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/310-neon-accelerate.mdx)
* [Introduction](https://www.prisma.io/docs/guides/neon-accelerate#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/neon-accelerate#prerequisites)
* [1\. Set up Prisma ORM](https://www.prisma.io/docs/guides/neon-accelerate#1-set-up-prisma-orm)
* [2\. Introspect your database](https://www.prisma.io/docs/guides/neon-accelerate#2-introspect-your-database)
* [3\. Install the Accelerate extension](https://www.prisma.io/docs/guides/neon-accelerate#3-install-the-accelerate-extension)
* [4\. Set up Accelerate in the Prisma Console](https://www.prisma.io/docs/guides/neon-accelerate#4-set-up-accelerate-in-the-prisma-console)
* [5\. Generate Prisma Client](https://www.prisma.io/docs/guides/neon-accelerate#5-generate-prisma-client)
* [6\. Send queries through the connection pool](https://www.prisma.io/docs/guides/neon-accelerate#6-send-queries-through-the-connection-pool)
---
# How to use Prisma ORM and Prisma Postgres with Next.js 15 and Vercel | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/nextjs#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/nextjs#introduction "Direct link to Introduction")
-----------------------------------------------------------------------------------------------------
This guide shows you how to use Prisma with Next.js 15, a fullstack React framework. You'll learn how to create a [Prisma Postgres](https://www.prisma.io/docs/postgres)
instance, set up Prisma ORM with Next.js, handle migrations, and deploy your application to Vercel.
You can find a [deployment-ready example on GitHub](https://github.com/prisma/prisma-examples/blob/latest/orm/nextjs)
.
Prerequisites[](https://www.prisma.io/docs/guides/nextjs#prerequisites "Direct link to Prerequisites")
--------------------------------------------------------------------------------------------------------
* [Node.js 18+](https://nodejs.org/)
* A Vercel account (if you want to deploy your application)
1\. Set up your project[](https://www.prisma.io/docs/guides/nextjs#1-set-up-your-project "Direct link to 1. Set up your project")
-----------------------------------------------------------------------------------------------------------------------------------
From the directory where you want to create your project, run `create-next-app` to create a new Next.js app that you will be using for this guide.
npx create-next-app@latest nextjs-prisma
You will be prompted to answer a few questions about your project. Select all of the defaults.
info
For reference, those are:
* TypeScript
* ESLint
* Tailwind CSS
* No `src` directory
* App Router
* Turbopack
* No customized import alias
Then, navigate to the project directory:
cd nextjs-prisma
2\. Install and Configure Prisma[](https://www.prisma.io/docs/guides/nextjs#2-install-and-configure-prisma "Direct link to 2. Install and Configure Prisma")
--------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/nextjs#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, you'll need to install a few dependencies:
* Prisma Postgres (recommended)
* Other databases
npm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client
npm install prisma tsx --save-devnpm install @prisma/client
Once installed, initialize Prisma in your project:
npx prisma init --db --output ../app/generated/prisma
info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My \_\_\_\_\_\_\_\_\_\_ Project"
This will create:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `app/generated/prisma`.
### 2.2. Define your Prisma Schema[](https://www.prisma.io/docs/guides/nextjs#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma Schema")
In the `prisma/schema.prisma` file, add the following models:
prisma/schema.prisma
generator client { provider = "prisma-client-js" output = "../app/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
### 2.3. Configure the Prisma Client generator[](https://www.prisma.io/docs/guides/nextjs#23-configure-the-prisma-client-generator "Direct link to 2.3. Configure the Prisma Client generator")
Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/nextjs#24-seed-the-database "Direct link to 2.4. Seed the database")
Add some seed data to populate the database with sample users and posts.
Create a new file called `seed.ts` in the `prisma/` directory:
prisma/seed.ts
import { PrismaClient, Prisma } from "../app/generated/prisma";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();
Now, tell Prisma how to run this script by updating your `package.json`:
package.json
{ "name": "nextjs-prisma", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev --turbopack", "build": "next build", "start": "next start", "lint": "next lint" }, "prisma": { "seed": "tsx prisma/seed.ts" }, "dependencies": { "@prisma/client": "^6.7.0", "@prisma/extension-accelerate": "^1.3.0", "next": "15.3.1", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@eslint/eslintrc": "^3", "@tailwindcss/postcss": "^4", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "15.3.1", "prisma": "^6.7.0", "tailwindcss": "^4", "tsx": "^4.19.4", "typescript": "^5" }}
warning
Before starting the development server, note that if you are using Next.js v15.2.0 or v15.2.1, do not use Turbopack as there is a known [issue](https://github.com/vercel/next.js/issues/76497)
. Remove Turbopack from your dev script by updating your `package.json`
package.json
"script":{ "dev": "next dev --turbopack", "dev": "next dev",}
This change is not needed on any versions before or after.
Finally, run `prisma db seed` to seed your database with the initial data we defined in the `seed.ts` file.
Run the seed script:
npx prisma db seed
And open Prisma Studio to inspect your data:
npx prisma studio
### 2.5 Set up Prisma Client[](https://www.prisma.io/docs/guides/nextjs#25-set-up-prisma-client "Direct link to 2.5 Set up Prisma Client")
Now that you have a database with some initial data, you can set up Prisma Client and connect it to your database.
At the root of your project, create a new `lib` directory and add a `prisma.ts` file to it.
mkdir -p lib && touch lib/prisma.ts
Now, add the following code to your `lib/prisma.ts` file:
* Prisma Postgres (recommended)
* Other databases
lib/prisma.ts
import { PrismaClient } from '../app/generated/prisma'import { withAccelerate } from '@prisma/extension-accelerate'const globalForPrisma = global as unknown as { prisma: PrismaClient}const prisma = globalForPrisma.prisma || new PrismaClient().$extends(withAccelerate())if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prismaexport default prisma
lib/prisma.ts
import { PrismaClient } from '../src/app/generated/prisma'const globalForPrisma = global as unknown as { prisma: PrismaClient}const prisma = globalForPrisma.prisma || new PrismaClient()if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prismaexport default prisma
This file creates a Prisma Client and attaches it to the global object so that only one instance of the client is created in your application. This helps resolve issues with hot reloading that can occur when using Prisma ORM with Next.js in development mode.
You'll use this client in the next section to run your first queries.
3\. Query your database with Prisma ORM[](https://www.prisma.io/docs/guides/nextjs#3-query-your-database-with-prisma-orm "Direct link to 3. Query your database with Prisma ORM")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Now that you have an initialized Prisma Client, a connection to your database, and some initial data, you can start querying your data with Prisma ORM.
In this example, you'll make the "home" page of your application display all of your users.
Open the `app/page.tsx` file and replace the existing code with the following:
app/page.tsx
export default async function Home() { return (
Superblog
Alice
Bob
);}
This gives you a basic page with a title and a list of users. However, that list is static with hardcoded values. Let's update the page to fetch the users from your database and make it dynamic.
app/page.tsx
import prisma from '@/lib/prisma'export default async function Home() { const users = await prisma.user.findMany(); return (
Superblog
{users.map((user) => (
{user.name}
))}
);}
You are now importing your client, querying the `User` model for all users, and then displaying them in a list.
Now your home page is dynamic and will display the users from your database.
### 3.1 Update your data (optional)[](https://www.prisma.io/docs/guides/nextjs#31-update-your-data-optional "Direct link to 3.1 Update your data (optional)")
If you want to see what happens when data is updated, you could:
* update your `User` table via a SQL browser of your choice
* change your `seed.ts` file to add more users
* change the call to `prisma.user.findMany` to re-order the users, filter the users, or similar.
Just reload the page and you'll see the changes.
4\. Add a new Posts list page[](https://www.prisma.io/docs/guides/nextjs#4-add-a-new-posts-list-page "Direct link to 4. Add a new Posts list page")
-----------------------------------------------------------------------------------------------------------------------------------------------------
You have your home page working, but you should add a new page that displays all of your posts.
First create a new `posts` directory in the `app` directory and create a new `page.tsx` file inside of it.
mkdir -p app/posts && touch app/posts/page.tsx
Second, add the following code to the `app/posts/page.tsx` file:
app/posts/page.tsx
import prisma from "@/lib/prisma";export default async function Posts() { return (
Posts
My first post
);}
Now `localhost:3000/posts` will load, but the content is hardcoded again. Let's update it to be dynamic, similarly to the home page:
app/posts/page.tsx
import prisma from "@/lib/prisma";export default async function Posts() { const posts = await prisma.post.findMany({ include: { author: true, }, }); return (
Posts
{posts.map((post) => (
{post.title} by {post.author.name}
))}
);}
This works similarly to the home page, but instead of displaying users, it displays posts. You can also see that you've used `include` in your Prisma Client query to fetch the author of each post so you can display the author's name.
This "list view" is one of the most common patterns in web applications. You're going to add two more pages to your application which you'll also commonly need: a "detail view" and a "create view".
5\. Add a new Posts detail page[](https://www.prisma.io/docs/guides/nextjs#5-add-a-new-posts-detail-page "Direct link to 5. Add a new Posts detail page")
-----------------------------------------------------------------------------------------------------------------------------------------------------------
To complement the Posts list page, you'll add a Posts detail page.
In the `posts` directory, create a new `[id]` directory and a new `page.tsx` file inside of that.
mkdir -p app/posts/[id] && touch app/posts/[id]/page.tsx
This page will display a single post's title, content, and author. Just like your other pages, add the following code to the `app/posts/new/page.tsx` file:
app/posts/\[id\]/page.tsx
import prisma from "@/lib/prisma";export default async function Post({ params }: { params: Promise<{ id: string }> }) { return (
My first post
by Anonymous
No content available.
);}
As before, this page is static with hardcoded content. Let's update it to be dynamic based on the `params` passed to the page:
app/posts/\[id\]/page.tsx
import prisma from "@/lib/prisma";import { notFound } from "next/navigation";export default async function Post({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const post = await prisma.post.findUnique({ where: { id: parseInt(id) }, include: { author: true, }, }); if (!post) { notFound(); } return (
{post.title}
by {post.author.name}
{post.content || "No content available."}
);}
There's a lot of changes here, so let's break it down:
* You're using Prisma Client to fetch the post by its `id`, which you get from the `params` object.
* In case the post doesn't exist (maybe it was deleted or maybe you typed a wrong ID), you call `notFound()` to display a 404 page.
* You then display the post's title, content, and author. If the post doesn't have content, you display a placeholder message.
It's not the prettiest page, but it's a good start. Try it out by navigating to `localhost:3000/posts/1` and `localhost:3000/posts/2`. You can also test the 404 page by navigating to `localhost:3000/posts/999`.
6\. Add a new Posts create page[](https://www.prisma.io/docs/guides/nextjs#6-add-a-new-posts-create-page "Direct link to 6. Add a new Posts create page")
-----------------------------------------------------------------------------------------------------------------------------------------------------------
To round out your application, you'll add a "create" page for posts. This will let you write your own posts and save them to the database.
As with the other pages, you'll start with a static page and then update it to be dynamic.
mkdir -p app/posts/new && touch app/posts/new/page.tsx
Now, add the following code to the `app/posts/new/page.tsx` file:
app/posts/new/page.tsx
import Form from "next/form";export default function NewPost() { async function createPost(formData: FormData) { "use server"; const title = formData.get("title") as string; const content = formData.get("content") as string; } return (
Create New Post
);}
This form looks good, but it doesn't do anything yet. Let's update the `createPost` function to save the post to the database:
app/posts/new/page.tsx
import Form from "next/form";import prisma from "@/lib/prisma";import { revalidatePath } from "next/cache";import { redirect } from "next/navigation";export default function NewPost() { async function createPost(formData: FormData) { "use server"; const title = formData.get("title") as string; const content = formData.get("content") as string; await prisma.post.create({ data: { title, content, authorId: 1, }, }); revalidatePath("/posts"); redirect("/posts"); } return (
Create New Post
);}
This page now has a functional form! When you submit the form, it will create a new post in the database and redirect you to the posts list page.
You also added a `revalidatePath` call to revalidate the posts list page so that it will be updated with the new post. That way everyone can read the new post immediately.
Try it out by navigating to `localhost:3000/posts/new` and submitting the form.
7\. Deploy your application to Vercel (Optional)[](https://www.prisma.io/docs/guides/nextjs#7-deploy-your-application-to-vercel-optional "Direct link to 7. Deploy your application to Vercel (Optional)")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The quickest way to deploy your application to Vercel is to use the [Vercel CLI](https://vercel.com/docs/cli)
.
First, install the Vercel CLI:
npm install -g vercel
Then, run `vercel login` to log in to your Vercel account.
vercel login
Before you deploy, you also need to tell Vercel to make sure that the Prisma Client is generated. You can do this by adding a `postinstall` script to your `package.json` file.
package.json
{ "name": "nextjs-prisma", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev --turbopack", "build": "next build", "postinstall": "prisma generate --no-engine", "start": "next start", "lint": "next lint" }, "prisma": { "seed": "tsx prisma/seed.ts" }, "dependencies": { "@prisma/client": "^6.2.1", "@prisma/extension-accelerate": "^1.2.1", "next": "15.1.4", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@eslint/eslintrc": "^3", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "15.1.4", "postcss": "^8", "prisma": "^6.2.1", "tailwindcss": "^3.4.1", "tsx": "^4.19.2", "typescript": "^5" }}
note
If you're not using Prisma Postgres, you need to remove the `--no-engine` flag from the command.
After this change, you can deploy your application to Vercel by running `vercel`.
vercel
After the deployment is complete, you can visit your application at the URL that Vercel provides. Congratulations, you've just deployed a Next.js application with Prisma ORM!
8\. Next steps[](https://www.prisma.io/docs/guides/nextjs#8-next-steps "Direct link to 8. Next steps")
--------------------------------------------------------------------------------------------------------
Now that you have a working Next.js application with Prisma ORM, here are some ways you can expand and improve your application:
* Add authentication to protect your routes
* Add the ability to edit and delete posts
* Add comments to posts
* Use [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
for visual database management
For more information:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
* [Next.js documentation](https://nextjs.org/docs)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/nextjs%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/nextjs%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/nextjs%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/090-nextjs.mdx)
* [Introduction](https://www.prisma.io/docs/guides/nextjs#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/nextjs#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/nextjs#1-set-up-your-project)
* [2\. Install and Configure Prisma](https://www.prisma.io/docs/guides/nextjs#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/nextjs#21-install-dependencies)
* [2.2. Define your Prisma Schema](https://www.prisma.io/docs/guides/nextjs#22-define-your-prisma-schema)
* [2.3. Configure the Prisma Client generator](https://www.prisma.io/docs/guides/nextjs#23-configure-the-prisma-client-generator)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/nextjs#24-seed-the-database)
* [2.5 Set up Prisma Client](https://www.prisma.io/docs/guides/nextjs#25-set-up-prisma-client)
* [3\. Query your database with Prisma ORM](https://www.prisma.io/docs/guides/nextjs#3-query-your-database-with-prisma-orm)
* [3.1 Update your data (optional)](https://www.prisma.io/docs/guides/nextjs#31-update-your-data-optional)
* [4\. Add a new Posts list page](https://www.prisma.io/docs/guides/nextjs#4-add-a-new-posts-list-page)
* [5\. Add a new Posts detail page](https://www.prisma.io/docs/guides/nextjs#5-add-a-new-posts-detail-page)
* [6\. Add a new Posts create page](https://www.prisma.io/docs/guides/nextjs#6-add-a-new-posts-create-page)
* [7\. Deploy your application to Vercel (Optional)](https://www.prisma.io/docs/guides/nextjs#7-deploy-your-application-to-vercel-optional)
* [8\. Next steps](https://www.prisma.io/docs/guides/nextjs#8-next-steps)
---
# Build a Nuxt app with Prisma ORM and Prisma Postgres | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/nuxt#__docusaurus_skipToContent_fallback)
On this page
This guide explains how to set up a Nuxt application, configure [Prisma Postgres](https://prisma.io/postgres)
using the [Prisma Nuxt module](https://www.prisma.io/docs/orm/more/help-and-troubleshooting/prisma-nuxt-module)
, and deploy the project to [Vercel](https://vercel.com/)
for production.
Here's what you'll learn:
* How to set up a Nuxt project with the Prisma Nuxt module.
* How to configure and use Prisma Postgres with the Prisma Nuxt module in your Nuxt app.
* How to deploy the project to Vercel.
Prerequisites[](https://www.prisma.io/docs/guides/nuxt#prerequisites "Direct link to Prerequisites")
------------------------------------------------------------------------------------------------------
To follow this guide, ensure you have the following:
* Node.js version: A [compatible Node.js version](https://www.prisma.io/docs/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-6#minimum-supported-nodejs-versions)
required for Prisma 6.
* Accounts:
* [GitHub](https://github.com/)
* [Vercel](https://vercel.com/)
* Basic knowledge of Git and Vercel deployment (helpful but not required).
1\. Create a New Nuxt Project and set up the Prisma Nuxt module[](https://www.prisma.io/docs/guides/nuxt#1-create-a-new-nuxt-project-and-set-up-the-prisma-nuxt-module "Direct link to 1. Create a New Nuxt Project and set up the Prisma Nuxt module")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Initialize [a new Nuxt project](https://nuxt.com/docs/getting-started/installation#new-project)
, select `npm` as the package manager and initialize git:
npm create nuxt hello-world
note
We recommend using `npm` as it is the most stable option with the `@prisma/nuxt` module.
2. Navigate into the project directory and install the `@prisma/nuxt` module:
cd hello-worldnpm i @prisma/nuxt
3. Install the [Prisma Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate)
as it's required to use Prisma Postgres:
npm i @prisma/extension-accelerate
4. Add the `@prisma/nuxt` module with the following configuration to your `nuxt.config.ts` file:
// https://nuxt.com/docs/api/configuration/nuxt-configexport default defineNuxtConfig({ compatibilityDate: "2024-11-01", modules: ["@prisma/nuxt"], experimental: { componentIslands: true, }, devtools: { enabled: true },});
2\. Setup Prisma ORM by running the development server locally[](https://www.prisma.io/docs/guides/nuxt#2-setup-prisma-orm-by-running-the-development-server-locally "Direct link to 2. Setup Prisma ORM by running the development server locally")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
After configuring your Nuxt project with the Prisma module, the next step is to set up Prisma ORM. This process begins by starting the development server, which automatically configures Prisma with a [SQLite database](https://www.prisma.io/docs/orm/overview/databases/sqlite)
.
Run the following command to start the development server:
npm run dev
After running this command, you will be prompted to run a database migration with [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate/understanding-prisma-migrate/overview)
:
? Do you want to migrate database changes to your database? › (Y/n)
Confirm that you want to migrate your database and create your initial tables by hitting Y on your keyboard.
Once the setup flow has terminated, it:
1. Installed the [Prisma CLI](https://www.prisma.io/docs/orm/reference/prisma-cli-reference)
.
2. Initialized a Prisma project with a SQLite database.
3. Created sample `User` and `Post` models in the `schema.prisma` file:
prisma/schema.prisma
// This is your Prisma schema file,// learn more about it in the docs: https://pris.ly/d/prisma-schemagenerator client { provider = "prisma-client-js"}datasource db { provider = "sqlite" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int}
4. Created the database tables for the `User` and `Post` models from the previous steps.
note
The database migrates automatically the first time you start the module if there isn't a `migrations` folder. After that, you need to run `npx prisma migrate dev` manually in the CLI to apply any schema changes. Running the `npx prisma migrate dev` command manually makes it easier and safer to manage migrations and also to [troubleshoot](https://www.prisma.io/docs/orm/prisma-migrate/workflows/troubleshooting)
any migration-related errors.
5. Installed and generated [Prisma Client](https://da-2255.docs-51g.pages.dev/orm/reference/prisma-client-reference)
which enables you to query your DB.
6. Installed [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
.
When the Prisma setup is complete, the development server should start on `https://localhost:3000`.
Next, stop the server, as we need to make some code changes.
4\. Update the application code[](https://www.prisma.io/docs/guides/nuxt#4-update-the-application-code "Direct link to 4. Update the application code")
---------------------------------------------------------------------------------------------------------------------------------------------------------
With Prisma configured, the next step is to update your application code to fetch and display data from your database.
1. In the root directory of your project, create a folder named `components`.
2. Inside the `components` folder, create a file named `User.server.vue`. This server component will fetch and display the name of the first user from the database:
components/User.server.vue
{{ user?.name ?? "No user has been added yet." }}
note
We're extending the `usePrismaClient()` composable with the `withAccelerate()` extension method to ensure [compatibility with Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/overview#using-the-client-extension-for-prisma-accelerate-required)
. This extension will also allow you to [cache your queries](https://www.prisma.io/docs/postgres/database/caching)
.
3. Modify the `app.vue` file in the root directory to include the new server component using Nuxt Islands:
app.vue
4. Run the following command to start the development server again:
npm run dev
5. Verify the application code is working by opening your application in a browser at `https://localhost:3000`.
As there are no users in the database yet, the application will display:
No user has been added yet.
This message will dynamically update when users are added to your database.
By completing these steps, your application is now capable of fetching data from your Prisma database and rendering it on the frontend.
5\. Create a Prisma Postgres instance[](https://www.prisma.io/docs/guides/nuxt#5-create-a-prisma-postgres-instance "Direct link to 5. Create a Prisma Postgres instance")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To store your app's data, you'll create a Prisma Postgres database instance using the Prisma Data Platform.
Follow these steps to create your Prisma Postgres database:
1. Log in to and open the Console.
2. In a [workspace](https://www.prisma.io/docs/platform/about#workspace)
of your choice, click the **New project** button.
3. Type a name for your project in the **Name** field, e.g. **hello-ppg**.
4. In the **Prisma Postgres** section, click the **Get started** button.
5. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**.
6. Click the **Create project** button.
At this point, you'll be redirected to the **Database** page where you will need to wait for a few seconds while the status of your database changes from **`PROVISIONING`** to **`CONNECTED`**.
Once the green **`CONNECTED`** label appears, your database is ready to use!
Then, find your database credentials in the **Set up database access** section, copy the `DATABASE_URL` environment variable\`.
DATABASE_URL=
The `DATABASE_URL` environment variable will be required in the next steps.
6\. Set up Prisma Postgres in your Nuxt app[](https://www.prisma.io/docs/guides/nuxt#6-set-up-prisma-postgres-in-your-nuxt-app "Direct link to 6. Set up Prisma Postgres in your Nuxt app")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Now that the Prisma Postgres instance is ready, update your Nuxt application to use this database:
1. Update the `.env` file by replacing the existing `DATABASE_URL` value with the one you previously copied. It will look similar to this:
.env
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=PRISMA_POSTGRES_API_KEY"
2. Modify the `schema.prisma` file by changing the database provider in the `datasource` block of the `schema.prisma` file located in the `prisma` folder:
prisma/schema.prisma
datasource db { provider = "postgresql" url = env("DATABASE_URL")}
3. Delete the SQLite database files (`dev.db` and `dev.db-journal`) along with the `migrations` folder, all located in the `prisma` directory. This cleans up the existing SQLite setup and prepares your project to migrate to PostgreSQL.
4. Manually create a new migration for the Postgres database by running the `prisma migrate` command:
npx prisma migrate dev --name init
5. Start the development server again:
npm run dev
6. Open the Nuxt DevTools (by hitting Shift+Option\+ D) and click the Prisma logo in the left sidenav to open Prisma Studio. Then add a new `User` record by specifying values for the `name` and `email` fields.
7. Verify the data in the application by refreshing your application at `https://localhost:3000`. The page should display the name of the user you added in Prisma Studio. For example, if you added a user named `Jon`, the application will display `Jon` in the browser.
Congratulations, your Nuxt app is now fully integrated with Prisma Postgres!
7\. Deploy to Vercel[](https://www.prisma.io/docs/guides/nuxt#7-deploy-to-vercel "Direct link to 7. Deploy to Vercel")
------------------------------------------------------------------------------------------------------------------------
Deploy your Nuxt application with Prisma Postgres integration to Vercel by following these steps:
1. Ensure your project is version-controlled and pushed to a GitHub repository. If you don't have a repository yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)
. Once the repository is ready, run the following commands:
git add .git commit -m "Initial commit with Prisma Postgres integration"git branch -M maingit remote add origin https://github.com//.gitgit push -u origin main
note
Replace `` and `` with your GitHub username and the name of your repository.
2. Log in to [Vercel](https://vercel.com/)
and navigate to your [Dashboard](https://vercel.com/docs/dashboard-features)
.
3. Create a new project. Follow Vercel's [Import an existing project](https://vercel.com/docs/getting-started-with-vercel/import)
guide, but stop at [step 3](https://vercel.com/docs/getting-started-with-vercel/import#optionally-configure-any-settings)
where you will configure environment variables _before_ clicking **Deploy**.
4. Configure the `DATABASE_URL` environment variable:
1. Expand the **Environment variables** section.
2. Add the `DATABASE_URL` environment variable:
* **Key**: `DATABASE_URL`
* **Value**: Paste your Prisma Postgres connection URL, e.g. by copying it from the `.env` file in your Nuxt project.
warning
Do not deploy without setting the `DATABASE_URL` variable. Your deployment will fail if the application cannot connect to the database.
5. Click the **Deploy** button. Vercel will build your project and deploy it to a live URL.
6. Open the live URL provided by Vercel and verify that your application is working:
* If you've added a user in Prisma Studio, their name should appear on the live site.
* If no users exist, the application will display:
No user has been added yet.
7. To add or manage data:
1. Open Prisma Studio via [the Prisma Data Platform](https://prisma.io/blog/studio-for-prisma-postgres-view-and-edit-your-data-online)
or local instance.
2. Add or update user data in the database.
3. Refresh your live site to confirm the changes.
Congratulations! Your Nuxt application with Prisma Postgres integration is now live and fully operational on Vercel.
Considerations[](https://www.prisma.io/docs/guides/nuxt#considerations "Direct link to Considerations")
---------------------------------------------------------------------------------------------------------
This guide helps you get started with Prisma Postgres using the Nuxt module. Because the Nuxt module is actively evolving, it does not cover all of Prisma's features or support every edge case. For more advanced functionality or edge deployments, consider using Prisma directly.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/nuxt%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/nuxt%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/nuxt%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/100-nuxt.mdx)
* [Prerequisites](https://www.prisma.io/docs/guides/nuxt#prerequisites)
* [1\. Create a New Nuxt Project and set up the Prisma Nuxt module](https://www.prisma.io/docs/guides/nuxt#1-create-a-new-nuxt-project-and-set-up-the-prisma-nuxt-module)
* [2\. Setup Prisma ORM by running the development server locally](https://www.prisma.io/docs/guides/nuxt#2-setup-prisma-orm-by-running-the-development-server-locally)
* [4\. Update the application code](https://www.prisma.io/docs/guides/nuxt#4-update-the-application-code)
* [5\. Create a Prisma Postgres instance](https://www.prisma.io/docs/guides/nuxt#5-create-a-prisma-postgres-instance)
* [6\. Set up Prisma Postgres in your Nuxt app](https://www.prisma.io/docs/guides/nuxt#6-set-up-prisma-postgres-in-your-nuxt-app)
* [7\. Deploy to Vercel](https://www.prisma.io/docs/guides/nuxt#7-deploy-to-vercel)
* [Considerations](https://www.prisma.io/docs/guides/nuxt#considerations)
---
# How to use Prisma ORM and Prisma Postgres with CPermit.io | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/permit-io-access-control#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/permit-io-access-control#introduction "Direct link to Introduction")
-----------------------------------------------------------------------------------------------------------------------
[Permit.io](https://www.permit.io/)
is an authorization-as-a-service platform that lets you implement fine-grained access control rules based on real-world relationships.
This guide explains how to connect Permit.io to a new Express + Prisma app, define a [Relationship-Based Access Control (ReBAC)](https://www.permit.io/blog/what-is-rebac)
policy, and automatically filter Prisma queries so users only see the data they're allowed to access.
You'll build a small project-task API to demonstrate access inheritance in action - no manual `WHERE` clauses required.
You can find a complete example of this guide [here](https://www.permit.io/blog/prisma-orm-data-filtering-with-rebac)
.
Prerequisites[](https://www.prisma.io/docs/guides/permit-io-access-control#prerequisites "Direct link to Prerequisites")
--------------------------------------------------------------------------------------------------------------------------
* [Node.js v16+](https://nodejs.org/)
* [PostgreSQL](https://www.postgresql.org/)
(local or hosted)
* [Prisma CLI](https://www.prisma.io/docs/orm/tools/prisma-cli)
(`npx prisma`)
* [TypeScript](https://www.typescriptlang.org/)
* [Permit CLI](https://github.com/permitio/permit-cli)
(`npm install -g @permitio/cli`)
1\. Set up your project[](https://www.prisma.io/docs/guides/permit-io-access-control#1-set-up-your-project "Direct link to 1. Set up your project")
-----------------------------------------------------------------------------------------------------------------------------------------------------
First of all, you'll create a new Express + Prisma project from scratch using TypeScript. You'll also install the tools needed to support ReBAC filtering with Permit.io.
### 1.1 Create the project folder[](https://www.prisma.io/docs/guides/permit-io-access-control#11-create-the-project-folder "Direct link to 1.1 Create the project folder")
mkdir prisma-rebac-filteringcd prisma-rebac-filteringnpm init -y
### 1.2 Install the required dependencies[](https://www.prisma.io/docs/guides/permit-io-access-control#12-install-the-required-dependencies "Direct link to 1.2 Install the required dependencies")
Install application and development dependencies:
npm install express cors dotenv @prisma/clientnpm install -D prisma typescript tsx
Then, initialize your Prisma setup:
npx prisma init
This creates a `prisma/` directory with a default `schema.prisma` file and a `.env` file at the root.
### 1.3 Set up your TypeScript config[](https://www.prisma.io/docs/guides/permit-io-access-control#13-set-up-your-typescript-config "Direct link to 1.3 Set up your TypeScript config")
Create a `tsconfig.json` file:
{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "moduleResolution": "node", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "dist" }, "include": ["src", "scripts"]}
### 1.4 Create your folder structure[](https://www.prisma.io/docs/guides/permit-io-access-control#14-create-your-folder-structure "Direct link to 1.4 Create your folder structure")
Set up your project folders:
mkdir -p src/controllers src/middleware src/config scripts
You're now ready to define your Prisma data model.
2\. The authorization model[](https://www.prisma.io/docs/guides/permit-io-access-control#2-the-authorization-model "Direct link to 2. The authorization model")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Before we continue with the setup, it's important to define how access control will work in your application.
This guide uses **Relationship-Based Access Control (ReBAC)** to automatically restrict database queries based on a user's relationship to the data.
Let's see what this looks like:

### Scenario overview[](https://www.prisma.io/docs/guides/permit-io-access-control#scenario-overview "Direct link to Scenario overview")
You're building a **project management API** that supports team-level access controls. Each project belongs to a team (like Marketing or Engineering), and users should only be able to access the projects—and their associated tasks—that they're assigned to.
This is a perfect use case for ReBAC, because:
* Access depends on relationships between users and data (e.g., team membership)
* You want task access to inherit from project access
* You want to avoid manually checking permissions in every controller
### Resources[](https://www.prisma.io/docs/guides/permit-io-access-control#resources "Direct link to Resources")
These are the main data entities you'll protect:
* `Project`: Represents a team-specific workspace that may contain business-critical data (timelines, budgets, client deliverables).
* `Task`: Represents an item of work that belongs to a project
### Relationships[](https://www.prisma.io/docs/guides/permit-io-access-control#relationships "Direct link to Relationships")
* Projects contain tasks (`Project → Task`)
* Users are members of projects (`User → Project`)
### Instance-level roles[](https://www.prisma.io/docs/guides/permit-io-access-control#instance-level-roles "Direct link to Instance-level roles")
Instance-level roles describe what users can do with specific resources:
| Role | Description |
| --- | --- |
| `project#Member` | User can access a specific project |
| `task#Member` | User can access tasks in that project |
### Role derivation[](https://www.prisma.io/docs/guides/permit-io-access-control#role-derivation "Direct link to Role derivation")
ReBAC lets you **automatically derive roles** based on relationships. In this case:
* If a user is a `project#Member`, they automatically become a `task#Member` for all tasks within that project.
* New tasks inherit project access—no need to update permissions manually.
### Access policies[](https://www.prisma.io/docs/guides/permit-io-access-control#access-policies "Direct link to Access policies")
Once relationships and roles are defined, access policies determine what users can do:
| Role | Action | Resource |
| --- | --- | --- |
| `project#Member` | `read` | Project |
| `task#Member` | `read` | Task |
This model ensures that:
* Users can only access the projects and tasks they're assigned to
* No cross-team visibility
* Access automatically stays in sync with the business structure

3\. Define your data model[](https://www.prisma.io/docs/guides/permit-io-access-control#3-define-your-data-model "Direct link to 3. Define your data model")
--------------------------------------------------------------------------------------------------------------------------------------------------------------
To support permission-aware data filtering, you need to structure your database so that relationships are clearly defined. In this case, every `Task` belongs to a `Project`, and users gain access to tasks by being members of the parent project.
### 3.1 Update your Prisma schema[](https://www.prisma.io/docs/guides/permit-io-access-control#31-update-your-prisma-schema "Direct link to 3.1 Update your Prisma schema")
Open `prisma/schema.prisma` and replace the contents with the following:
prisma/schema.prisma
generator client { provider = "prisma-client-js"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model Project { id String @id @default(uuid()) name String tasks Task[] // One-to-many relationship for permission inheritance createdAt DateTime @default(now()) updatedAt DateTime @updatedAt}model Task { id String @id @default(uuid()) name String description String? projectId String project Project @relation(fields: [projectId], references: [id]) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt}
### 3.2 Run your first migration[](https://www.prisma.io/docs/guides/permit-io-access-control#32-run-your-first-migration "Direct link to 3.2 Run your first migration")
To create the database schema:
npx prisma migrate dev --name init
This will:
* Apply your schema to the connected PostgreSQL database
* Generate your Prisma Client
* Create tables for `Project` and `Task` with a one-to-many relationship
### 3.3 Confirm the structure[](https://www.prisma.io/docs/guides/permit-io-access-control#33-confirm-the-structure "Direct link to 3.3 Confirm the structure")
You can open Prisma Studio to inspect your database:
npx prisma studio
This structure allows the `@permitio/permit-prisma` extension to filter records by user relationships at query time. Next, you'll seed test data to simulate distinct team ownership over projects and tasks.
4\. Seed test data with project boundaries[](https://www.prisma.io/docs/guides/permit-io-access-control#4-seed-test-data-with-project-boundaries "Direct link to 4. Seed test data with project boundaries")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To test your data filtering logic, you'll create two projects, each with its own set of tasks. This separation simulates team ownership and will allow you to validate that users only see the data of their assigned project.
### 4.1 Create the seed script[](https://www.prisma.io/docs/guides/permit-io-access-control#41-create-the-seed-script "Direct link to 4.1 Create the seed script")
Create a new file at `scripts/seed.ts` and add the following:
import { PrismaClient } from '@prisma/client';const prisma = new PrismaClient();async function main() { console.log('🌱 Seeding test data...'); // Clear existing records await prisma.task.deleteMany(); await prisma.project.deleteMany(); // Create Project Alpha for the Marketing team const projectAlpha = await prisma.project.create({ data: { id: 'project_alpha', name: 'Marketing Campaign Q2', }, }); // Create Project Beta for the Engineering team const projectBeta = await prisma.project.create({ data: { id: 'project_beta', name: 'API Development Sprint', }, }); // Add tasks to Project Alpha await prisma.task.createMany({ data: [ { id: 'task-alpha-1', name: 'Strategy Planning', description: 'Define campaign goals and KPIs', projectId: projectAlpha.id, }, { id: 'task-alpha-2', name: 'Budget Review', description: 'Review marketing budget with finance', projectId: projectAlpha.id, }, ], }); // Add tasks to Project Beta await prisma.task.createMany({ data: [ { id: 'task-beta-1', name: 'Implement Auth API', description: 'Create endpoints for user login/signup', projectId: projectBeta.id, }, { id: 'task-beta-2', name: 'Schema Migration', description: 'Update tables for new user roles', projectId: projectBeta.id, }, ], }); console.log('✅ Seeded 2 projects and 4 tasks with distinct ownership');}main() .catch((e) => { console.error('❌ Error seeding data:', e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); });
### 4.2 Run the seed script[](https://www.prisma.io/docs/guides/permit-io-access-control#42-run-the-seed-script "Direct link to 4.2 Run the seed script")
npx tsx scripts/seed.ts
If successful, you'll see:
✅ Seeded 2 projects and 4 tasks with distinct ownership
At this point, if you run a query like `prisma.task.findMany()`, it will return all tasks. In the next steps, you'll connect Permit.io to filter these results automatically based on the user's access rights.## 5. Install and configure ReBAC filteringIn this section, you'll install the `@permitio/permit-prisma` extension and configure it to automatically filter Prisma queries based on your access control policies.### 5.1 Install the Permit extensionInstall the `permit-prisma` package:```terminalnpm install @permitio/permit-prisma
### 5.2 Configure the Permit client[](https://www.prisma.io/docs/guides/permit-io-access-control#52-configure-the-permit-client "Direct link to 5.2 Configure the Permit client")
Create a new file at `src/config/permit-config.ts`:
import dotenv from 'dotenv';dotenv.config();export const clientExtensionConfig = { permitConfig: { token: process.env.PERMIT_API_KEY!, // Your Permit.io API key pdp: process.env.PERMIT_PDP_URL || 'http://localhost:7766', // Local or cloud PDP debug: true, }, enableAutomaticChecks: true, enableDataFiltering: true, // Enables automatic query filtering enableResourceSync: true // (Optional) Keeps Permit in sync with resource changes};
API Key
You can find your API key and PDP URL in your [Permit.io dashboard](https://app.permit.io/)
.
### 5.3 What this configuration does[](https://www.prisma.io/docs/guides/permit-io-access-control#53-what-this-configuration-does "Direct link to 5.3 What this configuration does")
When you later extend the Prisma Client with this config:
* All Prisma queries will automatically check access rules
* `findMany()` and similar methods will **only return data the user is allowed to access**
* You no longer need to manually add `WHERE` clauses to enforce permissions
You're now ready to define your ReBAC policy using the Permit CLI.
6\. Define your access control policy in Permit.io[](https://www.prisma.io/docs/guides/permit-io-access-control#6-define-your-access-control-policy-in-permitio "Direct link to 6. Define your access control policy in Permit.io")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Next, you'll use the **Permit CLI** to apply a ready-made ReBAC template that matches your project-task structure.
### 6.1 Install the Permit CLI[](https://www.prisma.io/docs/guides/permit-io-access-control#61-install-the-permit-cli "Direct link to 6.1 Install the Permit CLI")
npm install -g @permitio/cli
### 6.2 Log in to your Permit account[](https://www.prisma.io/docs/guides/permit-io-access-control#62-log-in-to-your-permit-account "Direct link to 6.2 Log in to your Permit account")
Use the CLI to authenticate:
permit login
This opens a browser window where you can log in to your Permit.io account and link your CLI session to an environment.
### 6.3 Apply the ReBAC policy template[](https://www.prisma.io/docs/guides/permit-io-access-control#63-apply-the-rebac-policy-template "Direct link to 6.3 Apply the ReBAC policy template")
Permit provides a prebuilt policy structure for hierarchical data filtering.
Apply it using:
permit env template apply --template orm-data-filtering
This will create:
* **Resources**: `project`, `task`
* **Relationships**: `project` is the parent of `task`
* **Roles**:
* `project#Member`: User can access a specific project
* `task#Member`: Derived from project membership
* **Access policies**: Users with the appropriate roles can `read` each resource
### 6.4 View the policy in the Permit UI[](https://www.prisma.io/docs/guides/permit-io-access-control#64-view-the-policy-in-the-permit-ui "Direct link to 6.4 View the policy in the Permit UI")
Go to the [Permit.io dashboard](https://app.permit.io/)
and navigate to your environment to explore:
* Your resource graph
* Role derivations
* Relationship mappings
* Policy rules for `read` access
info
These rules are used by the @permitio/permit-prisma extension to determine which records to return for each user—automatically.
With your policy in place, you're now ready to wire up user context and filtering logic in your Express middleware.
7\. Add middleware to set user context[](https://www.prisma.io/docs/guides/permit-io-access-control#7-add-middleware-to-set-user-context "Direct link to 7. Add middleware to set user context")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To filter Prisma queries per user, you need to:
1. Identify the current user (simulated via an email header)
2. Attach the filtered Prisma Client instance to the request
3. Set the user in the Permit context (`prisma.$permit.setUser()`)
### 7.1 Create the middleware file[](https://www.prisma.io/docs/guides/permit-io-access-control#71-create-the-middleware-file "Direct link to 7.1 Create the middleware file")
Create a new file: `src/middleware/auth.middleware.ts`
import { Request, Response, NextFunction } from 'express';import { PrismaClient } from '@prisma/client';import createPermitClientExtension from '@permitio/permit-prisma';import { clientExtensionConfig } from '../config/permit-config';// Extend PrismaClient with Permitconst prisma = new PrismaClient().$extends( createPermitClientExtension(clientExtensionConfig));// Extend Request type with Prisma and user contextexport interface AuthRequest extends Request { user?: { email: string }; prisma?: typeof prisma;}export const authenticate = ( req: AuthRequest, res: Response, next: NextFunction): void => { const userEmail = req.headers['x-user-email'] as string; if (!userEmail) { res.status(401).json({ error: 'Missing user email' }); return; } // Register the user in Permit context prisma.$permit.setUser(userEmail); // Add user + Prisma client to request req.user = { email: userEmail }; req.prisma = prisma; next();};
Going to prod.
In a production app, you'd replace the x-user-email header with proper authentication logic (e.g. JWT or session validation).
### 7.2 What this middleware does[](https://www.prisma.io/docs/guides/permit-io-access-control#72-what-this-middleware-does "Direct link to 7.2 What this middleware does")
* Reads the user's email from the request header
* Sets the user identity in the Permit context (used for query filtering)
* Adds the filtered Prisma client to the request object (`req.prisma`)
* Makes the user and database client available to all downstream route handlers
You're now ready to build your API endpoints without writing a single line of access control logic.
8\. Build your API endpoints[](https://www.prisma.io/docs/guides/permit-io-access-control#8-build-your-api-endpoints "Direct link to 8. Build your API endpoints")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
You'll now create two endpoints:
* `GET /api/projects`: returns all projects the user has access to
* `GET /api/tasks`: returns all tasks the user has access to (inherited from project membership)
Thanks to the Permit-Prisma integration, **you won't need to add any manual filtering logic**—it's handled automatically.
### 8.1 Get user-visible projects[](https://www.prisma.io/docs/guides/permit-io-access-control#81-get-user-visible-projects "Direct link to 8.1 Get user-visible projects")
Create a controller file: `src/controllers/project.controller.ts`
import { Response } from 'express';import { AuthRequest } from '../middleware/auth.middleware';export const getProjects = async (req: AuthRequest, res: Response) => { try { const prisma = req.prisma!; const projects = await prisma.project.findMany(); // Auto-filtered res.json({ user: req.user?.email, count: projects.length, projects, }); } catch (error: any) { console.error('Error fetching projects:', error); res.status(500).json({ error: error.message }); }};
> Even though this is a raw findMany() query, only authorized records will be returned for the current user.
### 8.2 Get user-visible tasks[](https://www.prisma.io/docs/guides/permit-io-access-control#82-get-user-visible-tasks "Direct link to 8.2 Get user-visible tasks")
Create another controller: `src/controllers/task.controller.ts`
import { Response } from 'express';import { AuthRequest } from '../middleware/auth.middleware';export const getTasks = async (req: AuthRequest, res: Response) => { try { const prisma = req.prisma!; const projectId = req.query.projectId as string; const where = projectId ? { projectId } : undefined; const tasks = await prisma.task.findMany({ where }); // Still filtered res.json({ user: req.user?.email, count: tasks.length, tasks, }); } catch (error: any) { console.error('Error fetching tasks:', error); res.status(500).json({ error: error.message }); }};
projectId
Even if you provide a projectId manually, the query results are still filtered by permissions.
### 8.3 What this demonstrates[](https://www.prisma.io/docs/guides/permit-io-access-control#83-what-this-demonstrates "Direct link to 8.3 What this demonstrates")
* You can write **normal Prisma queries**
* Users will only get records they're allowed to see
* You don't need custom role-checking logic in every handler
* Task access is **automatically derived** from project membership
You're now ready to wire it all together and launch the app.
### 9.1 Create your Express app[](https://www.prisma.io/docs/guides/permit-io-access-control#91-create-your-express-app "Direct link to 9.1 Create your Express app")
Create `src/app.ts`:
import express from 'express';import cors from 'cors';import { authenticate } from './middleware/auth.middleware';import { getProjects } from './controllers/project.controller';import { getTasks } from './controllers/task.controller';const app = express();const PORT = process.env.PORT || 3000;app.use(cors());app.use(express.json());// Auth middleware applies ReBAC filtering per requestapp.get('/api/projects', authenticate, getProjects);app.get('/api/tasks', authenticate, getTasks);app.listen(PORT, () => { console.log(`🚀 Server running at http://localhost:${PORT}`); console.log(`🔐 ReBAC filtering is now active`);});
### 9.2 Run the server[](https://www.prisma.io/docs/guides/permit-io-access-control#92-run-the-server "Direct link to 9.2 Run the server")
Start the development server with:
npx tsx src/app.ts
If everything is set up correctly, the console will display:
🚀 Server running at http://localhost:3000🔐 ReBAC filtering is now active
* * *
### 9.3 Test your API[](https://www.prisma.io/docs/guides/permit-io-access-control#93-test-your-api "Direct link to 9.3 Test your API")
You can simulate requests as different users by setting the `x-user-email` header. This mimics logged-in users with access to specific projects.
### Example: John (Marketing team member)[](https://www.prisma.io/docs/guides/permit-io-access-control#example-john-marketing-team-member "Direct link to Example: John (Marketing team member)")
curl -H "x-user-email: john@company.com" http://localhost:3000/api/projects
This should only return Project Alpha (and its tasks).
### Example: Mary (Engineering team member)[](https://www.prisma.io/docs/guides/permit-io-access-control#example-mary-engineering-team-member "Direct link to Example: Mary (Engineering team member)")
curl -H "x-user-email: mary@company.com" http://localhost:3000/api/tasks
This should only return tasks from Project Beta.
tip
If you haven't yet assigned users to project memberships in the Permit.io UI, visit the Policy Editor and assign users to roles (project#Member).
Once you've confirmed these results, your Prisma API is now enforcing secure, relationship-based access control, all **without adding manual filtering logic anywhere in your code.**
You've now built a secure API that:
* Filters query results based on user relationships
* Uses ReBAC to avoid role explosion and brittle permission logic
* Keeps Prisma queries clean, safe, and scalable
10\. Next steps[](https://www.prisma.io/docs/guides/permit-io-access-control#10-next-steps "Direct link to 10. Next steps")
-----------------------------------------------------------------------------------------------------------------------------
Now that you've successfully implemented data filtering with Prisma and ReBAC, you can extend this foundation to support more complex authorization use cases and developer tooling.
### Extend your model[](https://www.prisma.io/docs/guides/permit-io-access-control#extend-your-model "Direct link to Extend your model")
* Add a `User` model and create a many-to-many `Membership` relationship between users and projects.
* Introduce instance-level roles like `Editor` or `Owner` with different permissions.
* Support additional actions like `create`, `update`, and `delete`, using Permit.io's role policies.
### Add authentication[](https://www.prisma.io/docs/guides/permit-io-access-control#add-authentication "Direct link to Add authentication")
Integrate your API with an auth provider (e.g., [Clerk](https://www.prisma.io/docs/guides/clerk-nextjs)
, Auth0) and replace the `x-user-email` header with a secure identity mechanism (like a JWT token).
### Use Permit Elements[](https://www.prisma.io/docs/guides/permit-io-access-control#use-permit-elements "Direct link to Use Permit Elements")
Permit.io provides UI components for:
* Managing user access visually
* Reviewing access logs
* Approving access requests (MCP)
Explore [Permit Elements](https://docs.permit.io/embeddable-uis/overview/)
to make access management easier for your end users or admins.
### More resources[](https://www.prisma.io/docs/guides/permit-io-access-control#more-resources "Direct link to More resources")
* [Permit.io ReBAC Policy Setup Guide](https://docs.permit.io/overview/create-a-rebac-policy)
* [Read the full guide: Data Filtering with Prisma and ReBAC](https://docs.permit.io/how-to/enforce-permissions/data-filtering)
* [ReBAC vs RBAC - Learn when to use which](https://www.permit.io/blog/rbac-vs-rebac)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/permit-io-access-control%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/permit-io-access-control%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/permit-io-access-control%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/320-permit-io-access-control.mdx)
* [Introduction](https://www.prisma.io/docs/guides/permit-io-access-control#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/permit-io-access-control#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/permit-io-access-control#1-set-up-your-project)
* [1.1 Create the project folder](https://www.prisma.io/docs/guides/permit-io-access-control#11-create-the-project-folder)
* [1.2 Install the required dependencies](https://www.prisma.io/docs/guides/permit-io-access-control#12-install-the-required-dependencies)
* [1.3 Set up your TypeScript config](https://www.prisma.io/docs/guides/permit-io-access-control#13-set-up-your-typescript-config)
* [1.4 Create your folder structure](https://www.prisma.io/docs/guides/permit-io-access-control#14-create-your-folder-structure)
* [2\. The authorization model](https://www.prisma.io/docs/guides/permit-io-access-control#2-the-authorization-model)
* [Scenario overview](https://www.prisma.io/docs/guides/permit-io-access-control#scenario-overview)
* [Resources](https://www.prisma.io/docs/guides/permit-io-access-control#resources)
* [Relationships](https://www.prisma.io/docs/guides/permit-io-access-control#relationships)
* [Instance-level roles](https://www.prisma.io/docs/guides/permit-io-access-control#instance-level-roles)
* [Role derivation](https://www.prisma.io/docs/guides/permit-io-access-control#role-derivation)
* [Access policies](https://www.prisma.io/docs/guides/permit-io-access-control#access-policies)
* [3\. Define your data model](https://www.prisma.io/docs/guides/permit-io-access-control#3-define-your-data-model)
* [3.1 Update your Prisma schema](https://www.prisma.io/docs/guides/permit-io-access-control#31-update-your-prisma-schema)
* [3.2 Run your first migration](https://www.prisma.io/docs/guides/permit-io-access-control#32-run-your-first-migration)
* [3.3 Confirm the structure](https://www.prisma.io/docs/guides/permit-io-access-control#33-confirm-the-structure)
* [4\. Seed test data with project boundaries](https://www.prisma.io/docs/guides/permit-io-access-control#4-seed-test-data-with-project-boundaries)
* [4.1 Create the seed script](https://www.prisma.io/docs/guides/permit-io-access-control#41-create-the-seed-script)
* [4.2 Run the seed script](https://www.prisma.io/docs/guides/permit-io-access-control#42-run-the-seed-script)
* [5.2 Configure the Permit client](https://www.prisma.io/docs/guides/permit-io-access-control#52-configure-the-permit-client)
* [5.3 What this configuration does](https://www.prisma.io/docs/guides/permit-io-access-control#53-what-this-configuration-does)
* [6\. Define your access control policy in Permit.io](https://www.prisma.io/docs/guides/permit-io-access-control#6-define-your-access-control-policy-in-permitio)
* [6.1 Install the Permit CLI](https://www.prisma.io/docs/guides/permit-io-access-control#61-install-the-permit-cli)
* [6.2 Log in to your Permit account](https://www.prisma.io/docs/guides/permit-io-access-control#62-log-in-to-your-permit-account)
* [6.3 Apply the ReBAC policy template](https://www.prisma.io/docs/guides/permit-io-access-control#63-apply-the-rebac-policy-template)
* [6.4 View the policy in the Permit UI](https://www.prisma.io/docs/guides/permit-io-access-control#64-view-the-policy-in-the-permit-ui)
* [7\. Add middleware to set user context](https://www.prisma.io/docs/guides/permit-io-access-control#7-add-middleware-to-set-user-context)
* [7.1 Create the middleware file](https://www.prisma.io/docs/guides/permit-io-access-control#71-create-the-middleware-file)
* [7.2 What this middleware does](https://www.prisma.io/docs/guides/permit-io-access-control#72-what-this-middleware-does)
* [8\. Build your API endpoints](https://www.prisma.io/docs/guides/permit-io-access-control#8-build-your-api-endpoints)
* [8.1 Get user-visible projects](https://www.prisma.io/docs/guides/permit-io-access-control#81-get-user-visible-projects)
* [8.2 Get user-visible tasks](https://www.prisma.io/docs/guides/permit-io-access-control#82-get-user-visible-tasks)
* [8.3 What this demonstrates](https://www.prisma.io/docs/guides/permit-io-access-control#83-what-this-demonstrates)
* [9.1 Create your Express app](https://www.prisma.io/docs/guides/permit-io-access-control#91-create-your-express-app)
* [9.2 Run the server](https://www.prisma.io/docs/guides/permit-io-access-control#92-run-the-server)
* [9.3 Test your API](https://www.prisma.io/docs/guides/permit-io-access-control#93-test-your-api)
* [Example: John (Marketing team member)](https://www.prisma.io/docs/guides/permit-io-access-control#example-john-marketing-team-member)
* [Example: Mary (Engineering team member)](https://www.prisma.io/docs/guides/permit-io-access-control#example-mary-engineering-team-member)
* [10\. Next steps](https://www.prisma.io/docs/guides/permit-io-access-control#10-next-steps)
* [Extend your model](https://www.prisma.io/docs/guides/permit-io-access-control#extend-your-model)
* [Add authentication](https://www.prisma.io/docs/guides/permit-io-access-control#add-authentication)
* [Use Permit Elements](https://www.prisma.io/docs/guides/permit-io-access-control#use-permit-elements)
* [More resources](https://www.prisma.io/docs/guides/permit-io-access-control#more-resources)
---
# How to use Prisma ORM and Prisma Postgres with React Router 7 | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/react-router-7#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/react-router-7#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------
This guide shows you how to use Prisma ORM with [React Router 7](https://reactrouter.com/)
, a multi-strategy router that can be as minimal as declarative routing or as full-featured as a fullstack framework.
You'll learn how to set up Prisma ORM and Prisma Postgres with React Router 7 and handle migrations. You can find a [deployment-ready example on GitHub](https://github.com/prisma/prisma-examples/blob/latest/orm/react-router-7)
.
Prerequisites[](https://www.prisma.io/docs/guides/react-router-7#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------
* [Node.js 20+](https://nodejs.org/)
1\. Set up your project[](https://www.prisma.io/docs/guides/react-router-7#1-set-up-your-project "Direct link to 1. Set up your project")
-------------------------------------------------------------------------------------------------------------------------------------------
From the directory where you want to create your project, run `create-react-router` to create a new React Router app that you will be using for this guide.
npx create-react-router@latest react-router-7-prisma
You'll be prompted to select the following, select `Yes` for both:
info
* _Initialize a new git repository?_ `Yes`
* _Install dependencies with npm?_ `Yes`
Now, navigate to the project directory:
cd react-router-7-prisma
2\. Install and Configure Prisma[](https://www.prisma.io/docs/guides/react-router-7#2-install-and-configure-prisma "Direct link to 2. Install and Configure Prisma")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/react-router-7#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, you'll need to install a few dependencies:
* Prisma Postgres (recommended)
* Other databases
npm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client
npm install prisma tsx --save-devnpm install @prisma/client
Once installed, initialize Prisma in your project:
npx prisma init --db --output ../app/generated/prisma
info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My React Router 7 Project"
This will create:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `app/generated/prisma`.
### 2.2. Define your Prisma Schema[](https://www.prisma.io/docs/guides/react-router-7#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma Schema")
In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider:
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../app/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
### 2.3. Configure the Prisma Client generator[](https://www.prisma.io/docs/guides/react-router-7#23-configure-the-prisma-client-generator "Direct link to 2.3. Configure the Prisma Client generator")
Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/react-router-7#24-seed-the-database "Direct link to 2.4. Seed the database")
Add some seed data to populate the database with sample users and posts.
Create a new file called `seed.ts` in the `prisma/` directory:
prisma/seed.ts
import { PrismaClient, Prisma } from "../app/generated/prisma/client.js";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();
Now, tell Prisma how to run this script by updating your `package.json`:
package.json
{ "name": "react-router-7-prisma", "private": true, "type": "module", "scripts": { "build": "react-router build", "dev": "react-router dev", "start": "react-router-serve ./build/server/index.js", "typecheck": "react-router typegen && tsc" }, "prisma": { "seed": "tsx prisma/seed.ts" }, "dependencies": { "@react-router/node": "^7.3.0", "@react-router/serve": "^7.3.0", "isbot": "^5.1.17", "react": "^19.0.0", "react-dom": "^19.0.0", "react-router": "^7.3.0" }, "devDependencies": { "@react-router/dev": "^7.3.0", "@tailwindcss/vite": "^4.0.0", "@types/node": "^20", "@types/react": "^19.0.1", "@types/react-dom": "^19.0.1", "prisma": "^6.5.0", "react-router-devtools": "^1.1.0", "tailwindcss": "^4.0.0", "tsx": "^4.19.3", "typescript": "^5.7.2", "vite": "^5.4.11", "vite-tsconfig-paths": "^5.1.4" }}
Run the seed script:
npx prisma db seed
And open Prisma Studio to inspect your data:
npx prisma studio
3\. Integrate Prisma into React Router 7[](https://www.prisma.io/docs/guides/react-router-7#3-integrate-prisma-into-react-router-7 "Direct link to 3. Integrate Prisma into React Router 7")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Create a Prisma Client[](https://www.prisma.io/docs/guides/react-router-7#31-create-a-prisma-client "Direct link to 3.1. Create a Prisma Client")
Inside of your `app` directory, create a new `lib` directory and add a `prisma.ts` file to it. This file will be used to create and export your Prisma Client instance.
Set up the Prisma client like this:
* Prisma Postgres (recommended)
* Other databases
app/lib/prisma.ts
import { PrismaClient } from "../generated/prisma/client.js";import { withAccelerate } from '@prisma/extension-accelerate'const globalForPrisma = global as unknown as { prisma: PrismaClient}const prisma = globalForPrisma.prisma || new PrismaClient().$extends(withAccelerate())if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prismaexport default prisma
app/lib/prisma.ts
import { PrismaClient } from "../generated/prisma/client.js";const globalForPrisma = global as unknown as { prisma: PrismaClient}const prisma = globalForPrisma.prisma || new PrismaClient()if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prismaexport default prisma
warning
We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)
) to manage database connections efficiently.
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
You'll use this client in the next section to run your first queries.
### 3.2. Query your database with Prisma[](https://www.prisma.io/docs/guides/react-router-7#32-query-your-database-with-prisma "Direct link to 3.2. Query your database with Prisma")
Now that you have an initialized Prisma Client, a connection to your database, and some initial data, you can start querying your data with Prisma ORM.
In this example, you'll be making the "home" page of your application display all of your users.
Open the `app/routes/home.tsx` file and replace the existing code with the following:
app/routes/home.tsx
import type { Route } from "./+types/home";export function meta({}: Route.MetaArgs) { return [ { title: "New React Router App" }, { name: "description", content: "Welcome to React Router!" }, ];}export default function Home({ loaderData }: Route.ComponentProps) { return (
Superblog
Alice
Bob
);}
note
If you see an error on the first line, `import type { Route } from "./+types/home";`, make sure you run `npm run dev` so React Router generates needed types.
This gives you a basic page with a title and a list of users. However, the list of users is static. Update the page to fetch the users from your database and make it dynamic.
app/routes/home.tsx
import type { Route } from "./+types/home";import prisma from '~/lib/prisma'export function meta({}: Route.MetaArgs) { return [ { title: "New React Router App" }, { name: "description", content: "Welcome to React Router!" }, ];}export async function loader() { const users = await prisma.user.findMany(); return { users };}export default function Home({ loaderData }: Route.ComponentProps) { const { users } = loaderData; return (
Superblog
{users.map((user) => (
{user.name}
))}
);}
You are now importing your client, using [a React Router loader](https://reactrouter.com/start/framework/data-loading#server-data-loading)
to query the `User` model for all users, and then displaying them in a list.
Now your home page is dynamic and will display the users from your database.
### 3.4 Update your data (optional)[](https://www.prisma.io/docs/guides/react-router-7#34-update-your-data-optional "Direct link to 3.4 Update your data (optional)")
If you want to see what happens when data is updated, you could:
* update your `User` table via an SQL browser of your choice
* change your `seed.ts` file to add more users
* change the call to `prisma.user.findMany` to re-order the users, filter the users, or similar.
Just reload the page and you'll see the changes.
4\. Add a new Posts list page[](https://www.prisma.io/docs/guides/react-router-7#4-add-a-new-posts-list-page "Direct link to 4. Add a new Posts list page")
-------------------------------------------------------------------------------------------------------------------------------------------------------------
You have your home page working, but you should add a new page that displays all of your posts.
First, create a new `posts` directory under the `app/routes` directory and add a `home.tsx` file:
mkdir -p app/routes/posts && touch app/routes/posts/home.tsx
Second, add the following code to the `app/routes/posts/home.tsx` file:
app/routes/posts/home.tsx
import type { Route } from "./+types/home";import prisma from "~/lib/prisma";export default function Home() { return (
Posts
My first post
);}
Second, update the `app/routes.ts` file so when you visit the `/posts` route, the `posts/home.tsx` page is shown:
app/routes.ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";export default [ index("routes/home.tsx"), route("posts", "routes/posts/home.tsx"),] satisfies RouteConfig;
Now `localhost:5173/posts` will load, but the content is static. Update it to be dynamic, similarly to the home page:
app/routes/posts/home.tsx
import type { Route } from "./+types/home";import prisma from "~/lib/prisma";export async function loader() { const posts = await prisma.post.findMany({ include: { author: true, }, }); return { posts };}export default function Posts({ loaderData }: Route.ComponentProps) { const { posts } = loaderData; return (
Posts
{posts.map((post) => (
{post.title} by {post.author.name}
))}
);}
This works similarly to the home page, but instead of displaying users, it displays posts. You can also see that you've used `include` in your Prisma Client query to fetch the author of each post so you can display the author's name.
This "list view" is one of the most common patterns in web applications. You're going to add two more pages to your application which you'll also commonly need: a "detail view" and a "create view".
5\. Add a new Posts detail page[](https://www.prisma.io/docs/guides/react-router-7#5-add-a-new-posts-detail-page "Direct link to 5. Add a new Posts detail page")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
To complement the Posts list page, you'll add a Posts detail page.
In the `routes/posts` directory, create a new `post.tsx` file.
touch app/routes/posts/post.tsx
This page will display a single post's title, content, and author. Just like your other pages, add the following code to the `app/routes/posts/post.tsx` file:
app/routes/posts/post.tsx
import type { Route } from "./+types/post";import prisma from "~/lib/prisma";export default function Post({ loaderData }: Route.ComponentProps) { return (
My first post
by Anonymous
No content available.
);}
And then add a new route for this page:
app/routes.ts
export default [ index("routes/home.tsx"), route("posts", "routes/posts/home.tsx"), route("posts/:postId", "routes/posts/post.tsx"),] satisfies RouteConfig;
As before, this page is static. Update it to be dynamic based on the `params` passed to the page:
app/routes/posts/post.tsx
import { data } from "react-router";import type { Route } from "./+types/post";import prisma from "~/lib/prisma";export async function loader({ params }: Route.LoaderArgs) { const { postId } = params; const post = await prisma.post.findUnique({ where: { id: parseInt(postId) }, include: { author: true, }, }); if (!post) { throw data("Post Not Found", { status: 404 }); } return { post };}export default function Post({ loaderData }: Route.ComponentProps) { const { post } = loaderData; return (
{post.title}
by {post.author.name}
{post.content || "No content available."}
);}
There's a lot of changes here, so break it down:
* You're using Prisma Client to fetch the post by its `id`, which you get from the `params` object.
* In case the post doesn't exist (maybe it was deleted or maybe you typed a wrong ID), you throw an error to display a 404 page.
* You then display the post's title, content, and author. If the post doesn't have content, you display a placeholder message.
It's not the prettiest page, but it's a good start. Try it out by navigating to `localhost:5173/posts/1` and `localhost:5173/posts/2`. You can also test the 404 page by navigating to `localhost:5173/posts/999`.
6\. Add a new Posts create page[](https://www.prisma.io/docs/guides/react-router-7#6-add-a-new-posts-create-page "Direct link to 6. Add a new Posts create page")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
To round out your application, you'll add a "create" page for posts. This will allow you to write your own posts and save them to the database.
As with the other pages, you'll start with a static page and then update it to be dynamic.
touch app/routes/posts/new.tsx
Now, add the following code to the `app/routes/posts/new.tsx` file:
app/routes/posts/new.tsx
import type { Route } from "./+types/new";import { Form } from "react-router";export async function action({ request }: Route.ActionArgs) { const formData = await request.formData(); const title = formData.get("title") as string; const content = formData.get("content") as string;}export default function NewPost() { return (
Create New Post
);}
You can't open the `posts/new` page in your app yet. To do that, you need to add it to `routes.tsx` again:
app/routes.ts
export default [ index("routes/home.tsx"), route("posts", "routes/posts/home.tsx"), route("posts/:postId", "routes/posts/post.tsx"), route("posts/new", "routes/posts/new.tsx"),] satisfies RouteConfig;
Now you can view the form at the new URL. It looks good, but it doesn't do anything yet. Update the `action` to save the post to the database:
app/routes/posts/new.tsx
import type { Route } from "./+types/new";import { Form, redirect } from "react-router";import prisma from "~/lib/prisma";export async function action({ request }: Route.ActionArgs) { const formData = await request.formData(); const title = formData.get("title") as string; const content = formData.get("content") as string; try { await prisma.post.create({ data: { title, content, authorId: 1, }, }); } catch (error) { console.error(error); return Response.json({ error: "Failed to create post" }, { status: 500 }); } return redirect("/posts");}export default function NewPost() { return (
Create New Post
);}
This page now has a functional form! When you submit the form, it will create a new post in the database and redirect you to the posts list page.
Try it out by navigating to `localhost:5173/posts/new` and submitting the form.
7\. Next steps[](https://www.prisma.io/docs/guides/react-router-7#7-next-steps "Direct link to 7. Next steps")
----------------------------------------------------------------------------------------------------------------
Now that you have a working React Router application with Prisma ORM, here are some ways you can expand and improve your application:
* Add authentication to protect your routes
* Add the ability to edit and delete posts
* Add comments to posts
* Use [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
for visual database management
For more information and updates:
* [Prisma ORM documentation](https://www.prisma.io/docs/orm)
* [Prisma Client API reference](https://www.prisma.io/docs/orm/prisma-client)
* [React Router documentation](https://reactrouter.com/home)
* Join our [Discord community](https://pris.ly/discord)
* Follow us on [Twitter](https://twitter.com/prisma)
and [YouTube](https://youtube.com/prismadata)
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/react-router-7%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/react-router-7%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/react-router-7%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/170-react-router-7.mdx)
* [Introduction](https://www.prisma.io/docs/guides/react-router-7#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/react-router-7#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/react-router-7#1-set-up-your-project)
* [2\. Install and Configure Prisma](https://www.prisma.io/docs/guides/react-router-7#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/react-router-7#21-install-dependencies)
* [2.2. Define your Prisma Schema](https://www.prisma.io/docs/guides/react-router-7#22-define-your-prisma-schema)
* [2.3. Configure the Prisma Client generator](https://www.prisma.io/docs/guides/react-router-7#23-configure-the-prisma-client-generator)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/react-router-7#24-seed-the-database)
* [3\. Integrate Prisma into React Router 7](https://www.prisma.io/docs/guides/react-router-7#3-integrate-prisma-into-react-router-7)
* [3.1. Create a Prisma Client](https://www.prisma.io/docs/guides/react-router-7#31-create-a-prisma-client)
* [3.2. Query your database with Prisma](https://www.prisma.io/docs/guides/react-router-7#32-query-your-database-with-prisma)
* [3.4 Update your data (optional)](https://www.prisma.io/docs/guides/react-router-7#34-update-your-data-optional)
* [4\. Add a new Posts list page](https://www.prisma.io/docs/guides/react-router-7#4-add-a-new-posts-list-page)
* [5\. Add a new Posts detail page](https://www.prisma.io/docs/guides/react-router-7#5-add-a-new-posts-detail-page)
* [6\. Add a new Posts create page](https://www.prisma.io/docs/guides/react-router-7#6-add-a-new-posts-create-page)
* [7\. Next steps](https://www.prisma.io/docs/guides/react-router-7#7-next-steps)
---
# How to use Prisma Postgres with Shopify | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/shopify#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/shopify#introduction "Direct link to Introduction")
------------------------------------------------------------------------------------------------------
[Shopify](https://www.shopify.com/)
is a popular platform for building e-commerce stores. This guide will show you how to connect a Shopify app to a [Prisma Postgres](https://www.prisma.io/postgres)
database in order to create internal notes for products.
Prerequisites[](https://www.prisma.io/docs/guides/shopify#prerequisites "Direct link to Prerequisites")
---------------------------------------------------------------------------------------------------------
* [Node.js](https://nodejs.org/en/download/)
* [Shopify CLI](https://shopify.dev/docs/api/shopify-cli)
* [Shopify Partner Account](https://www.shopify.com/partners)
and a [development store](https://shopify.dev/docs/api/development-stores#create-a-development-store-to-test-your-app)
1\. Set up your project[](https://www.prisma.io/docs/guides/shopify#1-set-up-your-project "Direct link to 1. Set up your project")
------------------------------------------------------------------------------------------------------------------------------------
note
If you do not have the Shopify CLI installed, you can install it with `npm install -g @shopify/cli`.
To start, initialize a new Shopify app using the Shopify CLI:
shopify app init
During setup, you'll be prompted to customize your app. Don't worry—just follow these recommended options to get started quickly and ensure your app is set up for success:
info
* _Get started building your app:_ `Build a Remix app (recommended)`
* _For your Remix template, which language do you want:_ `JavaScript`
* _App Name:_ `prisma-store` _(name cannot contain `shopify`)_
Navigate to the `prisma-store` directory:
cd prisma-store
2\. Set up Prisma[](https://www.prisma.io/docs/guides/shopify#2-set-up-prisma "Direct link to 2. Set up Prisma")
------------------------------------------------------------------------------------------------------------------
Prisma comes pre-installed in your project, but let's take a moment to update it to the latest version. This ensures you have access to the newest features, improvements, and the best possible experience as you build your app.
You will be swapping to a Prisma Postgres database, so delete the `migrations` folder along with the `dev.sqlite` file, inside of the `prisma` directory.
You need to update a few things in the `schema.prisma` file to get it working with Remix and Prisma Postgres.
* Swap to the new `prisma-client` generator.
* Update the provider to `postgresql`.
* Update the url to the new database url.
prisma/schema.prisma
generator client { provider = "prisma-client-js" provider = "prisma-client" output = "../app/generated/prisma"}datasource db { provider = "sqlite" provider = "postgresql" url = "file:../dev.db" url = env("DATABASE_URL")}model Session { // ... existing model}
To enable your app to store notes for each product, let's add a new `ProductNote` model to your Prisma schema.
This model will allow you to save and organize notes linked to individual products in your database through the `productGid` field.
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../app/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model Session { // ... existing model}model ProductNote { id String @id @default(uuid()) productGid String body String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt}
Next, Prisma will need to be updated to the latest version. Run:
npm install prisma --save-dev && npm install @prisma/client
Prisma Postgres allows you to create a new database on the fly, you can create a new database at the same time you initialize your project by adding the `--db` flag:
npx prisma init --db
Once you've completed the prompts, it's time to access your new database:
1. **Open the :**
* Log in and find your newly created database project.
2. **Set up your database credentials:**
* In the sidebar, click **Database**, then select **Setup**.
* Choose **Existing project** and press **Generate database credentials**.
3. **Configure your environment:**
* Create a new `.env` file in the root of your project.
* Copy and paste the `DATABASE_URL` you just generated into this file. It should look similar to this:
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=..."
4. **Apply your database schema:**
* Run the following command to create your tables and get your database ready:
npx prisma migrate dev --name init
Now, before moving on, let's update your `db.server.ts` file to use the newly generated Prisma client.
app/db.server.ts
import { PrismaClient } from "@prisma/client";import { PrismaClient } from "./generated/prisma/client.js";if (process.env.NODE_ENV !== "production") { if (!global.prismaGlobal) { global.prismaGlobal = new PrismaClient(); }}const prisma = global.prismaGlobal ?? new PrismaClient();export default prisma;
warning
It is recommended to add `app/generated/prisma` to your `.gitignore` file.
3\. Create your Remix model[](https://www.prisma.io/docs/guides/shopify#3-create-your-remix-model "Direct link to 3. Create your Remix model")
------------------------------------------------------------------------------------------------------------------------------------------------
To keep your project organized, let's create a new `models/` folder. Inside this folder, add a file named `notes.server.js`. This will be the home for all your note-related logic and make your codebase easier to manage as your app grows.
The `notes.server.js` file will contain two functions:
* `getNotes` - This will get all the notes for a given product.
* `createNote` - This will create a new note for a given product.
Start by importing the Prisma client from `db.server.ts` and creating the `getNotes` function:
models/notes.server.js
import prisma from "../db.server";export const getNotes = async (productGid) => { const notes = await prisma.productNote.findMany({ where: { productGid: productGid.toString() }, orderBy: { createdAt: "desc" }, }); return notes;};
To enable users to add new notes to your database, let's create a function in `notes.server.js` that uses `prisma.productNote.create`:
models/notes.server.js
import prisma from "../db.server";export const getNotes = async (productGid) => { const notes = await prisma.productNote.findMany({ where: { productGid: productGid.toString() }, orderBy: { createdAt: "desc" }, }); return notes;};export const createNote = async (note) => { const newNote = await prisma.productNote.create({ data: { body: note.body, productGid: note.productGid, }, }); return newNote;};
4\. Create your layout route[](https://www.prisma.io/docs/guides/shopify#4-create-your-layout-route "Direct link to 4. Create your layout route")
---------------------------------------------------------------------------------------------------------------------------------------------------
Before those functions are able to be called, our route needs a layout to sit in. This layout route will feature a button for selecting a product, and will act as the parent for your `ProductNotes` route, keeping your app organized and user-friendly.
### 4.1. Create the ProductNotesLayout component[](https://www.prisma.io/docs/guides/shopify#41-create-the-productnoteslayout-component "Direct link to 4.1. Create the ProductNotesLayout component")
Start by creating the the folder `routes/app.product-notes.jsx` and adding the `ProductNotesLayout` component inside of it:
app/routes/app.product-notes.jsx
import { Page, Layout } from "@shopify/polaris";export default function ProductNotesLayout() { return ( );}
Next, create the `selectProduct` function and a `Button` to let the user pick a product:
app/routes/app.product-notes.jsx
import { useNavigate } from "@remix-run/react";import { Page, Layout } from "@shopify/polaris";import { Button, Page, Layout } from "@shopify/polaris";export default function ProductNotesLayout() { const navigate = useNavigate(); async function selectProduct() { const products = await window.shopify.resourcePicker({ type: "product", action: "select", }); const selectedGid = products[0].id; navigate(`/app/product-notes/${encodeURIComponent(selectedGid)}`); } return ( );}
Remix renders provides the ability to render a nested route. Add an `` to the `routes/app.product-notes.jsx` file where the `ProductNotes` route will be rendered:
app/routes/app.product-notes.jsx
import { useNavigate } from "@remix-run/react";import { Outlet, useNavigate } from "@remix-run/react";import { Page, Button, Layout } from "@shopify/polaris";export default function ProductNotesLayout() { const navigate = useNavigate(); async function selectProduct() { const products = await window.shopify.resourcePicker({ type: "product", action: "select", }); const selectedGid = products[0].id; navigate(`/app/product-notes/${encodeURIComponent(selectedGid)}`); } return ( );}
### 4.2. Add the ProductNotesLayout to the sidebar[](https://www.prisma.io/docs/guides/shopify#42-add-the-productnoteslayout-to-the-sidebar "Direct link to 4.2. Add the ProductNotesLayout to the sidebar")
If you run `npm run dev`, you won't be able to see the `Product Notes` route. To fix this, you need to add the `ProductNotesLayout` to the `app.jsx` file so it shows up in the sidebar:
app/routes/app.jsx
import { Link, Outlet, useLoaderData, useRouteError } from "@remix-run/react";import { boundary } from "@shopify/shopify-app-remix/server";import { AppProvider } from "@shopify/shopify-app-remix/react";import { NavMenu } from "@shopify/app-bridge-react";import polarisStyles from "@shopify/polaris/build/esm/styles.css?url";import { authenticate } from "../shopify.server";export const links = () => [{ rel: "stylesheet", href: polarisStyles }];export const loader = async ({ request }) => { await authenticate.admin(request); return { apiKey: process.env.SHOPIFY_API_KEY || "" };};export default function App() { const { apiKey } = useLoaderData(); return ( Home Product Notes );}// Shopify needs Remix to catch some thrown responses, so that their headers are included in the response.export function ErrorBoundary() { return boundary.error(useRouteError());}export const headers = (headersArgs) => { return boundary.headers(headersArgs);};
5\. Create your product notes route[](https://www.prisma.io/docs/guides/shopify#5-create-your-product-notes-route "Direct link to 5. Create your product notes route")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Currently, if you run `npm run dev` and navigate to the `Product Notes` route, you will see nothing once selecting a product.
Follow these steps to create the product notes route:
Create a new `routes/app/app.notes.$productGid.jsx` file which will take in the productGid as a parameter, and return the product notes associated with the product as well as a form to create a new note:
app/routes/app/app.notes.$productGid.jsx
export default function ProductNotes() { return ( <>> );}
### 5.1. Render the notes[](https://www.prisma.io/docs/guides/shopify#51-render-the-notes "Direct link to 5.1. Render the notes")
On load, the route will need to fetch the notes for the product and display them.
Add a `loader` function to the route:
app/routes/app/app.notes.$productGid.jsx
import { json } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";import { getNotes } from "../models/note.server";export const loader = async ({ params }) => { const { productGid } = params; const notes = await getNotes(productGid); return json({ notes, productGid });};export default function ProductNotes() { const { notes, productGid } = useLoaderData(); return ( <>> );}
Map out the notes in the `ProductNotes` component, using Polaris components:
app/routes/app/app.notes.$productGid.jsx
import { json } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";import { getNotes } from "../models/note.server";import { Card, Layout, Text, BlockStack } from "@shopify/polaris";export const loader = async ({ params }) => { const { productGid } = params; const notes = await getNotes(productGid); return json({ notes, productGid });};export default function ProductNotes() { const { notes, productGid } = useLoaderData(); return ( <> {notes.length === 0 ? ( No notes yet. ) : ( notes.map((note) => ( {note.body && ( {note.body} )} Added: {new Date(note.createdAt).toLocaleString()} )) )} > );}
You should be seeing "No notes yet.". If so, you're on the right track.
### 5.2. Add the form[](https://www.prisma.io/docs/guides/shopify#52-add-the-form "Direct link to 5.2. Add the form")
A few things need to be added to the route in order to create a new note:
* Add an `action` function to the route.
* Display a `Toast` notification when a note is created.
* Import the `createNote` function from `models/note.server.js`.
* Import the `useActionData` and `useAppBridge`
app/routes/app/app.notes.$productGid.jsx
import { json, redirect } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";import { useLoaderData, useActionData } from "@remix-run/react";import { getNotes } from "../models/note.server";import { getNotes, createNote } from "../models/note.server";import { Card, Layout, Text, BlockStack } from "@shopify/polaris";import { useAppBridge } from "@shopify/app-bridge-react";export const loader = async ({ params }) => { const { productGid } = params; const notes = await getNotes(productGid); return json({ notes, productGid });};export const action = async ({ request, params }) => { const formData = await request.formData(); const body = formData.get("body")?.toString() || null; const { productGid } = params; await createNote({ productGid, body }); return redirect(`/app/product-notes/${encodeURIComponent(productGid)}`);};export default function ProductNotes() { const { notes, productGid } = useLoaderData(); const actionData = useActionData(); const app = useAppBridge(); useEffect(() => { if (actionData?.ok) { app.toast.show("Note saved", { duration: 3000 }); setBody(""); } }, [actionData, app]); return ( <> {notes.length === 0 ? ( No notes yet. ) : ( notes.map((note) => ( {note.body && ( {note.body} )} Added: {new Date(note.createdAt).toLocaleString()} )) )} > );}
Now, you can build out the form that will call the `action` function:
app/routes/app/app.notes.$productGid.jsx
import { json, redirect } from "@remix-run/node";import { useLoaderData, useActionData } from "@remix-run/react";import { getNotes, createNote } from "../models/note.server";import { Card, Layout, Text, BlockStack } from "@shopify/polaris";import { Card, Layout, Text, BlockStack, Form, FormLayout, TextField, Button } from "@shopify/polaris";import { useAppBridge } from "@shopify/app-bridge-react";export const loader = async ({ params }) => { const { productGid } = params; const notes = await getNotes(productGid); return json({ notes, productGid });};export const action = async ({ request, params }) => { const formData = await request.formData(); const body = formData.get("body")?.toString() || null; const { productGid } = params; await createNote({ productGid, body }); return redirect(`/app/product-notes/${encodeURIComponent(productGid)}`);};export default function ProductNotes() { const { notes, productGid } = useLoaderData(); const actionData = useActionData(); const app = useAppBridge(); useEffect(() => { if (actionData?.ok) { app.toast.show("Note saved", { duration: 3000 }); setBody(""); } }, [actionData, app]); return ( <> {notes.length === 0 ? ( No notes yet. ) : ( notes.map((note) => ( {note.body && ( {note.body} )} Added: {new Date(note.createdAt).toLocaleString()} )) )} > );}
You should now be able to add a note to a product and see it displayed.
### 6\. Test your route[](https://www.prisma.io/docs/guides/shopify#6-test-your-route "Direct link to 6. Test your route")
Run `npm run dev` and navigate to the `Product Notes` route.
* Navigate to Product Notes on the sidebar
* Select a product
* Add a note
* Verify that notes are displayed and saved correctly.
Next Steps[](https://www.prisma.io/docs/guides/shopify#next-steps "Direct link to Next Steps")
------------------------------------------------------------------------------------------------
Now that you have a working Shopify app connected to a Prisma Postgres database, you can:
* Extend your Prisma schema with more models and relationships
* Add create/update/delete routes and forms
* Enable query caching with [Prisma Postgres](https://www.prisma.io/docs/postgres/database/caching)
for better performance
### More Info[](https://www.prisma.io/docs/guides/shopify#more-info "Direct link to More Info")
* [Prisma Documentation](https://www.prisma.io/docs/orm/overview/introduction)
* [Shopify Dev Documentation](https://shopify.dev/docs)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/shopify%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/shopify%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/shopify%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/210-shopify.mdx)
* [Introduction](https://www.prisma.io/docs/guides/shopify#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/shopify#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/shopify#1-set-up-your-project)
* [2\. Set up Prisma](https://www.prisma.io/docs/guides/shopify#2-set-up-prisma)
* [3\. Create your Remix model](https://www.prisma.io/docs/guides/shopify#3-create-your-remix-model)
* [4\. Create your layout route](https://www.prisma.io/docs/guides/shopify#4-create-your-layout-route)
* [4.1. Create the ProductNotesLayout component](https://www.prisma.io/docs/guides/shopify#41-create-the-productnoteslayout-component)
* [4.2. Add the ProductNotesLayout to the sidebar](https://www.prisma.io/docs/guides/shopify#42-add-the-productnoteslayout-to-the-sidebar)
* [5\. Create your product notes route](https://www.prisma.io/docs/guides/shopify#5-create-your-product-notes-route)
* [5.1. Render the notes](https://www.prisma.io/docs/guides/shopify#51-render-the-notes)
* [5.2. Add the form](https://www.prisma.io/docs/guides/shopify#52-add-the-form)
* [6\. Test your route](https://www.prisma.io/docs/guides/shopify#6-test-your-route)
* [Next Steps](https://www.prisma.io/docs/guides/shopify#next-steps)
* [More Info](https://www.prisma.io/docs/guides/shopify#more-info)
---
# How to use Prisma ORM and Prisma Postgres with SolidStart | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/solid-start#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/solid-start#introduction "Direct link to Introduction")
----------------------------------------------------------------------------------------------------------
Prisma ORM streamlines database access with type-safe queries and a smooth developer experience. SolidStart, a modern framework for building reactive web apps with SolidJS, pairs well with Prisma and Postgres to create a clean and scalable full-stack architecture.
In this guide, you'll learn how to integrate Prisma ORM with a Prisma Postgres database in a SolidStart project from scratch. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/solid-start)
.
Prerequisites[](https://www.prisma.io/docs/guides/solid-start#prerequisites "Direct link to Prerequisites")
-------------------------------------------------------------------------------------------------------------
* [Node.js 18+](https://nodejs.org/)
1\. Set up your project[](https://www.prisma.io/docs/guides/solid-start#1-set-up-your-project "Direct link to 1. Set up your project")
----------------------------------------------------------------------------------------------------------------------------------------
Begin by creating a new SolidStart app. In your terminal, run:
npm init solid@latest
Use the following options when prompted:
info
* _Project name:_ `my-solid-prisma-app`
* _Is this a SolidStart project:_ `Yes`
* _Template:_ `bare`
* _Use TypeScript:_ `Yes`
Next, navigate into your new project, install dependencies, and start the development server:
cd my-solid-prisma-appnpm installnpm run dev
Once the dev server is running, open `http://localhost:3000` in your browser. You should see the SolidStart welcome screen.
Clean up the default UI by editing the `app.tsx` file and replacing its content with the following code:
src/app.tsx
import "./app.css";export default function App() { return (
SolidStart + Prisma
);}
2\. Install and Configure Prisma[](https://www.prisma.io/docs/guides/solid-start#2-install-and-configure-prisma "Direct link to 2. Install and Configure Prisma")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/solid-start#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, you'll need to install a few dependencies:
* Prisma Postgres (recommended)
* Other databases
npm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client
npm install prisma tsx --save-devnpm install @prisma/client
Once installed, initialize Prisma in your project:
npx prisma init --db --output ../src/generated/prisma
info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My SolidStart Project"
This will create:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `src/generated/prisma`.
### 2.2. Define your Prisma Schema[](https://www.prisma.io/docs/guides/solid-start#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma Schema")
In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider:
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../src/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
### 2.3. Configure the Prisma Client generator[](https://www.prisma.io/docs/guides/solid-start#23-configure-the-prisma-client-generator "Direct link to 2.3. Configure the Prisma Client generator")
Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/solid-start#24-seed-the-database "Direct link to 2.4. Seed the database")
Let's add some seed data to populate the database with sample users and posts.
Create a new file called `seed.ts` in the `prisma/` directory:
prisma/seed.ts
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();
Now, tell Prisma how to run this script by updating your `package.json`:
package.json
{ "name": "prisma-solid", "type": "module", "scripts": { "dev": "vinxi dev", "build": "vinxi build", "start": "vinxi start" }, "prisma": { "seed": "tsx prisma/seed.ts" } "dependencies": { "@prisma/client": "^6.5.0", "@prisma/extension-accelerate": "^1.3.0", "@solidjs/start": "^1.1.0", "solid-js": "^1.9.5", "vinxi": "^0.5.3" }, "engines": { "node": ">=22" }, "devDependencies": { "@types/node": "^22.13.11", "prisma": "^6.5.0", "tsx": "^4.19.3" }}
Run the seed script:
npx prisma db seed
And open Prisma Studio to inspect your data:
npx prisma studio
3\. Integrate Prisma into SolidStart[](https://www.prisma.io/docs/guides/solid-start#3-integrate-prisma-into-solidstart "Direct link to 3. Integrate Prisma into SolidStart")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Create a Prisma Client[](https://www.prisma.io/docs/guides/solid-start#31-create-a-prisma-client "Direct link to 3.1. Create a Prisma Client")
At the root of your project, create a new `lib` folder and a `prisma.ts` file inside it:
mkdir -p lib && touch lib/prisma.ts
Add the following code to create a Prisma Client instance:
* Prisma Postgres (recommended)
* Other databases
lib/prisma.ts
import { PrismaClient } from "../src/generated/prisma/client.js";import { withAccelerate } from "@prisma/extension-accelerate";const prisma = new PrismaClient().$extends(withAccelerate());export default prisma;
lib/prisma.ts
import { PrismaClient } from "../src/generated/prisma/client.js";const prisma = new PrismaClient();export default prisma;
warning
We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)
) to manage database connections efficiently.
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
### 3.2. Create an API Route[](https://www.prisma.io/docs/guides/solid-start#32-create-an-api-route "Direct link to 3.2. Create an API Route")
Now, let's fetch data from the database using an API route.
Create a new file at `src/routes/api/users.ts`:
src/routes/api/users.ts
import prisma from "../../../lib/prisma";export async function GET() { const users = await prisma.user.findMany({ include: { posts: true, }, }); return new Response(JSON.stringify(users), { headers: { "Content-Type": "application/json" }, });}
### 3.3. Fetch Data in Your Component[](https://www.prisma.io/docs/guides/solid-start#33-fetch-data-in-your-component "Direct link to 3.3. Fetch Data in Your Component")
In your `app.tsx` file, use `createResource` to fetch data from your new API route:
src/app.tsx
import "./app.css";import { createResource } from "solid-js";import { User, Post } from "./generated/prisma/client";type UserWithPosts = User & { posts: Post[];};const fetchUsers = async () => { const res = await fetch("http://localhost:3000/api/users"); return res.json();};export default function App() { const [users, { mutate, refetch }] = createResource(fetchUsers); return (
SolidStart + Prisma
);}
info
`createResource` is a SolidJS hook for managing async data. It tracks loading and error states automatically. [Learn more](https://docs.solidjs.com/reference/basic-reactivity/create-resource#createresource)
.
### 3.4. Display the Data[](https://www.prisma.io/docs/guides/solid-start#34-display-the-data "Direct link to 3.4. Display the Data")
To show the users and their posts, use SolidJS's `` component:
src/app.tsx
import "./app.css";import { createResource, For } from "solid-js";import { User, Post } from "./generated/prisma/client";type UserWithPosts = User & { posts: Post[];};const fetchUsers = async () => { const res = await fetch("http://localhost:3000/api/users"); return res.json();};export default function App() { const [users, { mutate, refetch }] = createResource(fetchUsers); return (
SolidJS + Prisma
{(user) => (
{user.name}
{(post) =>
{post.title}
}
)} );}
info
`` loops through an array reactively. Think of it like `.map()` in React. [Learn more](https://docs.solidjs.com/reference/components/for)
### 3.5. Add Loading and Error States[](https://www.prisma.io/docs/guides/solid-start#35-add-loading-and-error-states "Direct link to 3.5. Add Loading and Error States")
Use SolidJS's `` component to handle loading and error conditions:
src/app.tsx
import "./app.css";import { createResource, For, Show } from "solid-js";import { User, Post } from "./generated/prisma/client";type UserWithPosts = User & { posts: Post[];};const fetchUsers = async () => { const res = await fetch("http://localhost:3000/api/users"); return res.json();};export default function App() { const [users, { mutate, refetch }] = createResource(fetchUsers); return (
SolidJS + Prisma
Loading...
}> Error loading data}> {(user) => (
{user.name}
{(post) =>
{post.title}
}
)} );}
info
`` conditionally renders content. It's similar to an `if` statement. [Learn more](https://docs.solidjs.com/reference/components/show)
You're done! You've just created a SolidStart app connected to a Prisma Postgres database.
Next Steps[](https://www.prisma.io/docs/guides/solid-start#next-steps "Direct link to Next Steps")
----------------------------------------------------------------------------------------------------
Now that you have a working SolidStart app connected to a Prisma Postgres database, you can:
* Extend your Prisma schema with more models and relationships
* Add create/update/delete routes and forms
* Explore authentication, validation, and optimistic updates
* Enable query caching with [Prisma Postgres](https://www.prisma.io/docs/postgres/database/caching)
for better performance
More Info[](https://www.prisma.io/docs/guides/solid-start#more-info "Direct link to More Info")
-------------------------------------------------------------------------------------------------
* [Prisma ORM Docs](https://www.prisma.io/docs/orm/overview/introduction)
* [SolidStart Documentation](https://start.solidjs.com/)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/solid-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/solid-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/solid-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/180-solid-start.mdx)
* [Introduction](https://www.prisma.io/docs/guides/solid-start#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/solid-start#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/solid-start#1-set-up-your-project)
* [2\. Install and Configure Prisma](https://www.prisma.io/docs/guides/solid-start#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/solid-start#21-install-dependencies)
* [2.2. Define your Prisma Schema](https://www.prisma.io/docs/guides/solid-start#22-define-your-prisma-schema)
* [2.3. Configure the Prisma Client generator](https://www.prisma.io/docs/guides/solid-start#23-configure-the-prisma-client-generator)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/solid-start#24-seed-the-database)
* [3\. Integrate Prisma into SolidStart](https://www.prisma.io/docs/guides/solid-start#3-integrate-prisma-into-solidstart)
* [3.1. Create a Prisma Client](https://www.prisma.io/docs/guides/solid-start#31-create-a-prisma-client)
* [3.2. Create an API Route](https://www.prisma.io/docs/guides/solid-start#32-create-an-api-route)
* [3.3. Fetch Data in Your Component](https://www.prisma.io/docs/guides/solid-start#33-fetch-data-in-your-component)
* [3.4. Display the Data](https://www.prisma.io/docs/guides/solid-start#34-display-the-data)
* [3.5. Add Loading and Error States](https://www.prisma.io/docs/guides/solid-start#35-add-loading-and-error-states)
* [Next Steps](https://www.prisma.io/docs/guides/solid-start#next-steps)
* [More Info](https://www.prisma.io/docs/guides/solid-start#more-info)
---
# Set up PostgreSQL on Supabase with Prisma Accelerate's Connection Pool | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/supabase-accelerate#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/supabase-accelerate#introduction "Direct link to Introduction")
------------------------------------------------------------------------------------------------------------------
This guides teaches you how to add connection pooling to a PostgreSQL database hosted on [Supabase](https://supabase.com/)
using [Prisma Accelerate](https://www.prisma.io/docs/accelerate)
.
Prisma Accelerate is a robust and mature connection pooler enabling your database to function properly during traffic spikes and high load scenarios. Check out this [video](https://www.youtube.com/watch?v=cnL75if6Aq0)
demonstrating how it performs in a load test or [learn why connection pooling is important](https://www.prisma.io/blog/saving-black-friday-with-connection-pooling)
.
Prerequisites[](https://www.prisma.io/docs/guides/supabase-accelerate#prerequisites "Direct link to Prerequisites")
---------------------------------------------------------------------------------------------------------------------
To successfully complete this guide, you need **a connection string for a PostgreSQL instance hosted on Supabase**. It typically looks similar to this:
postgresql://postgres:[YOUR-PASSWORD]@db.nzpppscrldfwlzfalbrf.supabase.co:5432/postgres
If you already have a project using Prisma ORM, you can skip the first two steps and jump ahead to [Step 3. Install the Accelerate extension](https://www.prisma.io/docs/guides/supabase-accelerate#3-install-the-accelerate-extension)
.
1\. Set up Prisma ORM[](https://www.prisma.io/docs/guides/supabase-accelerate#1-set-up-prisma-orm "Direct link to 1. Set up Prisma ORM")
------------------------------------------------------------------------------------------------------------------------------------------
Start by installing the Prisma CLI in your project:
npm install prisma --save-dev
Then, run the following command to initialize a new project:
npx prisma init
This will create a new `prisma` directory with a `schema.prisma` file and add a `.env` file with the `DATABASE_URL` environment variable.
Update the file and set the `DATABASE_URL` to your Supabase connection string:
.env
DATABASE_URL="postgresql://postgres:[YOUR-PASSWORD]@db.nzpppscrldfwlzfalbrf.supabase.co:5432/postgres"
2\. Introspect your database[](https://www.prisma.io/docs/guides/supabase-accelerate#2-introspect-your-database "Direct link to 2. Introspect your database")
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Next, run the following command to introspect your database and create your data model:
npx prisma db pull
This command reads your database schema and creates new models in your `schema.prisma` file that match the tables in your database.
note
If you want to use Prisma Migrate in the future, you also need to [baseline your database](https://www.prisma.io/docs/orm/prisma-migrate/workflows/baselining)
.
3\. Install the Accelerate extension[](https://www.prisma.io/docs/guides/supabase-accelerate#3-install-the-accelerate-extension "Direct link to 3. Install the Accelerate extension")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Install the Prisma Client extension for Accelerate:
npm install @prisma/extension-accelerate
This is needed to access Prisma Accelerate's connection pool.
4\. Set up Accelerate in the Prisma Console[](https://www.prisma.io/docs/guides/supabase-accelerate#4-set-up-accelerate-in-the-prisma-console "Direct link to 4. Set up Accelerate in the Prisma Console")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To set up Accelerate in the Prisma Console, follow these steps:
1. Log into the .
2. Select **New project**
3. Choose a **Name** for your project
4. In the **Choose your starting product** section, find the **Accelerate** card and click **Get started**
5. In the field for your **Database connection string**, paste your Supabase connection string
6. Select the **Region** that's closest to your database
7. Click **Create project**
8. On the next screen, click **Enable Accelerate**
Once you went through these steps, you'll be redirected to another page where you need to the click the **Generate API key** button.
You'll then be shown a new connection URL which enables you to connect to Prisma Accelerate's connection pool. This needs to be set as the new `DATABASE_URL` in your `.env` file:
.env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=ey..."
note
If you want to use Prisma Migrate with Prisma Accelerate, you can set the `directUrl` field on the `datasource` block:
schema.prisma
datasource db { url = env("DATABASE_URL") // points to the connection pool for queries directUrl = env("DIRECT_URL") // points to the database for migrations}
Accordingly, you'll need to set the `DIRECT_URL` in your `.env` file:
.env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=ey..."DIRECT_URL="postgresql://postgres:[YOUR-PASSWORD]@db.nzpppscrldfwlzfalbrf.supabase.co:5432/postgres"
5\. Generate Prisma Client[](https://www.prisma.io/docs/guides/supabase-accelerate#5-generate-prisma-client "Direct link to 5. Generate Prisma Client")
---------------------------------------------------------------------------------------------------------------------------------------------------------
With your Prisma schema in place, you can go ahead and generate Prisma Client:
npx prisma generate --no-engine
The `--no-engine` option is used to omit the [query engine](https://www.prisma.io/docs/orm/more/under-the-hood/engines)
in the generated Prisma Client library. The query engine manages Prisma ORM's internal connection pool and is not needed when using Prisma Accelerate.
6\. Send queries through the connection pool[](https://www.prisma.io/docs/guides/supabase-accelerate#6-send-queries-through-the-connection-pool "Direct link to 6. Send queries through the connection pool")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
In your application code, you now need to apply the Accelerate extension to your Prisma Client instance:
import { PrismaClient } from "./generated/prisma"import { withAccelerate } from "@prisma/extension-accelerate"const prisma = new PrismaClient().$extends(withAccelerate())
At this point, you can now start sending queries which will be routed through the connection pool to your database.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/supabase-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/supabase-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/supabase-accelerate%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/300-supabase-accelerate.mdx)
* [Introduction](https://www.prisma.io/docs/guides/supabase-accelerate#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/supabase-accelerate#prerequisites)
* [1\. Set up Prisma ORM](https://www.prisma.io/docs/guides/supabase-accelerate#1-set-up-prisma-orm)
* [2\. Introspect your database](https://www.prisma.io/docs/guides/supabase-accelerate#2-introspect-your-database)
* [3\. Install the Accelerate extension](https://www.prisma.io/docs/guides/supabase-accelerate#3-install-the-accelerate-extension)
* [4\. Set up Accelerate in the Prisma Console](https://www.prisma.io/docs/guides/supabase-accelerate#4-set-up-accelerate-in-the-prisma-console)
* [5\. Generate Prisma Client](https://www.prisma.io/docs/guides/supabase-accelerate#5-generate-prisma-client)
* [6\. Send queries through the connection pool](https://www.prisma.io/docs/guides/supabase-accelerate#6-send-queries-through-the-connection-pool)
---
# Prisma Optimize | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize#__docusaurus_skipToContent_fallback)
On this page
Prisma Optimize
===============
[Prisma Optimize](https://www.prisma.io/optimize?utm_source=docs)
. helps you generate insights and provides recommendations that can help you make your database queries faster.
This helps you to:
* Generate insights about your database queries
* Identify errors to help debug your database queries
* Receive recommendations and discuss them with an AI assistant to enhance query performance.
Optimize aims to help developers of all skill levels write efficient database queries, reducing database load and making applications more responsive.
[###### Get started\
\
Start analyzing the prisma queries in your app in 5 minutes.](https://www.prisma.io/docs/optimize/getting-started)
[###### Examples\
\
Explore our ready-to-run examples using Optimize.](https://github.com/prisma/prisma-examples?tab=readme-ov-file#prisma-optimize)
Supported databases[](https://www.prisma.io/docs/optimize#supported-databases "Direct link to Supported databases")
---------------------------------------------------------------------------------------------------------------------
Optimize works with the database you already have.
[](https://www.prisma.io/docs/optimize/getting-started)
[](https://www.prisma.io/docs/optimize/getting-started)
[](https://www.prisma.io/docs/optimize/getting-started)
[](https://www.prisma.io/docs/optimize/getting-started)
[](https://www.prisma.io/docs/optimize/getting-started)
In this section[](https://www.prisma.io/docs/optimize#in-this-section "Direct link to In this section")
---------------------------------------------------------------------------------------------------------
[Optimize\
--------\
\
Prisma Optimize](https://www.prisma.io/docs/optimize)
[Getting Started\
---------------\
\
Prerequisites](https://www.prisma.io/docs/optimize/getting-started)
[Recordings\
----------\
\
The recordings feature helps developers debug and isolate sets of queries into distinct sessions, known as recordings. This targeted approach enables precise performance analysis and optimization by preventing the mixing of queries from different applications or test rounds, leading to clearer insights and more effective debugging.](https://www.prisma.io/docs/optimize/recordings)
[Recommendations\
---------------\
\
Optimize provides recommendations focused on performance improvements such as indexing issues, excessive data retrieval, and inefficient query patterns. Recommendations include:](https://www.prisma.io/docs/optimize/recommendations)
[Prisma AI\
---------\
\
Prisma AI enables you to ask follow-up questions on a provided recommendation for additional clarity. Learn more about Prisma AI here.](https://www.prisma.io/docs/optimize/prisma-ai)
[Performance metrics\
-------------------\
\
An Optimize recording session provides detailed insights into the latencies of executed queries, capturing key metrics such as average duration, 50th percentile, 99th percentile, and maximal query execution time.](https://www.prisma.io/docs/optimize/performance-metrics)
[FAQ\
---\
\
To learn more about frequently asked questions around Prisma Optimize and query recommendations, visit this page.](https://www.prisma.io/docs/optimize/faq)
[Known limitations\
-----------------\
\
Below are the known limitations when using Prisma Optimize. If you are aware of any limitations that are missing, please let us know on the #help-and-questions channel in our community Discord.](https://www.prisma.io/docs/optimize/known-limitations)
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/optimize/%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/optimize/%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/optimize/%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/700-optimize/index.mdx)
* [Supported databases](https://www.prisma.io/docs/optimize#supported-databases)
* [In this section](https://www.prisma.io/docs/optimize#in-this-section)
---
# Prisma Optimize: FAQ | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize/faq#__docusaurus_skipToContent_fallback)
To learn more about frequently asked questions around Prisma Optimize and query recommendations, [visit this page](https://www.prisma.io/docs/postgres/more/faq#query-optimization)
.
---
# How to use Prisma ORM and Prisma Postgres with SvelteKit | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/sveltekit#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/sveltekit#introduction "Direct link to Introduction")
--------------------------------------------------------------------------------------------------------
Prisma ORM simplifies database access with type-safe queries, and when paired with [SvelteKit](https://svelte.dev/docs/kit)
, it creates a robust and scalable full-stack architecture.
In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in a SvelteKit project from scratch. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/sveltekit)
.
Prerequisites[](https://www.prisma.io/docs/guides/sveltekit#prerequisites "Direct link to Prerequisites")
-----------------------------------------------------------------------------------------------------------
* [Node.js 18+](https://nodejs.org/)
* [Svelte VSCode extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode)
(Recommended by Svelte)
1\. Set up your project[](https://www.prisma.io/docs/guides/sveltekit#1-set-up-your-project "Direct link to 1. Set up your project")
--------------------------------------------------------------------------------------------------------------------------------------
You'll be using [Svelte CLI](https://github.com/sveltejs/cli)
instead of `npx create svelte@latest`. This CLI provides a more interactive setup and built-in support for popular tooling like ESLint and Prettier
Create a new Svelte project:
npx sv create sveltekit-prisma
It will prompt you to customize your setup. Here are the options you'll choose:
info
* _Which template would you like?_ `SvelteKit minimal`
* _Add type checking with TypeScript?_ `Yes, using TypeScript syntax`
* _What would you like to add to your project?_
* `prettier`
* `eslint`
* _Which package manager do you want to install dependencies with?_ `npm`
Once the setup completes, navigate into your project and start the development server:
cd sveltekit-prismanpm run dev
That's it! Svelte makes it a very simple process to get up and running. At this point, your project is ready to integrate Prisma and connect to a Prisma Postgres database.
2\. Install and Configure Prisma[](https://www.prisma.io/docs/guides/sveltekit#2-install-and-configure-prisma "Direct link to 2. Install and Configure Prisma")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/sveltekit#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, you'll need to install a few dependencies:
* Prisma Postgres (recommended)
* Other databases
npm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client
npm install prisma tsx --save-devnpm install @prisma/client
Once installed, initialize Prisma in your project:
npx prisma init --db --output src/generated/prisma
info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My SvelteKit Project"
This will create:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `src/generated/prisma`.
### 2.2. Define your Prisma Schema[](https://www.prisma.io/docs/guides/sveltekit#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma Schema")
In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider:
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../src/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
### 2.3. Configure the Prisma Client generator[](https://www.prisma.io/docs/guides/sveltekit#23-configure-the-prisma-client-generator "Direct link to 2.3. Configure the Prisma Client generator")
Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/sveltekit#24-seed-the-database "Direct link to 2.4. Seed the database")
Add some seed data to populate the database with sample users and posts.
Create a new file called `seed.ts` in the `prisma/` directory:
prisma/seed.ts
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();
Now, tell Prisma how to run this script by updating your `package.json`:
package.json
{ "name": "sveltekit-prisma", "private": true, "version": "0.0.1", "type": "module", "scripts": { // ... }, "prisma": { "seed": "tsx prisma/seed.ts" } "devDependencies": { // ... }, "dependencies": { // ... }}
Run the seed script:
npx prisma db seed
And open Prisma Studio to inspect your data:
npx prisma studio
3\. Integrate Prisma into SvelteKit[](https://www.prisma.io/docs/guides/sveltekit#3-integrate-prisma-into-sveltekit "Direct link to 3. Integrate Prisma into SvelteKit")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1. Create a Prisma Client[](https://www.prisma.io/docs/guides/sveltekit#31-create-a-prisma-client "Direct link to 3.1. Create a Prisma Client")
Inside your `/src/lib` directory, rename `index.ts` to `prisma.ts`. This file will be used to create and export your Prisma Client instance.
tip
Files in `src/lib` can be accessed from anywhere using the `$lib` alias.
The `DATABASE_URL` is stored in the `.env` file. To access it, you'll need to import it from the [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private)
namespace.
Set up the Prisma client like this:
* Prisma Postgres (recommended)
* Other databases
src/lib/prisma.ts
import { PrismaClient } from '../generated/prisma/client.js';import { DATABASE_URL } from '$env/static/private';import { withAccelerate } from '@prisma/extension-accelerate';const prisma = new PrismaClient({ datasourceUrl: DATABASE_URL}).$extends(withAccelerate());export default prisma;
src/lib/prisma.ts
import { PrismaClient } from '../generated/prisma/client.js';import { DATABASE_URL } from '$env/static/private';const prisma = new PrismaClient({ datasourceUrl: DATABASE_URL});export default prisma;
warning
We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)
) to manage database connections efficiently.
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
### 3.2. Create a server route[](https://www.prisma.io/docs/guides/sveltekit#32-create-a-server-route "Direct link to 3.2. Create a server route")
To fetch data from the database on the server side, create a `+page.server.ts` file in your `routes` directory. This file should export a `load` function, which runs on the server before your page renders.
Use the `findMany()` method within a basic `load` function to get a list of users.
Update your `+page.server.ts` file like this:
src/routes/+page.server.ts
import prisma from '$lib/prisma';export async function load() { const users = await prisma.user.findMany({}); return { users };}
At this point, you're only getting data directly on the `User` model — no relations like posts are included yet.
To also fetch each user's posts, we can expand the query using the `include` option. This tells Prisma to join the related `Posts` table in the result.
Update your `findMany()` call like this:
src/routes/+page.server.ts
import prisma from '$lib/prisma';export async function load() { const users = await prisma.user.findMany({ include: { posts: true } }); return { users };}
Now, every user in the result will also include a `posts` array.
### 3.3. Populate the page[](https://www.prisma.io/docs/guides/sveltekit#33-populate-the-page "Direct link to 3.3. Populate the page")
In `src/routes/+page.svelte`, strip the file down to the basics and add a `
SvelteKit + Prisma
We need to grab the data exported from `+page.server.ts`:
src/routes/+page.svelte
SvelteKit + Prisma
Now that we have the data, let's map through the users and their posts with Svelte's [`each`](https://svelte.dev/docs/svelte/each)
block:
src/routes/+page.svelte
{/each}{/each}
You're done! You've just created a SvelteKit app with Prisma ORM. Below are some next steps to explore, as well as some more resources to help you get started expanding your project.
Next Steps[](https://www.prisma.io/docs/guides/sveltekit#next-steps "Direct link to Next Steps")
--------------------------------------------------------------------------------------------------
Now that you have a working SvelteKit app connected to a Prisma Postgres database, you can:
* Extend your Prisma schema with more models and relationships
* Add create/update/delete routes and forms
* Explore authentication and validation
* Enable query caching with [Prisma Postgres](https://www.prisma.io/docs/postgres/database/caching)
for better performance
### More Info[](https://www.prisma.io/docs/guides/sveltekit#more-info "Direct link to More Info")
* [Prisma Documentation](https://www.prisma.io/docs/orm/overview/introduction)
* [SvelteKit Documentation](https://svelte.dev/docs/kit)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/sveltekit%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/sveltekit%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/sveltekit%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/190-sveltekit.mdx)
* [Introduction](https://www.prisma.io/docs/guides/sveltekit#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/sveltekit#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/sveltekit#1-set-up-your-project)
* [2\. Install and Configure Prisma](https://www.prisma.io/docs/guides/sveltekit#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/sveltekit#21-install-dependencies)
* [2.2. Define your Prisma Schema](https://www.prisma.io/docs/guides/sveltekit#22-define-your-prisma-schema)
* [2.3. Configure the Prisma Client generator](https://www.prisma.io/docs/guides/sveltekit#23-configure-the-prisma-client-generator)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/sveltekit#24-seed-the-database)
* [3\. Integrate Prisma into SvelteKit](https://www.prisma.io/docs/guides/sveltekit#3-integrate-prisma-into-sveltekit)
* [3.1. Create a Prisma Client](https://www.prisma.io/docs/guides/sveltekit#31-create-a-prisma-client)
* [3.2. Create a server route](https://www.prisma.io/docs/guides/sveltekit#32-create-a-server-route)
* [3.3. Populate the page](https://www.prisma.io/docs/guides/sveltekit#33-populate-the-page)
* [Next Steps](https://www.prisma.io/docs/guides/sveltekit#next-steps)
* [More Info](https://www.prisma.io/docs/guides/sveltekit#more-info)
---
# How to use Prisma ORM and Prisma Postgres with TanStack Start | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/tanstack-start#__docusaurus_skipToContent_fallback)
On this page
Introduction[](https://www.prisma.io/docs/guides/tanstack-start#introduction "Direct link to Introduction")
-------------------------------------------------------------------------------------------------------------
Prisma ORM simplifies database interactions, and [TanStack Start](https://tanstack.com/start/latest/docs/framework/react/overview)
offers a robust framework for building modern React applications. Together with [Prisma Postgres](https://www.prisma.io/postgres)
, they provide a seamless full-stack development experience with type-safe queries and efficient data management.
This guide will walk you through integrating Prisma ORM with a Prisma Postgres database in a TanStack Start project from scratch.
Prerequisites[](https://www.prisma.io/docs/guides/tanstack-start#prerequisites "Direct link to Prerequisites")
----------------------------------------------------------------------------------------------------------------
* [Node.js 18+](https://nodejs.org/)
1\. Set up your project[](https://www.prisma.io/docs/guides/tanstack-start#1-set-up-your-project "Direct link to 1. Set up your project")
-------------------------------------------------------------------------------------------------------------------------------------------
To begin, create a new TanStack Start project.
note
For the purpose of this guide, we're using the same setup instructions that you can find in the [TanStart Start docs](https://tanstack.com/start/latest/docs/framework/react/build-from-scratch)
.
In the directory where you'd like to create your project, run the following commands:
mkdir tanstack-start-prismacd tanstack-start-prismanpm init -y
This will create a new folder called `tanstack-start-prisma`, navigate into it, and initialize a new Node.js project.
Open the directory in your IDE and create a `tsconfig.json` file with the following configuration:
tsconfig.json
{ "compilerOptions": { "jsx": "react-jsx", "moduleResolution": "Bundler", "module": "ESNext", "target": "ES2022", "skipLibCheck": true, "strictNullChecks": true }}
We also need a `.gitignore` file, so let's set that up now:
.gitignore
node_modules.envapp/generated
Next, install TanStack Router and Vinxi, as TanStack Start currently requires them:
npm install @tanstack/react-start @tanstack/react-router vinxi
We also need React, the Vite React plugin, and TypeScript:
npm install react react-domnpm install --save-dev @vitejs/plugin-react vite-tsconfig-pathsnpm install --save-dev typescript @types/react @types/react-dom
Update your `package.json` to use Vinxi's CLI. Add `"type": "module"` and modify the scripts to use Vinxi's CLI:
package.json
{ "name": "tanstack-start-prisma", "version": "1.0.0", "main": "index.js", "type": "module", "scripts": { "dev": "vinxi dev", "build": "vinxi build", "start": "vinxi start" }, "keywords": [], "author": "", "license": "ISC", "description": "", "dependencies": { "@tanstack/react-router": "^1.119.0", "@tanstack/react-start": "^1.119.0", "react": "^19.1.0", "react-dom": "^19.1.0", "vinxi": "^0.5.6" }, "devDependencies": { "@types/react": "^19.1.2", "@types/react-dom": "^19.1.3", "@vitejs/plugin-react": "^4.4.1", "typescript": "^5.8.3", "vite-tsconfig-paths": "^5.1.4" }}
Then, create and configure TanStack Start's `app.config.ts` file:
app.config.ts
import { defineConfig } from '@tanstack/react-start/config'import tsConfigPaths from 'vite-tsconfig-paths'export default defineConfig({ vite: { plugins: [ tsConfigPaths({ projects: ['./tsconfig.json'], }), ], },})
For TanStack Start to function, we need 5 files in `~/app/`:
* `router.tsx` (The router configuration)
* `ssr.tsx` (The server entry point)
* `client.tsx` (The client entry point)
* `routes/__root.tsx` (The root of the app)
* `routes/index.tsx` (The home page)
You can create them with these commands:
mkdir apptouch app/router.tsxtouch app/ssr.tsxtouch app/client.tsxmkdir app/routestouch app/routes/__root.tsxtouch app/routes/index.tsx
`router.tsx` configures the application's main router with route definitions and settings:
app/router.tsx
import { createRouter as createTanStackRouter } from '@tanstack/react-router'import { routeTree } from './routeTree.gen'export function createRouter() { const router = createTanStackRouter({ routeTree, scrollRestoration: true, }) return router}declare module '@tanstack/react-router' { interface Register { router: ReturnType }}
note
You should be seeing an error about `routeTree.gen.ts` not existing. This is expected. It will be generated when you run TanStack Start for the first time.
`ssr.tsx` allows us to know what routes and loaders we need to execute when the user hits a given route:
app/ssr.tsx
import { createStartHandler, defaultStreamHandler,} from '@tanstack/react-start/server'import { getRouterManifest } from '@tanstack/react-start/router-manifest'import { createRouter } from './router'export default createStartHandler({ createRouter, getRouterManifest,})(defaultStreamHandler)
`client.tsx` initializes the client-side logic to handle routes in the browser:
app/client.tsx
import { hydrateRoot } from "react-dom/client";import { StartClient } from "@tanstack/react-start/client";import { createRouter } from "./router";const router = createRouter();hydrateRoot(document, );
`routes/__root.tsx` defines the root route and global HTML layout for the entire application:
app/routes/\_\_root.tsx
import type { ReactNode } from "react";import { Outlet, createRootRoute, HeadContent, Scripts,} from "@tanstack/react-router";export const Route = createRootRoute({ head: () => ({ meta: [ { charSet: "utf-8", }, { name: "viewport", content: "width=device-width, initial-scale=1", }, { title: "Prisma TanStack Start Demo", }, ], }), component: RootComponent,});function RootComponent() { return ( );}function RootDocument({ children }: Readonly<{ children: ReactNode }>) { return ( {children} );}
`routes/index.tsx` is the home page of the application:
app/routes/index.tsx
import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/")({ component: Home,});function Home() { return (
Posts
);}
Now, run:
npm run dev
This will generate the `routeTree.gen.ts` file and resolve any routing errors.
Your file tree should look like this (without `node_modules`):
.├── app│ ├── client.tsx│ ├── routeTree.gen.ts│ ├── router.tsx│ ├── routes│ │ ├── __root.tsx│ │ └── index.tsx│ └── ssr.tsx├── app.config.ts├── package-lock.json├── package.json└── tsconfig.json
2\. Install and Configure Prisma[](https://www.prisma.io/docs/guides/tanstack-start#2-install-and-configure-prisma "Direct link to 2. Install and Configure Prisma")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install dependencies[](https://www.prisma.io/docs/guides/tanstack-start#21-install-dependencies "Direct link to 2.1. Install dependencies")
To get started with Prisma, you'll need to install a few dependencies:
* Prisma Postgres (recommended)
* Other databases
npm install prisma tsx --save-devnpm install @prisma/extension-accelerate @prisma/client
npm install prisma tsx --save-devnpm install @prisma/client
Once installed, initialize Prisma in your project:
npx prisma init --db --output ../app/generated/prisma
info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My \_\_\_\_\_\_\_\_\_\_ Project"
This will create:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `app/generated/prisma`.
### 2.2. Define your Prisma Schema[](https://www.prisma.io/docs/guides/tanstack-start#22-define-your-prisma-schema "Direct link to 2.2. Define your Prisma Schema")
In `schema.prisma`, create a model for our posts and change the generator to use the [`prisma-client`](https://www.prisma.io/docs/orm/prisma-schema/overview/generators#prisma-client-preview)
provider:
prisma/schema.prisma
generator client { provider = "prisma-client" output = "../app/generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
### 2.3. Configure the Prisma Client generator[](https://www.prisma.io/docs/guides/tanstack-start#23-configure-the-prisma-client-generator "Direct link to 2.3. Configure the Prisma Client generator")
Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
### 2.4. Seed the database[](https://www.prisma.io/docs/guides/tanstack-start#24-seed-the-database "Direct link to 2.4. Seed the database")
Let's add some seed data to populate the database with sample users and posts.
Create a new file called `seed.ts` in the `prisma/` directory:
prisma/seed.ts
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";const prisma = new PrismaClient();const userData: Prisma.UserCreateInput[] = [ { name: "Alice", email: "alice@prisma.io", posts: { create: [ { title: "Join the Prisma Discord", content: "https://pris.ly/discord", published: true, }, { title: "Prisma on YouTube", content: "https://pris.ly/youtube", }, ], }, }, { name: "Bob", email: "bob@prisma.io", posts: { create: [ { title: "Follow Prisma on Twitter", content: "https://www.twitter.com/prisma", published: true, }, ], }, },];export async function main() { for (const u of userData) { await prisma.user.create({ data: u }); }}main();
Now, tell Prisma how to run this script by updating your `package.json`:
package.json
"prisma": { "seed": "tsx prisma/seed.ts"}
Run the seed script:
npx prisma db seed
And open Prisma Studio to inspect your data:
npx prisma studio
3\. Integrate Prisma into TanStack Start[](https://www.prisma.io/docs/guides/tanstack-start#3-integrate-prisma-into-tanstack-start "Direct link to 3. Integrate Prisma into TanStack Start")
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 3.1 Create a Prisma Client[](https://www.prisma.io/docs/guides/tanstack-start#31-create-a-prisma-client "Direct link to 3.1 Create a Prisma Client")
Instead of creating a new Prisma Client instance in each file, create a single instance in a shared file to be used globally.
Create a `/lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance.
Set up the Prisma client like this:
* Prisma Postgres (recommended)
* Other databases
src/lib/prisma.ts
import { PrismaClient } from "../generated/prisma/client.js";import { withAccelerate } from "@prisma/extension-accelerate";const prisma = new PrismaClient().$extends(withAccelerate());export default prisma;
src/lib/prisma.ts
import { PrismaClient } from "../generated/prisma/client.js";const prisma = new PrismaClient();export default prisma;
warning
We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)
) to manage database connections efficiently.
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
### 3.2 Fetch users and posts on load[](https://www.prisma.io/docs/guides/tanstack-start#32-fetch-users-and-posts-on-load "Direct link to 3.2 Fetch users and posts on load")
First, import the necessary modules. Then, create a server function using the [`createServerFn`](https://tanstack.com/start/latest/docs/framework/react/server-functions#defining-server-functions)
function. This function will fetch the users from the database using the `.findMany()` method. Use the [`include`](https://www.prisma.io/docs/orm/prisma-client/queries/relation-queries#include-a-relation)
option to fetch the related posts:
app/routes/index.tsx
import { prisma } from "../lib/prisma";import { createServerFn } from "@tanstack/react-start";import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/")({ component: Home,});const getUsers = createServerFn({ method: "GET" }).handler(async () => { return prisma.user.findMany({ include: { posts: true, }, });});function Home() { return (
Posts
);}
TanStack Start allows functions to run on load with loader functions in the [`createFileRoute`](https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction)
function. Fetch the users and their posts on load with this code:
app/routes/index.tsx
import { prisma } from "../lib/prisma";import { createServerFn } from "@tanstack/react-start";import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/")({ component: Home, loader: () => { return getUsers(); },});const getUsers = createServerFn({ method: "GET" }).handler(async () => { return prisma.user.findMany({ include: { posts: true, }, });});function Home() { return (
Posts
);}
Store the response from the loader in the main component using [`Route.useLoaderData()`](https://tanstack.com/router/latest/docs/framework/react/api/router/useLoaderDataHook)
:
app/routes/index.tsx
import { prisma } from "../lib/prisma";import { createServerFn } from "@tanstack/react-start";import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/")({ component: Home, loader: () => { return getUsers(); },});const getUsers = createServerFn({ method: "GET" }).handler(async () => { return prisma.user.findMany({ include: { posts: true, }, });});function Home() { const users = Route.useLoaderData(); return (
Posts
);}
### 3.3 Display the users and posts[](https://www.prisma.io/docs/guides/tanstack-start#33-display-the-users-and-posts "Direct link to 3.3 Display the users and posts")
Next, you'll update the home page to display the users and posts retrieved from your database.
Map over the `users` and display them in a list along with their `posts`:
app/routes/index.tsx
import { createFileRoute } from "@tanstack/react-router";import { createServerFn } from "@tanstack/react-start";import prisma from "../../lib/prisma";export const Route = createFileRoute("/")({ component: Home, loader: () => { return getUsers(); },});const getUsers = createServerFn({ method: "GET" }).handler(async () => { return prisma.user.findMany({ include: { posts: true, }, });});function Home() { const users = Route.useLoaderData(); return (
Posts
{users.map((user) => (
{user.name}
{user.posts.map((post) => (
{post.title}
))}
))}
);}
This setup will display the posts on your page, fetched directly from your database.
Next steps[](https://www.prisma.io/docs/guides/tanstack-start#next-steps "Direct link to Next steps")
-------------------------------------------------------------------------------------------------------
You've successfully integrated Prisma ORM with TanStack Start, creating a seamless full-stack application. Here are a few suggestions for what you can do next:
* Expand your Prisma models to handle more complex data relationships.
* Implement additional CRUD operations to enhance your application's functionality.
* Explore more features of Prisma and TanStack Start to deepen your understanding.
* Check out [Prisma Postgres](https://www.prisma.io/postgres)
to see how you can scale your application.
More info[](https://www.prisma.io/docs/guides/tanstack-start#more-info "Direct link to More info")
----------------------------------------------------------------------------------------------------
* [Prisma ORM Documentation](https://www.prisma.io/docs/orm/overview/introduction)
* [TanStack Start Documentation](https://tanstack.com/start/latest/docs/framework/react/overview)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/tanstack-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/tanstack-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/tanstack-start%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/160-tanstack-start.mdx)
* [Introduction](https://www.prisma.io/docs/guides/tanstack-start#introduction)
* [Prerequisites](https://www.prisma.io/docs/guides/tanstack-start#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/tanstack-start#1-set-up-your-project)
* [2\. Install and Configure Prisma](https://www.prisma.io/docs/guides/tanstack-start#2-install-and-configure-prisma)
* [2.1. Install dependencies](https://www.prisma.io/docs/guides/tanstack-start#21-install-dependencies)
* [2.2. Define your Prisma Schema](https://www.prisma.io/docs/guides/tanstack-start#22-define-your-prisma-schema)
* [2.3. Configure the Prisma Client generator](https://www.prisma.io/docs/guides/tanstack-start#23-configure-the-prisma-client-generator)
* [2.4. Seed the database](https://www.prisma.io/docs/guides/tanstack-start#24-seed-the-database)
* [3\. Integrate Prisma into TanStack Start](https://www.prisma.io/docs/guides/tanstack-start#3-integrate-prisma-into-tanstack-start)
* [3.1 Create a Prisma Client](https://www.prisma.io/docs/guides/tanstack-start#31-create-a-prisma-client)
* [3.2 Fetch users and posts on load](https://www.prisma.io/docs/guides/tanstack-start#32-fetch-users-and-posts-on-load)
* [3.3 Display the users and posts](https://www.prisma.io/docs/guides/tanstack-start#33-display-the-users-and-posts)
* [Next steps](https://www.prisma.io/docs/guides/tanstack-start#next-steps)
* [More info](https://www.prisma.io/docs/guides/tanstack-start#more-info)
---
# How to use Prisma ORM with Turborepo | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/turborepo#__docusaurus_skipToContent_fallback)
On this page
Prisma is a powerful ORM for managing databases, and [Turborepo](https://turbo.build/)
simplifies monorepo workflows. By combining these tools, you can create a scalable, modular architecture for your projects.
This guide will show you how to set up Prisma as a standalone package in a Turborepo monorepo, enabling efficient configuration, type sharing, and database management across multiple apps.
#### What you'll learn:[](https://www.prisma.io/docs/guides/turborepo#what-youll-learn "Direct link to What you'll learn:")
* How to set up Prisma in a Turborepo monorepo.
* Steps to generate and reuse PrismaClient across packages.
* Integrating the Prisma package into other applications in the monorepo.
### Prerequisites[](https://www.prisma.io/docs/guides/turborepo#prerequisites "Direct link to Prerequisites")
* [Node.js 18+](https://nodejs.org/)
1\. Set up your project[](https://www.prisma.io/docs/guides/turborepo#1-set-up-your-project "Direct link to 1. Set up your project")
--------------------------------------------------------------------------------------------------------------------------------------
To set up a Turborepo monorepo named `turborepo-prisma`, run the following command:
npx create-turbo@latest turborepo-prisma
You'll be prompted to select your package manager, this guide will use `npm`:
info
* _Which package manager do you want to use?_ `npm`
After the setup, choose a package manager for the project. Navigate to the project root directory and install Turborepo as a development dependency:
* npm
* yarn
* pnpm
cd turborepo-prismanpm install turbo --save-dev
cd turborepo-prismayarn add turbo --dev --ignore-workspace-root-check
cd turborepo-prismapnpm add turbo --save-dev --ignore-workspace-root-check
For more information about installing Turborepo, refer to the [official Turborepo guide](https://turbo.build/repo/docs/getting-started/installation)
.
2\. Add a new `database` package to the monorepo[](https://www.prisma.io/docs/guides/turborepo#2-add-a-new-database-package-to-the-monorepo "Direct link to 2-add-a-new-database-package-to-the-monorepo")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1 Create the package and install Prisma[](https://www.prisma.io/docs/guides/turborepo#21-create-the-package-and-install-prisma "Direct link to 2.1 Create the package and install Prisma")
Create a `database` package within the `packages` directory. Then, create a `package.json` file for the package by running:
cd packages/mkdir databasecd databasetouch package.json
Define the `package.json` file as follows:
packages/database/package.json
{ "name": "@repo/db", "version": "0.0.0"}
Next, install the required dependencies to use Prisma ORM. Use your preferred package manager:
* npm
* yarn
* pnpm
npm install prisma --save-devnpm install @prisma/client
yarn add prisma --devyarn add @prisma/client
pnpm add prisma --save-devpnpm add @prisma/client
note
If using [Prisma Postgres](https://prisma.io/postgres)
, install the `@prisma/extension-accelerate` package:
* npm
* yarn
* pnpm
npm install @prisma/extension-accelerate
yarn add @prisma/extension-accelerate
pnpm add @prisma/extension-accelerate
### 2.2. Initialize Prisma and define models[](https://www.prisma.io/docs/guides/turborepo#22-initialize-prisma-and-define-models "Direct link to 2.2. Initialize Prisma and define models")
Inside the `database` directory, initialize prisma by running:
* npm
* yarn
* pnpm
npx prisma init --db --output ../generated/prisma
yarn prisma init --db --output ../generated/prisma
pnpm prisma init --db --output ../generated/prisma
This will create several files inside `packages/database`:
* A `prisma` directory with a `schema.prisma` file.
* A Prisma Postgres database.
* A `.env` file containing the `DATABASE_URL` at the project root.
* An `output` directory for the generated Prisma Client as `generated/prisma`.
In the `packages/database/prisma/schema.prisma` file, add the following models:
packages/database/prisma/schema.prisma
generator client { provider = "prisma-client-js" output = "../generated/prisma"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id])}
warning
It is recommended to add `../generated/prisma` to the `.gitignore` file because it contains platform-specific binaries that can cause compatibility issues across different environments.
#### The importance of generating Prisma types in a custom directory[](https://www.prisma.io/docs/guides/turborepo#the-importance-of-generating-prisma-types-in-a-custom-directory "Direct link to The importance of generating Prisma types in a custom directory")
In the `schema.prisma` file, we specify a custom [`output`](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
path where Prisma will generate its types. This ensures Prisma's types are resolved correctly across different package managers.
info
In this guide, the types will be generated in the `database/generated/prisma` directory.
### 2.3. Add scripts and run migrations[](https://www.prisma.io/docs/guides/turborepo#23-add-scripts-and-run-migrations "Direct link to 2.3. Add scripts and run migrations")
Let's add some scripts to the `package.json` inside `packages/database`:
packages/database/package.json
{ "name": "@repo/db", "version": "0.0.0", "scripts": { "db:generate": "prisma generate", "db:migrate": "prisma migrate dev --skip-generate", "db:deploy": "prisma migrate deploy" }, "devDependencies": { "prisma": "^6.6.0" }, "dependencies": { "@prisma/client": "^6.6.0" }}
Let's also add these scripts to `turbo.json` in the root and ensure that `DATABASE_URL` is added to the environment:
turbo.json
{"$schema": "https://turbo.build/schema.json","ui": "tui","tasks": { "build": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": [".next/**", "!.next/cache/**"], "env": ["DATABASE_URL"] }, "lint": { "dependsOn": ["^lint"] }, "check-types": { "dependsOn": ["^check-types"] }, "dev": { "cache": false, "persistent": true }, "db:generate": { "cache": false }, "db:migrate": { "cache": false, "persistent": true // This is necessary to interact with the CLI and assign names to your database migrations. }, "db:deploy": { "cache": false }}
Migrate your `prisma.schema` and generate types
Navigate to the project root and run the following command to automatically migrate our database:
* npm
* yarn
* pnpm
npx turbo db:migrate
yarn turbo db:migrate
pnpm turbo db:migrate
Generate your `prisma.schema`
To generate the types from Prisma schema, from the project root run:
* npm
* yarn
* pnpm
npx turbo db:generate
yarn turbo db:generate
pnpm turbo db:generate
### 2.4. Export the Prisma client and types[](https://www.prisma.io/docs/guides/turborepo#24-export-the-prisma-client-and-types "Direct link to 2.4. Export the Prisma client and types")
Next, export the generated types and an instance of `PrismaClient` so it can used in your applications.
In the `packages/database` directory, create a `src` folder and add a `client.ts` file. This file will define an instance of `PrismaClient`:
* Prisma Postgres (recommended)
* Other databases
packages/database/src/client.ts
import { PrismaClient } from "../generated/prisma";import { withAccelerate } from "@prisma/extension-accelerate";const globalForPrisma = global as unknown as { prisma: PrismaClient };export const prisma = globalForPrisma.prisma || new PrismaClient().$extends(withAccelerate());if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
packages/database/src/client.ts
import { PrismaClient } from "../generated/prisma";const globalForPrisma = global as unknown as { prisma: PrismaClient };export const prisma = globalForPrisma.prisma || new PrismaClient();if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
Then create an `index.ts` file in the `src` folder to re-export the generated prisma types and the `PrismaClient` instance:
packages/database/src/index.ts
export { prisma } from './client' // exports instance of prisma export * from "../generated/prisma" // exports generated types from prisma
Follow the [Just-in-Time packaging pattern](https://turbo.build/repo/docs/core-concepts/internal-packages#just-in-time-packages)
and create an entrypoint to the package inside `packages/database/package.json`:
warning
If you're not using a bundler, use the [Compiled Packages](https://turborepo.com/docs/core-concepts/internal-packages#compiled-packages)
strategy instead.
packages/database/package.json
{ "name": "@repo/db", "version": "0.0.0", "scripts": { "db:generate": "npx prisma generate", "db:migrate": "npx prisma migrate dev --skip-generate", "db:deploy": "npx prisma migrate deploy" }, "devDependencies": { "prisma": "^6.6.0" }, "dependencies": { "@prisma/client": "^6.6.0" }, "exports": { ".": "./src/index.ts" }}
By completing these steps, you'll make the Prisma types and `PrismaClient` instance accessible throughout the monorepo.
3\. Import the `database` package in the web app[](https://www.prisma.io/docs/guides/turborepo#3-import-the-database-package-in-the-web-app "Direct link to 3-import-the-database-package-in-the-web-app")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The `turborepo-prisma` project should have an app called `web` at `apps/web`. Add the `database` dependency to `apps/web/package.json`:
* npm
* yarn
* pnpm
{ // ... "dependencies": { "@repo/db": "*" // ... } // ...}
{ // ... "dependencies": { "@repo/db": "*" // ... } // ...}
{ // ... "dependencies": { "@repo/db": "workspace:*" // ... } // ...}
Run your package manager's install command inside the `apps/web` directory:
* npm
* yarn
* pnpm
cd apps/webnpm install
cd apps/webyarn install
cd apps/webpnpm install
Let's import the intantiated `prisma` client from the `database` package in the `web` app.
In the `apps/web/app` directory, open the `page.tsx` file and add the following code:
apps/web/app/page.tsx
import styles from "./page.module.css";import { prisma } from "@repo/db";export default async function Home() { const user = await prisma.user.findFirst() return (
{user?.name ?? "No user added yet"}
);}
Then, create a `.env` file in the `web` directory and copy into it the contents of the `.env` file from the `/database` directory containing the `DATABASE_URL`:
apps/web/.env
DATABASE_URL="Same database url as used in the database directory"
note
If you want to use a single `.env` file in the root directory across your apps and packages in a Turborepo setup, consider using a package like [`dotenvx`](https://dotenvx.com/docs/monorepos/turborepo)
.
To implement this, update the `package.json` files for each package or app to ensure they load the required environment variables from the shared `.env` file. For detailed instructions, refer to the [`dotenvx` guide for Turborepo](https://dotenvx.com/docs/monorepos/turborepo)
.
Keep in mind that Turborepo [recommends using separate `.env` files for each package](https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#use-env-files-in-packages)
to promote modularity and avoid potential conflicts.
4\. Configure task dependencies in Turborepo[](https://www.prisma.io/docs/guides/turborepo#4-configure-task-dependencies-in-turborepo "Direct link to 4. Configure task dependencies in Turborepo")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The `db:generate` and `db:deploy` scripts are not yet optimized for the monorepo setup but are essential for the `dev` and `build` tasks.
If a new developer runs `turbo dev` on an application without first running `db:generate`, they will encounter errors.
To prevent this, ensure that `db:generate` is always executed before running `dev` or `build`. Additionally, make sure both `db:deploy` and `db:generate` are executed before `db:build`. Here's how to configure this in your `turbo.json` file:
turbo.json
{ "$schema": "https://turbo.build/schema.json", "ui": "tui", "tasks": { "build": { "dependsOn": ["^build", "^db:generate"], "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": [".next/**", "!.next/cache/**"], "env": ["DATABASE_URL"] }, "lint": { "dependsOn": ["^lint"] }, "check-types": { "dependsOn": ["^check-types"] }, "dev": { "dependsOn": ["^db:generate"], "cache": false, "persistent": true }, "db:generate": { "cache": false }, "db:migrate": { "cache": false, "persistent": true }, "db:deploy": { "cache": false } }}
5\. Run the project in development[](https://www.prisma.io/docs/guides/turborepo#5-run-the-project-in-development "Direct link to 5. Run the project in development")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
warning
Before starting the development server, note that if you are using Next.js v15.2.0, do not use Turbopack as there is a known [issue](https://github.com/vercel/next.js/issues/76497)
. Remove Turbopack from your dev script by updating your `apps/web/package.json`
apps/web/package.json
"script":{ "dev": "next dev --port 3000",}
Then from the project root run the project:
* npm
* yarn
* pnpm
npx turbo run dev --filter=web
yarn turbo run dev --filter=web
pnpm turbo run dev --filter=web
Navigate to the `http://localhost:3000` and you should see the message:
No user added yet
note
You can add users to your database by creating a seed script or manually by using [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio)
.
To use Prisma Studio to add manually data via a GUI, navigate inside the `packages/database` directory and run `prisma studio` using your package manager:
* npm
* yarn
* pnpm
npx prisma studio
yarn prisma studio
pnpm prisma studio
This command starts a server with a GUI at [http://localhost:5555](http://localhost:5555/)
, allowing you to view and modify your data.
Congratulations, you're done setting up Prisma for Turborepo!
Next Steps[](https://www.prisma.io/docs/guides/turborepo#next-steps "Direct link to Next Steps")
--------------------------------------------------------------------------------------------------
* Expand your Prisma models to handle more complex data relationships.
* Implement additional CRUD operations to enhance your application's functionality.
* Check out [Prisma Postgres](https://www.prisma.io/postgres)
to see how you can scale your application.
### More Info[](https://www.prisma.io/docs/guides/turborepo#more-info "Direct link to More Info")
* [Turborepo Docs](https://turbo.build/repo/docs)
* [Next.js Docs](https://nextjs.org/docs)
* [Prisma ORM Docs](https://www.prisma.io/docs/orm/overview/introduction)
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/turborepo%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/turborepo%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/turborepo%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/080-turborepo.mdx)
* [Prerequisites](https://www.prisma.io/docs/guides/turborepo#prerequisites)
* [1\. Set up your project](https://www.prisma.io/docs/guides/turborepo#1-set-up-your-project)
* [2\. Add a new `database` package to the monorepo](https://www.prisma.io/docs/guides/turborepo#2-add-a-new-database-package-to-the-monorepo)
* [2.1 Create the package and install Prisma](https://www.prisma.io/docs/guides/turborepo#21-create-the-package-and-install-prisma)
* [2.2. Initialize Prisma and define models](https://www.prisma.io/docs/guides/turborepo#22-initialize-prisma-and-define-models)
* [2.3. Add scripts and run migrations](https://www.prisma.io/docs/guides/turborepo#23-add-scripts-and-run-migrations)
* [2.4. Export the Prisma client and types](https://www.prisma.io/docs/guides/turborepo#24-export-the-prisma-client-and-types)
* [3\. Import the `database` package in the web app](https://www.prisma.io/docs/guides/turborepo#3-import-the-database-package-in-the-web-app)
* [4\. Configure task dependencies in Turborepo](https://www.prisma.io/docs/guides/turborepo#4-configure-task-dependencies-in-turborepo)
* [5\. Run the project in development](https://www.prisma.io/docs/guides/turborepo#5-run-the-project-in-development)
* [Next Steps](https://www.prisma.io/docs/guides/turborepo#next-steps)
* [More Info](https://www.prisma.io/docs/guides/turborepo#more-info)
---
# How to use Prisma ORM in a pnpm workspaces monorepo | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#__docusaurus_skipToContent_fallback)
On this page
Prisma is a powerful ORM for managing your database, and when combined with [pnpm Workspaces](https://pnpm.io/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:[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#what-youll-learn "Direct link to 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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#1-prepare-your-project-and-configure-pnpm-workspaces "Direct link to 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-monorepocd my-monorepopnpm 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`:
pnpm-workspace.yaml
packages: - "apps/*" - "packages/*"catalogs: prisma: prisma: latest
note
The `catalogs` help you pin a certain version of prisma across your repositories. You can learn more about them [here](https://pnpm.io/catalogs)
. _Explictly_ pin the lastest version of [prisma](https://www.npmjs.com/package/prisma)
in the `pnpm-workspace.yaml` file. At the time of writing, this is version `6.3.1`.
Finally, create directories for your applications and shared packages:
mkdir appsmkdir -p packages/database
2\. Setup the shared database package[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#2-setup-the-shared-database-package "Direct link to 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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#21-initialize-the-package-and-install-dependencies "Direct link to 2.1. Initialize the package and install dependencies")
Navigate to the `packages/database` directory and initialize a new package:
cd packages/databasepnpm init
Add Prisma as a development dependency in your `package.json` using the pinned `catalog`:
database/package.json
"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
info
This guide uses [Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/getting-started)
. If you plan to use a different database, you can omit the [@prisma/extension-accelerate package](https://www.npmjs.com/package/@prisma/extension-accelerate/)
.
Initalize a `tsconfig.json` file for your `database` package:
pnpm tsc --init
### 2.2. Setup Prisma ORM in your database package[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#22-setup-prisma-orm-in-your-database-package "Direct link to 2.2. Setup Prisma ORM in your database package")
Initialize Prisma ORM with an instance of [Prisma Postgres](https://www.prisma.io/docs/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.
info
We're going to be using [Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/getting-started)
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 a `schema.prisma` file for your database models.
* Creates a `.env` file with your `DATABASE_URL` (e.g., for Prisma Postgres it should have something similar to `DATABASE_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](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
to generate the Prisma Client. This ensures that generated types are resolved correctly:
prisma/schema.prisma
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:
database/package.json
{ "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" }}
info
If you're not using [Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/getting-started)
for your database, exclude the `--no-engine` flag from the `db:generate` script.
Use [Prisma Migrate](https://www.prisma.io/docs/orm/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:
database/client.ts
import { PrismaClient } from "./generated/client";import { withAccelerate } from "@prisma/extension-accelerate";// Instantiate the extended Prisma client to infer its typeconst extendedPrisma = new PrismaClient().$extends(withAccelerate());type ExtendedPrismaClient = typeof extendedPrisma;// Use globalThis for broader environment compatibilityconst globalForPrisma = globalThis as typeof globalThis & { prisma?: ExtendedPrismaClient;};// Named export with global memoizationexport const prisma: ExtendedPrismaClient = globalForPrisma.prisma ?? extendedPrisma;if (process.env.NODE_ENV !== "production") { globalForPrisma.prisma = prisma;}
info
If you're not using [Prisma Postgres](https://www.prisma.io/docs/postgres/introduction/getting-started)
for your database, exclude the `import { withAccelerate }` line and `.$extends(withAccelerate())` from the line following it.
Then, create an `index.ts` file to re-export the instance of Prisma Client and all generated types:
database/index.ts
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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#3-set-up-and-integrate-your-frontend-application "Direct link to 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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#31-bootstrap-a-nextjs-application "Direct link to 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
important
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:
web/package.json
"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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#32-integrate-the-shared-database-package-in-your-app-code "Direct link to 32-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:
app/page.tsx
import { prisma } from "database";export default async function Home() { const user = await prisma.user.findFirst({ select: { name: true } }) return (
{user?.name &&
Hello from {user.name}
} {!user?.name &&
No user has been added to the database yet.
}
);}
This code demonstrates importing and using the shared Prisma Client to query your `User` model.
### 3.3. Add helper scripts and run your application[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#33-add-helper-scripts-and-run-your-application "Direct link to 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[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#34-run-your-application "Direct link to 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`](http://localhost:3000/)
to see your app in action.
### 3.5. (Optional) Add data to your database using Prisma Studio[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#35-optional-add-data-to-your-database-using-prisma-studio "Direct link to 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](https://www.prisma.io/docs/orm/tools/prisma-studio)
in [`http://localhost:5555`](http://localhost:5555/)
to interact with your database and add data to it.
Next Steps[](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#next-steps "Direct link to 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](https://www.prisma.io/docs/guides/turborepo)
guide.
Stay connected with Prisma
--------------------------
Continue your Prisma journey by connecting with [our active community](https://www.prisma.io/community)
. Stay informed, get involved, and collaborate with other developers:
* [Follow us on X](https://pris.ly/x?utm_source=docs&utm_medium=generated_text_cta)
for announcements, live events and useful tips.
* [Join our Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
to ask questions, talk to the community, and get active support through conversations.
* [Subscribe on YouTube](https://pris.ly/youtube?utm_source=docs&utm_medium=generated_text_cta)
for tutorials, demos, and streams.
* [Engage on GitHub](https://pris.ly/github?utm_source=docs&utm_medium=generated_text_cta)
by starring the repository, reporting issues, or contributing to an issue.
We genuinely value your involvement and look forward to having you as part of our community!
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/guides/use-prisma-in-pnpm-workspaces%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/guides/use-prisma-in-pnpm-workspaces%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/guides/use-prisma-in-pnpm-workspaces%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/800-guides/140-use-prisma-in-pnpm-workspaces.mdx)
* [What you'll learn:](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#what-youll-learn)
* [1\. Prepare your project and configure pnpm workspaces](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#1-prepare-your-project-and-configure-pnpm-workspaces)
* [2\. Setup the shared database package](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#2-setup-the-shared-database-package)
* [2.1. Initialize the package and install dependencies](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#21-initialize-the-package-and-install-dependencies)
* [2.2. Setup Prisma ORM in your database package](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#22-setup-prisma-orm-in-your-database-package)
* [3\. Set up and integrate your frontend application](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#3-set-up-and-integrate-your-frontend-application)
* [3.1. Bootstrap a Next.js application](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#31-bootstrap-a-nextjs-application)
* [3.2. Integrate the shared `database` package in your app code](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#32-integrate-the-shared-database-package-in-your-app-code)
* [3.3. Add helper scripts and run your application](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#33-add-helper-scripts-and-run-your-application)
* [3.4. Run your application](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#34-run-your-application)
* [3.5. (Optional) Add data to your database using Prisma Studio](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#35-optional-add-data-to-your-database-using-prisma-studio)
* [Next Steps](https://www.prisma.io/docs/guides/use-prisma-in-pnpm-workspaces#next-steps)
---
# Optimize: Known limitations | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize/known-limitations#__docusaurus_skipToContent_fallback)
On this page
Below are the known limitations when using Prisma Optimize. If you are aware of any limitations that are missing, please let us know on the `#help-and-questions` channel in our community [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=intro_text)
.
Query limit on a recording session[](https://www.prisma.io/docs/optimize/known-limitations#query-limit-on-a-recording-session "Direct link to Query limit on a recording session")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Each [recording session](https://www.prisma.io/docs/postgres/query-optimization/recordings)
can contain a maximum of 10,000 queries. Once this limit is reached, the recording session will end.
Recording limit per workspace[](https://www.prisma.io/docs/optimize/known-limitations#recording-limit-per-workspace "Direct link to Recording limit per workspace")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Each [workspace](https://www.prisma.io/docs/platform/about#workspace)
can contain a maximum of 100 [recordings](https://www.prisma.io/docs/postgres/query-optimization/recordings)
.
Scope and constraints for the Prisma AI[](https://www.prisma.io/docs/optimize/known-limitations#scope-and-constraints-for-the-prisma-ai "Direct link to Scope and constraints for the Prisma AI")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
While [Prisma AI](https://www.prisma.io/docs/postgres/query-optimization/prisma-ai)
can provide helpful guidance to implement a [recommendation](https://www.prisma.io/docs/postgres/query-optimization/recommendations)
, there are some important limitations to keep in mind:
* **Information and accuracy**: The AI provides advice based on a broad, general knowledge base and does not have direct access to Prisma ORM documentation. This may occasionally result in inaccuracies or outdated information.
* **Limited context and adaptation**: The AI does not persist conversations or learn from previous interactions. Its responses are generalized and may not always address the specific needs of advanced users.
* **Static knowledge and scope**: The AI's knowledge is static and may not include recent updates or best practices after a certain date. It provides advice only within the context of Prisma ORM and cannot modify or execute code, nor interact directly with user environments.
Using Prisma Accelerate client extension with the Optimize extension[](https://www.prisma.io/docs/optimize/known-limitations#using-prisma-accelerate-client-extension-with-the-optimize-extension "Direct link to Using Prisma Accelerate client extension with the Optimize extension")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
When using the [Optimize client extension](https://www.npmjs.com/package/@prisma/extension-optimize)
with the [Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate)
, ensure the Accelerate client extension is added last to your extended `PrismaClient`. This allows cacheable operations to be received by Optimize.
const prisma = new PrismaClient() .$extends( withOptimize({ apiKey: process.env.OPTIMIZE_API_KEY, }), ) .$extends(withAccelerate());
### SQL references in MongoDB recommendations[](https://www.prisma.io/docs/optimize/known-limitations#sql-references-in-mongodb-recommendations "Direct link to SQL references in MongoDB recommendations")
Prisma Optimize provides helpful recommendations for MongoDB users, though some explanations from [Prisma AI](https://www.prisma.io/docs/postgres/query-optimization/prisma-ai)
may reference SQL-specific concepts. However, the [recommendations](https://www.prisma.io/docs/postgres/query-optimization/recommendations)
remain useful and applicable to MongoDB environments.
### Raw query visibility in MongoDB[](https://www.prisma.io/docs/optimize/known-limitations#raw-query-visibility-in-mongodb "Direct link to Raw query visibility in MongoDB")
Raw queries are visible in MongoDB, though the parameters passed to them are not displayed.
Driver adapter compatibility[](https://www.prisma.io/docs/optimize/known-limitations#driver-adapter-compatibility "Direct link to Driver adapter compatibility")
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Prisma Optimize is not yet compatible with [driver adapters](https://www.prisma.io/docs/orm/overview/databases/database-drivers#driver-adapters)
. However, as a workaround, you can run your queries locally using the regular Prisma Client along with Prisma Optimize to inspect and improve query performance.
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/optimize/known-limitations%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/optimize/known-limitations%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/optimize/known-limitations%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/700-optimize/700-known-limitations.mdx)
* [Query limit on a recording session](https://www.prisma.io/docs/optimize/known-limitations#query-limit-on-a-recording-session)
* [Recording limit per workspace](https://www.prisma.io/docs/optimize/known-limitations#recording-limit-per-workspace)
* [Scope and constraints for the Prisma AI](https://www.prisma.io/docs/optimize/known-limitations#scope-and-constraints-for-the-prisma-ai)
* [Using Prisma Accelerate client extension with the Optimize extension](https://www.prisma.io/docs/optimize/known-limitations#using-prisma-accelerate-client-extension-with-the-optimize-extension)
* [SQL references in MongoDB recommendations](https://www.prisma.io/docs/optimize/known-limitations#sql-references-in-mongodb-recommendations)
* [Raw query visibility in MongoDB](https://www.prisma.io/docs/optimize/known-limitations#raw-query-visibility-in-mongodb)
* [Driver adapter compatibility](https://www.prisma.io/docs/optimize/known-limitations#driver-adapter-compatibility)
---
# Optimize: Prisma AI | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize/prisma-ai#__docusaurus_skipToContent_fallback)
Prisma AI enables you to ask follow-up questions on a provided [recommendation](https://www.prisma.io/docs/postgres/query-optimization/recommendations)
for additional clarity. Learn more about [Prisma AI here](https://www.prisma.io/docs/postgres/query-optimization/prisma-ai)
.
---
# Getting started with Prisma Optimize | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize/getting-started#__docusaurus_skipToContent_fallback)
On this page
Prerequisites[](https://www.prisma.io/docs/optimize/getting-started#prerequisites "Direct link to Prerequisites")
-------------------------------------------------------------------------------------------------------------------
Before you begin with Prisma Optimize, ensure you have the following:
* A .
* A project using [Prisma Client](https://www.prisma.io/docs/orm/prisma-client)
version `5.0.0` or higher (we recommend using the latest version).
* A PostgreSQL, MySQL/MariaDB, CockroachDB, or MS SQL Server database.
note
Prisma Optimize is intended for use in local environments. Learn more in the [FAQ](https://www.prisma.io/docs/postgres/more/faq#can-i-enable-query-optimizations-for-prisma-postgres-in-production)
.
1\. Launch Optimize[](https://www.prisma.io/docs/optimize/getting-started#1-launch-optimize "Direct link to 1. Launch Optimize")
----------------------------------------------------------------------------------------------------------------------------------
1. Log in to your .
2. [Follow the instructions](https://www.prisma.io/docs/platform/about#accessing-the-optimize-dashboard)
to access and launch Prisma Optimize.
2\. Add Optimize to your application[](https://www.prisma.io/docs/optimize/getting-started#2-add-optimize-to-your-application "Direct link to 2. Add Optimize to your application")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### 2.1. Install the Optimize Prisma Client extension[](https://www.prisma.io/docs/optimize/getting-started#21-install-the-optimize-prisma-client-extension "Direct link to 2.1. Install the Optimize Prisma Client extension")
Install Prisma Client and the Optimize extension:
npm install @prisma/client@latest @prisma/extension-optimize
Enabling tracing in older versions of Prisma ORM
For versions of Prisma ORM between `4.2.0` and `6.1.0`, you need to enable the `tracing` preview feature in your Prisma schema file.
generator client { provider = "prisma-client-js" previewFeatures = ["tracing"]}
### 2.2. Add the Optimize API Key to your `.env` file[](https://www.prisma.io/docs/optimize/getting-started#22-add-the-optimize-api-key-to-your-env-file "Direct link to 22-add-the-optimize-api-key-to-your-env-file")
[Generate a Prisma Optimize API key](https://www.prisma.io/docs/platform/about#generating-an-optimize-api-key)
and add it to your `.env` file:
OPTIMIZE_API_KEY="YOUR_OPTIMIZE_API_KEY"
### 2.3. Extend your Prisma Client instance[](https://www.prisma.io/docs/optimize/getting-started#23-extend-your-prisma-client-instance "Direct link to 2.3. Extend your Prisma Client instance")
Extend your existing Prisma Client instance with the Optimize extension:
import { PrismaClient } from "@prisma/client";import { withOptimize } from "@prisma/extension-optimize";const prisma = new PrismaClient().$extends( withOptimize({ apiKey: process.env.OPTIMIZE_API_KEY }),);
#### Using the Optimize extension with other extensions or middleware[](https://www.prisma.io/docs/optimize/getting-started#using-the-optimize-extension-with-other-extensions-or-middleware "Direct link to Using the Optimize extension with other extensions or middleware")
Since [extensions are applied one after another](https://www.prisma.io/docs/orm/prisma-client/client-extensions#conflicts-in-combined-extensions)
, make sure you apply them in the correct order. Extensions cannot share behavior and the last extension applied takes precedence.
If you are using [Prisma Accelerate](https://www.prisma.io/docs/accelerate)
in your application, make sure you apply it _after_ the Optimize extension. For example:
const prisma = new PrismaClient().$extends(withOptimize()).$extends(withAccelerate())
If you are using [Prisma Middleware](https://www.prisma.io/docs/orm/prisma-client/client-extensions/middleware)
in your application, make sure they are added before any Prisma Client extensions (like Optimize). For example:
const prisma = new PrismaClient().$use(middleware).$extends(withOptimize())
### 2.5. Use Prisma Optimize to generate insights[](https://www.prisma.io/docs/optimize/getting-started#25-use-prisma-optimize-to-generate-insights "Direct link to 2.5. Use Prisma Optimize to generate insights")
Follow these steps to start generating query insights with Prisma Optimize:
1. In the Optimize dashboard, click the **Start recording** button, then run your app and execute some Prisma queries while recording is active.
2. After your app runs and generates insights based on the executed Prisma queries, click the **Stop recording** button.
3. Explore [individual query details](https://www.prisma.io/docs/postgres/query-optimization/recordings#data-captured-in-a-recording-session)
by clicking on them, and check the **Recommendations** tab for any suggested improvements to enhance query performance.
info
Use [Prisma AI](https://www.prisma.io/docs/postgres/query-optimization/prisma-ai)
to understand recommendations and apply them within your Prisma model context.
For a hands-on learning experience, try out the [step-by-step example](https://github.com/prisma/prisma-examples/tree/latest/optimize/starter)
.
Need help?[](https://www.prisma.io/docs/optimize/getting-started#need-help "Direct link to Need help?")
---------------------------------------------------------------------------------------------------------
If you need assistance, reach out in the `#help-and-questions` channel on our [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=generated_text_cta)
, or connect with [our community](https://www.prisma.io/community)
to see how others are using Optimize.
Open in
Copy as Markdown
[Open in Claude](https://claude.ai/new?q=Read%20https://prisma.io/docs/optimize/getting-started%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in ChatGPT](https://chat.openai.com/?q=Read%20https://prisma.io/docs/optimize/getting-started%20so%20I%20can%20ask%20questions%20about%20it.)
[Open in T3.chat](https://www.t3.chat/new?q=Read%20https://prisma.io/docs/optimize/getting-started%20so%20I%20can%20ask%20questions%20about%20it.)
[Edit in GitHub](https://github.com/prisma/docs/tree/main/content/700-optimize/200-getting-started.mdx)
* [Prerequisites](https://www.prisma.io/docs/optimize/getting-started#prerequisites)
* [1\. Launch Optimize](https://www.prisma.io/docs/optimize/getting-started#1-launch-optimize)
* [2\. Add Optimize to your application](https://www.prisma.io/docs/optimize/getting-started#2-add-optimize-to-your-application)
* [2.1. Install the Optimize Prisma Client extension](https://www.prisma.io/docs/optimize/getting-started#21-install-the-optimize-prisma-client-extension)
* [2.2. Add the Optimize API Key to your `.env` file](https://www.prisma.io/docs/optimize/getting-started#22-add-the-optimize-api-key-to-your-env-file)
* [2.3. Extend your Prisma Client instance](https://www.prisma.io/docs/optimize/getting-started#23-extend-your-prisma-client-instance)
* [2.5. Use Prisma Optimize to generate insights](https://www.prisma.io/docs/optimize/getting-started#25-use-prisma-optimize-to-generate-insights)
* [Need help?](https://www.prisma.io/docs/optimize/getting-started#need-help)
---
# Optimize: Recordings | Prisma Documentation
[Skip to main content](https://www.prisma.io/docs/optimize/recordings#__docusaurus_skipToContent_fallback)
The recordings feature helps developers debug and isolate sets of queries into distinct sessions, known as recordings. This targeted approach enables precise performance analysis and optimization by preventing the mixing of queries from different applications or test rounds, leading to clearer insights and more effective debugging.
Learn more about the [Optimize recordings here](https://www.prisma.io/docs/postgres/query-optimization/recommendations)
.
---