# 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. ![GitHub Actions comment](https://www.prisma.io/docs/assets/images/github-comment-bd0b8c699ab8f82f3e821f51d61d6d80.png) 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: ![A diagram showing changes by two separate developers converging in a single migration history.](https://www.prisma.io/docs/assets/images/migrate-team-dev-67fee0857c7f229cc4fb06010314e229.png) 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: ![App displaying data by querying two separate database instances](https://www.prisma.io/docs/assets/images/multi-client-app-demo-92e2c6e469cc4600ffb35af919f265b1.png) 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

  1. Alice
  2. 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) => (
  1. {user.name}
  2. ))}
);} 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