# Prisma Documentation - Full Content Feed This file contains the complete Prisma documentation in machine-readable format. Includes the current docs plus legacy v6 ORM pages. --- # Choose a setup path (/docs/getting-started) Location: Choose a setup path Prisma gives you a few good starting points depending on whether you need a database, already have one, or want the smallest possible local setup. Choose your path [#choose-your-path] Start a new project [#start-a-new-project] * [Quickstart with Prisma Postgres](/prisma-orm/quickstart/prisma-postgres) for the fastest end-to-end path with a managed PostgreSQL database * [Quickstart with PostgreSQL](/prisma-orm/quickstart/postgresql) if you want to work with PostgreSQL * [Quickstart with SQLite](/prisma-orm/quickstart/sqlite) for a lightweight local setup * [Quickstart with MySQL](/prisma-orm/quickstart/mysql) if your application uses MySQL * [Quickstart with MongoDB](/prisma-orm/quickstart/mongodb) if your application uses MongoDB Add Prisma to an existing project [#add-prisma-to-an-existing-project] * [Add Prisma ORM to an existing PostgreSQL project](/prisma-orm/add-to-existing-project/postgresql) * [Add Prisma ORM to an existing MySQL project](/prisma-orm/add-to-existing-project/mysql) * [Add Prisma ORM to an existing SQLite project](/prisma-orm/add-to-existing-project/sqlite) * [Add Prisma ORM to an existing MongoDB project](/prisma-orm/add-to-existing-project/mongodb) * [Add Prisma ORM to an existing Prisma Postgres project](/prisma-orm/add-to-existing-project/prisma-postgres) What you will do [#what-you-will-do] No matter which guide you choose, the flow is usually the same: 1. Define a database connection and data model in your [Prisma schema](/orm/prisma-schema/overview). 2. Install Prisma CLI and [Prisma Client](/orm/prisma-client). 3. Run `prisma generate` to create a type-safe client for your schema. 4. Create or introspect your database, then start sending queries from your application. Next steps [#next-steps] After setup, these pages are usually the next ones people need: * [Prisma Client overview](/orm/prisma-client) * [Generating Prisma Client](/orm/prisma-client/setup-and-configuration/generating-prisma-client) * [Prisma Migrate getting started](/orm/prisma-migrate/getting-started) * [Prisma schema overview](/orm/prisma-schema/overview) If you want the fastest path [#if-you-want-the-fastest-path] * [Quickstart with Prisma Postgres](/prisma-orm/quickstart/prisma-postgres) if you want Prisma to provision the database layer for you * [Open Prisma Studio](/studio/getting-started) if you want to inspect and edit data visually once your app is running * [Review pricing](https://www.prisma.io/pricing) if you're evaluating Prisma Postgres or other paid workflows for a team ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows - [`Management API`](https://www.prisma.io/docs/management-api): Programmatically manage your Prisma Postgres databases, projects, and workspaces with the Management API # Introduction to Prisma (/docs) [**Prisma ORM**](/orm) is an open-source ORM that provides fast, type-safe access to Postgres, MySQL, SQLite, and other databases, and runs smoothly across Node.js, Bun, and Deno. #### npm ```bash npx prisma init ``` #### pnpm ```bash pnpm dlx prisma init ``` #### yarn ```bash yarn dlx prisma init ``` #### bun ```bash bunx --bun prisma init ``` [**Prisma Postgres**](/postgres) is a fully managed PostgreSQL database that scales to zero, integrates with [Prisma ORM](/orm) and [Prisma Studio](/studio), and includes a [generous free tier](https://www.prisma.io/pricing). #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` - [Use Prisma Postgres](/prisma-orm/quickstart/prisma-postgres): **Need a database?** Get started with your favorite framework and Prisma Postgres. - [Bring your own database](/prisma-postgres/quickstart/prisma-orm): **Already have a database?** Use Prisma ORM for a type-safe developer experience and automated migrations. # Caching queries (/docs/accelerate/caching) Location: Accelerate > Caching queries Prisma Accelerate provides global caching for read queries using TTL, Stale-While-Revalidate (SWR), or a combination of both. It's included as part of Prisma Postgres, but can also be used with your own database by enabling Accelerate in the [Prisma Data Platform](https://console.prisma.io?utm_source=docs) and [configuring it with your database](/accelerate/getting-started). ## Related pages - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate - [`Getting started`](https://www.prisma.io/docs/accelerate/getting-started): Learn how to get up and running with Prisma Accelerate # Compare Accelerate (/docs/accelerate/compare) Location: Accelerate > Compare Accelerate Prisma Accelerate supports products that serve a global audience, with a global caching system and connection pool that spans multiple regions, providing consistent access to data with low latency no matter where your user (or your database) is located in the world. The managed connection pool is designed to support serverless infrastructure, capable of handling high volumes of connections and adapting to traffic spikes with ease. Explore how Prisma Accelerate compares to other global cache and connection pool solutions on the market, and discover what sets it apart. What makes Accelerate unique? [#what-makes-accelerate-unique] Prisma Accelerate is chosen and loved by many for a number of key reasons which make Accelerate unique: * [**Query-Level policies**](/accelerate/compare#accelerate-global-cache): Accelerate is the only solution that offers query-level cache policies, allowing you to control the cache strategy for each query specifically. It is common to have some values that need to be cached for a long time, others that need caching for a short time, and some that should not be cached at all. With Accelerate you can do this, and even set different cache strategies per query. * [**Global by default**](/accelerate/compare#accelerate-global-cache): Accelerate is globally distributed by default. You never need to worry about where a user is located with respect to your database location. * [**Fully managed**](/accelerate/compare#management): You don't need to manage a server or worry about uptime. Accelerate is fully managed for you. * [**Auto-scaling**](/accelerate/compare#performance): Accelerate automatically adjusts resources to match workload demands, providing fast and consistent performance during traffic spikes. Accelerate global cache [#accelerate-global-cache] Prisma Accelerate offers a powerful global cache, so you can serve data to your users at the edge — the closest point to where the users are located — no matter where your database is hosted. This not only speeds up the experience for users, but also reduces read load on your database as well by avoiding roundtrips. | | Accelerate | Hyperdrive | PlanetScale Boost | | ----------------------------------- | ---------- | ---------- | ----------------- | | **Fully Managed** | ✅ | ✅ | ✅ | | **Globally distributed edge infra** | ✅ | ✅ | ✅ | | **Control cache policy from code** | ✅ | ❌ | ❌ | | **Query-level cache policies** | ✅ | ❌ | ❌ | | **Postgres compatible** | ✅ | ✅ | ❌ | | **MySQL compatible** | ✅ | ❌ | ✅ | | **MongoDB compatible** | ✅ | ❌ | ❌ | | **Automatic cache updates** | ❌ | ❌ | ✅ | **Why are these important?** * Since Accelerate extends the Prisma client, you can control caching policies directly from your codebase with just an extra line of code. Integration is seamless. Here is an example using the stale-while-revalidating caching strategy: ```jsx await prisma.user.findMany({ cacheStrategy: { swr: 60, }, }); ``` * Query level cache policies are critical for serious applications, so that you can control which queries are cached, and the characteristics of the policy. You may want certain data in your app to be cached for several days, other data to be cached for a just a few minutes, and other data to be not cached at all. This is only possible with Prisma Accelerate. * Automatic cache updates means that the cache is automatically updated when a change in the database occurs. With Accelerate, you are in control of how the cache is invalidated, using [various caching strategies](/accelerate/caching). Accelerate connection pool [#accelerate-connection-pool] Prisma Accelerate includes a globally hosted connection pooler, which allows you to handle peak loads without any problem. Using a connection pool is important especially for serverless infrastructure, which by nature is not able to control connection volume to the database on its own. Prisma Accelerate offers a fully managed, globally colocated option, which auto scales to support any workload. Management [#management] | | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | | ------------------------------ | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | | **Fully managed** | ✅ | ❌ | ❌ | 🟠 | ✅ | ❌ | ✅ | | **Globally distributed** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | **Integrated with ORM client** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Authenticate with API key** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Redundancy** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | **Why are these important?** * If you decide to manage a connection pooler yourself (eg. using pgbouncer or pgcat) you will also be responsible for managing its uptime. If the server crashes, your application may be down until you recover it. Accelerate, as a fully managed solution will be recovered for you transparently, in the unlikely case of any infrastructure issue. * The hosted pgbouncer option on Digital Ocean is semi-managed, you will need to set it up in your Digital Ocean account, and ensure it is running smoothly at all times. * Authenticating with an API key can be a helpful security measure, allowing you to decouple database credentials from application secrets. Easily rotate API keys as often as you like, without needing any credential changes in your database * Redundancy is helpful in the unlikely scenario that your connection pool service goes down. With Accelerate, it is automatically and seamlessly handed over to another server and recovered without any interruption. Performance [#performance] | | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | | ------------------------------- | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | | **Auto scaling** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Globally distributed** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | **Optimized queries over HTTP** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | **Isolated compute** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | **Why are these important?** * Accelerate will automatically scale up and down to suit your application workload, meaning you'll never run out of compute resource. Additionally, this provides important redundancy to protect against any single compute instance failing — in the unlikely event of an instance going down, Accelerate will automatically spawn a new instance. * Cross-region TCP handshakes between the application server and PgBouncer or the database are costly and time-consuming. If connections are reused only at the PgBouncer layer, the TCP handshake and connection setup still consume unnecessary time on every single request, which undermines the efficiency of connection reuse. Prisma Accelerate improves this by leveraging HTTP, which is more efficient for connection management. It reduces the overhead associated with TCP handshakes, resulting in faster, more responsive interactions between your application and the database. * Never worry about 'noisy neighbors' with isolated compute resources. Other customers never impact on your own performance. Database Support [#database-support] | | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | | --------------- | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | | **PostgreSQL** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **MySQL** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PlanetScale** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **CockroachDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **MongoDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate - [`Getting started`](https://www.prisma.io/docs/accelerate/getting-started): Learn how to get up and running with Prisma Accelerate # Connection Pooling (/docs/accelerate/connection-pooling) Location: Accelerate > Connection Pooling Accelerate provides built-in connection pooling to efficiently manage database connections. It's included as part of [Prisma Postgres](/postgres), but you can also use it with your own database by enabling Accelerate in the [Prisma Data Platform](https://console.prisma.io?utm_source=docs) and [connecting it to your database](/accelerate/getting-started). This page has moved, connection pooling in Prisma Accelerate is now documented in the [Prisma Postgres section](/postgres/database/connection-pooling). ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate - [`Getting started`](https://www.prisma.io/docs/accelerate/getting-started): Learn how to get up and running with Prisma Accelerate # Evaluating (/docs/accelerate/evaluating) Location: Accelerate > Evaluating Prisma Accelerate optimizes database interactions through advanced connection pooling and global edge caching. Its connection pooler is available in 16 regions and helps applications load-balance and scale database requests based on demand. Considering the information above, we recommend evaluating Accelerate with high volume to see it perform under load. How Accelerate's connection pool optimizes performance under load [#how-accelerates-connection-pool-optimizes-performance-under-load] Prisma Accelerate employs a dynamic, serverless connection pooling infrastructure. When a request is made, a connection pool is quickly provisioned for the project in the region assigned while configuring Prisma Accelerate. This connection pool remains active, serving many additional requests while reusing established database connections. The connection pool will disconnect after a period of inactivity, so it’s important to evaluate Prisma Accelerate with a consistent stream of traffic. **Key Benefits:** * **Optimized Query Performance:** The serverless connection pooler adapts to the query load, ensuring the database connections are managed efficiently during peak demand. > Prisma Accelerate’s connection pooler cannot improve the performance of queries in the database. In scenarios where query performance is an issue, we recommend optimizing the Prisma query, applying indexes, or utilizing Accelerate’s edge caching. * **Maximize Connection Reuse:** Executing a consistent volume of queries helps maintain active instances of Accelerate connection poolers. This increases connection reuse, ensuring faster response times for subsequent queries. By understanding and harnessing this mechanism, you can ensure that your database queries perform consistently and efficiently at scale. Evaluating Prisma Accelerate connection pooling performance [#evaluating-prisma-accelerate-connection-pooling-performance] Below you will find an example of how to evaluate Prisma Accelerate using a sample model: ```prisma model Notes { id Int @id @default(autoincrement()) title String createdAt DateTime @default(now()) updatedAt DateTime? @updatedAt } ``` ```typescript import { PrismaClient } from "@prisma/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient().$extends(withAccelerate()); function calculateStatistics(numbers: number[]): { average: number; p50: number; p75: number; p99: number; } { if (numbers.length === 0) { throw new Error("The input array is empty."); } // Sort the array in ascending order numbers.sort((a, b) => a - b); const sum = numbers.reduce((acc, num) => acc + num, 0); const count = numbers.length; const average = sum / count; const p50 = getPercentile(numbers, 50); const p75 = getPercentile(numbers, 75); const p99 = getPercentile(numbers, 99); return { average, p50, p75, p99 }; } function getPercentile(numbers: number[], percentile: number): number { if (percentile <= 0 || percentile >= 100) { throw new Error("Percentile must be between 0 and 100."); } const index = (percentile / 100) * (numbers.length - 1); if (Number.isInteger(index)) { // If the index is an integer, return the corresponding value return numbers[index]; } else { // If the index is not an integer, interpolate between two adjacent values const lowerIndex = Math.floor(index); const upperIndex = Math.ceil(index); const lowerValue = numbers[lowerIndex]; const upperValue = numbers[upperIndex]; const interpolationFactor = index - lowerIndex; return lowerValue + (upperValue - lowerValue) * interpolationFactor; } } async function main() { const timings = []; // fire a query before going to the loop await prisma.notes.findMany({ take: 20, }); // we recommend evaluating Prisma Accelerate with a large loop const LOOP_LENGTH = 10000; for (let i = 0; i < LOOP_LENGTH; i++) { const start = Date.now(); await prisma.notes.findMany({ take: 20, }); timings.push(Date.now() - start); } const statistics = calculateStatistics(timings); console.log("Average:", statistics.average); console.log("P50:", statistics.p50); console.log("P75:", statistics.p75); console.log("P99:", statistics.p99); } main() .then(async () => { await prisma.$disconnect(); }) .catch((e) => { await prisma.$disconnect(); process.exit(1); }); ``` Evaluating Prisma Accelerate caching performance [#evaluating-prisma-accelerate-caching-performance] Prisma Accelerate’s edge cache is also optimized for a high volume of queries. The cache automatically optimizes for repeated queries. As a result, the cache hit rate will increase as the query frequency does. Adding a query result to the cache is also non-blocking, so a short burst of queries might not utilize the cache or a sustained load. To evaluate Accelerate’s edge caching, you can modify the above script with the below: ```typescript import { PrismaClient } from "@prisma/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient().$extends(withAccelerate()); function calculateStatistics(numbers: number[]): { average: number; p50: number; p75: number; p99: number; } { if (numbers.length === 0) { throw new Error("The input array is empty."); } // Sort the array in ascending order numbers.sort((a, b) => a - b); const sum = numbers.reduce((acc, num) => acc + num, 0); const count = numbers.length; const average = sum / count; const p50 = getPercentile(numbers, 50); const p75 = getPercentile(numbers, 75); const p99 = getPercentile(numbers, 99); return { average, p50, p75, p99 }; } function getPercentile(numbers: number[], percentile: number): number { if (percentile <= 0 || percentile >= 100) { throw new Error("Percentile must be between 0 and 100."); } const index = (percentile / 100) * (numbers.length - 1); if (Number.isInteger(index)) { // If the index is an integer, return the corresponding value return numbers[index]; } else { // If the index is not an integer, interpolate between two adjacent values const lowerIndex = Math.floor(index); const upperIndex = Math.ceil(index); const lowerValue = numbers[lowerIndex]; const upperValue = numbers[upperIndex]; const interpolationFactor = index - lowerIndex; return lowerValue + (upperValue - lowerValue) * interpolationFactor; } } async function main() { const timings = []; // fire a query before going to the loop await prisma.notes.findMany({ take: 20, cacheStrategy: { ttl: 30, }, }); // we recommend evaluating Prisma Accelerate with a large loop const LOOP_LENGTH = 10000; for (let i = 0; i < LOOP_LENGTH; i++) { const start = Date.now(); await prisma.notes.findMany({ take: 20, cacheStrategy: { ttl: 30, }, }); timings.push(Date.now() - start); } const statistics = calculateStatistics(timings); console.log("Average:", statistics.average); console.log("P50:", statistics.p50); console.log("P75:", statistics.p75); console.log("P99:", statistics.p99); } main() .then(async () => { await prisma.$disconnect(); }) .catch((e) => { await prisma.$disconnect(); process.exit(1); }); ``` ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate - [`Getting started`](https://www.prisma.io/docs/accelerate/getting-started): Learn how to get up and running with Prisma Accelerate # Examples (/docs/accelerate/examples) Location: Accelerate > Examples Here is a list of ready-to-run example projects that demonstrate how to use Prisma Accelerate: | Demo | Description | | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | [`nextjs-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nextjs-starter) | A Next.js project using Prisma Accelerate's caching and connection pooling | | [`svelte-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/svelte-starter) | A SvelteKit project using Prisma Accelerate's caching and connection pooling | | [`solidstart-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/solidstart-starter) | A Solidstart project using Prisma Accelerate's caching and connection pooling | | [`remix-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/remix-starter) | A Remix project using Prisma Accelerate's caching and connection pooling | | [`nuxt-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nuxtjs-starter) | A Nuxt.js project using Prisma Accelerate's caching and connection pooling | | [`astro-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/astro-starter) | An Astro project using Prisma Accelerate's caching and connection pooling | | [`accelerate-hacker-news`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/accelerate-hacker-news) | A simple Hacker News clone built with Prisma Accelerate, demonstrating the use of on-demand cache invalidation | | [`prisma-accelerate-invalidation`](https://github.com/prisma/prisma-accelerate-invalidation) | An app demonstrating how long it takes to invalidate a cached query result using on-demand cache invalidation. | ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Getting started`](https://www.prisma.io/docs/accelerate/getting-started): Learn how to get up and running with Prisma Accelerate # Getting started (/docs/accelerate/getting-started) Location: Accelerate > Getting started Prerequisites [#prerequisites] To get started with Accelerate, you will need the following: * A [Prisma Data Platform account](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=accelerate) * A project that uses [Prisma Client](/orm/prisma-client/setup-and-configuration/introduction) `4.16.1` or higher. If your project is using interactive transactions, you need to use `5.1.1` or higher. (We always recommend using the latest version of Prisma.) * A hosted PostgreSQL, MySQL/MariaDB, PlanetScale, CockroachDB, or MongoDB database 1. Enable Accelerate [#1-enable-accelerate] Navigate to your Prisma Data Platform project, choose an environment, and enable Accelerate by providing your database connection string and selecting the region nearest your database. > [!NOTE] > If you require IP allowlisting or firewall configurations with trusted IP addresses, enable Static IP for enhanced security. Learn more on [how to enable static IP for Accelerate in the Platform Console](/accelerate/static-ip). 2. Add Accelerate to your application [#2-add-accelerate-to-your-application] 2.1. Update your database connection string [#21-update-your-database-connection-string] Once enabled, you'll be prompted to generate a connection string that you'll use to authenticate requests. Replace your direct database URL with your new Accelerate connection string. ```bash title=".env" # New Accelerate connection string with generated API_KEY DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" # Previous (direct) database connection string # DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" ``` Prisma Client reads the `prisma://` URL from `DATABASE_URL` at runtime, while Prisma CLI commands use the connection string defined in `prisma.config.ts`. Prisma Migrate and Introspection do not work with a `prisma://` connection string. In order to continue using these features add a new variable to the `.env` file named `DIRECT_DATABASE_URL` whose value is the direct database connection string: ```bash title=".env" DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" DIRECT_DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" # [!code ++] ``` Then point `prisma.config.ts` to the direct connection string: ```ts title="prisma.config.ts" showLineNumbers import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", datasource: { url: env("DIRECT_DATABASE_URL"), }, }); ``` Migrations and introspections will use the `directUrl` connection string rather than the one defined in `url` when this configuration is provided. > `directUrl` is useful for you to carry out migrations and introspections. However, you don't need `directUrl` to use Accelerate in your application. > [!NOTE] > If you are using Prisma with PostgreSQL, there is no need for `directUrl`, as Prisma Migrate and Introspection work with the `prisma+postgres://` connection string. 2.2. Install the Accelerate Prisma Client extension [#22-install-the-accelerate-prisma-client-extension] > [!NOTE] > 💡 Accelerate requires [Prisma Client](/orm/prisma-client/setup-and-configuration/introduction) version `4.16.1` or higher and [`@prisma/extension-accelerate`](https://www.npmjs.com/package/@prisma/extension-accelerate) version `1.0.0` or higher. > > 💡 Accelerate extension [`@prisma/extension-accelerate`](https://www.npmjs.com/package/@prisma/extension-accelerate) version `2.0.0` and above requires Node.js version `18` or higher. Install the latest version of Prisma Client and Accelerate Prisma Client extension #### npm ```bash npm install @prisma/client@latest @prisma/extension-accelerate ``` #### pnpm ```bash pnpm add @prisma/client@latest @prisma/extension-accelerate ``` #### yarn ```bash yarn add @prisma/client@latest @prisma/extension-accelerate ``` #### bun ```bash bun add @prisma/client@latest @prisma/extension-accelerate ``` 2.3. Generate Prisma Client for Accelerate [#23-generate-prisma-client-for-accelerate] If you're using Prisma version `5.2.0` or greater, Prisma Client will automatically determine how it should connect to the database depending on the protocol in the database connection string. If the connection string in the `DATABASE_URL` starts with `prisma://`, Prisma Client will try to connect to your database using Prisma Accelerate. When using Prisma Accelerate in long-running application servers, such as a server deployed on AWS EC2, you can generate the Prisma Client by executing the following command: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` When using Prisma Accelerate in a Serverless or an Edge application, we recommend you to run the following command to generate Prisma Client: #### npm ```bash npx prisma generate --no-engine ``` #### pnpm ```bash pnpm dlx prisma generate --no-engine ``` #### yarn ```bash yarn dlx prisma generate --no-engine ``` #### bun ```bash bunx --bun prisma generate --no-engine ``` The `--no-engine` flag prevents a Query Engine file from being included in the generated Prisma Client, this ensures the bundle size of your application remains small. > [!WARNING] > If your Prisma version is below `5.2.0`, generate Prisma Client with the `--accelerate` option: > > > > > #### npm > ```bash > npx prisma generate --accelerate > ``` > > > #### pnpm > ```bash > pnpm dlx prisma generate --accelerate > ``` > > > #### yarn > ```bash > yarn dlx prisma generate --accelerate > ``` > > > #### bun > ```bash > bunx --bun prisma generate --accelerate > ``` > > > > If your Prisma version is below `5.0.0`, generate Prisma Client with the `--data-proxy` option: > > > > > #### npm > ```bash > npx prisma generate --data-proxy > ``` > > > #### pnpm > ```bash > pnpm dlx prisma generate --data-proxy > ``` > > > #### yarn > ```bash > yarn dlx prisma generate --data-proxy > ``` > > > #### bun > ```bash > bunx --bun prisma generate --data-proxy > ``` > > 2.4. Extend your Prisma Client instance with the Accelerate extension [#24-extend-your-prisma-client-instance-with-the-accelerate-extension] Add the following to extend your existing Prisma Client instance with the Accelerate extension: ```ts import { PrismaClient } from "@prisma/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient({ accelerateUrl: process.env.DATABASE_URL, }).$extends(withAccelerate()); ``` If you are going to deploy to an edge runtime (like Cloudflare Workers, Vercel Edge Functions, Deno Deploy, or Supabase Edge Functions), use our edge client instead: ```ts import { PrismaClient } from "@prisma/client/edge"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient({ accelerateUrl: process.env.DATABASE_URL, }).$extends(withAccelerate()); ``` If VS Code does not recognize the `$extends` method, refer to [this section](/accelerate/more/faq#vs-code-does-not-recognize-the-extends-method) on how to resolve the issue. Using the Accelerate extension with other extensions [#using-the-accelerate-extension-with-other-extensions] Since [extensions are applied one after another](/orm/prisma-client/client-extensions#conflicts-in-combined-extensions), make sure you apply them in the correct order. Extensions cannot share behavior and the last extension applied takes precedence. If you are using [Query Insights](/query-insights) in your application, make sure you apply it *before* the Accelerate extension. For example: ```ts const prisma = new PrismaClient({ accelerateUrl: process.env.DATABASE_URL, }) .$extends(withOptimize()) .$extends(withAccelerate()); ``` 2.5. Use Accelerate in your database queries [#25-use-accelerate-in-your-database-queries] The `withAccelerate` extension primarily does two things: * Gives you access to the `cacheStrategy` field within each applicable model method that allows you to define a cache strategy per-query. * Routes all of your queries through a connection pooler. No cache strategy to only use connection pool [#no-cache-strategy-to-only-use-connection-pool] If you simply want to take advantage of Accelerate's connection pooling feature without applying a cache strategy, you may run your query the same way you would have without Accelerate. By enabling Accelerate and supplying the Accelerate connection string, your queries now use the connection pooler by default. > [!NOTE] > As of Prisma version `5.2.0` you can use Prisma Studio with the Accelerate connection string. Invalidate the cache and keep your cached query results up-to-date [#invalidate-the-cache-and-keep-your-cached-query-results-up-to-date] If your application requires real-time or near-real-time data, cache invalidation ensures that users see the most current data, even when using a large `ttl` (Time-To-Live) or `swr` (Stale-While-Revalidate) [cache strategy](/accelerate/caching). By invalidating your cache, you can bypass extended caching periods to show live data whenever it's needed. For example, if a dashboard displays customer information and a customer’s contact details change, cache invalidation allows you to refresh only that data instantly, ensuring support staff always see the latest information without waiting for the cache to expire. To invalidate a cached query result, you can add tags and then use the `$accelerate.invalidate` API. > [!NOTE] > On-demand cache invalidation is available with our paid plans. For more details, please see our [pricing](https://www.prisma.io/pricing#accelerate). To invalidate the query below: ```ts await prisma.user.findMany({ where: { email: { contains: "alice@prisma.io", }, }, cacheStrategy: { swr: 60, ttl: 60, tags: ["emails_with_alice"], // [!code highlight] }, }); ``` You need to provide the cache tag in the `$accelerate.invalidate` API: ```ts try { await prisma.$accelerate.invalidate({ // [!code highlight] tags: ["emails_with_alice"], // [!code highlight] }); // [!code highlight] } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError) { // The .code property can be accessed in a type-safe manner if (e.code === "P6003") { console.log("You've reached the cache invalidation rate limit. Please try again shortly."); } } throw e; } ``` ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate # Prisma Accelerate (/docs/accelerate) Location: Prisma Accelerate [Prisma Accelerate](https://www.prisma.io/accelerate) is a managed connection pool and global cache for your database. It works with Prisma ORM and supports PostgreSQL, MySQL, MongoDB, and more. Prisma ORM supports connection pooling and query caching through Accelerate — you don't need a separate pooler or caching layer. Accelerate is included with [Prisma Postgres](/postgres) and also available as a standalone add-on for external databases. **Connection pooling.** Accelerate manages a global connection pool across 15+ regions. This matters most in serverless and edge environments, where connection exhaustion is a real failure mode. Prisma ORM routes through the pool automatically once you swap in the Accelerate connection string. **Query caching.** Add a `cacheStrategy` to any Prisma ORM query to cache results at the edge using TTL or stale-while-revalidate. Results are served from 300+ cache locations. No Redis, no Memcached, no separate service. ```typescript title="src/lib/posts.ts" const posts = await prisma.post.findMany({ cacheStrategy: { ttl: 60, swr: 10 }, // serve from cache for 60s (TTL); after TTL expires, serve stale for up to 10s while revalidating in the background (SWR) }) ``` Supported databases [#supported-databases] Accelerate works with the database you already have, whether it is publicly accessible, or via an IP allowlist. * PostgreSQL * MySQL * MariaDB * PlanetScale * CockroachDB * MongoDB Getting started [#getting-started] * [Getting started](/accelerate/getting-started) - Learn how to get up and running with Prisma Accelerate * [Local development](/accelerate/local-development) - Learn how to use Prisma Accelerate in a development environment * [Examples](/accelerate/examples) - Check out ready-to-run examples for Prisma Accelerate ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # Local development (/docs/accelerate/local-development) Location: Accelerate > Local development Prisma Accelerate efficiently scales production traffic with integrated connection pooling and a global database cache. In development environments, you may want to use a local database to minimize expenses. Furthermore, you may consider extending Prisma Client with the Accelerate client extension once so that you can use a local database in development and a hosted database with Accelerate’s connection pooling and caching enabled. This eliminates the need for conditional logic to switch clients between development and production. This guide will explain how to use Prisma Accelerate client extension in a development environment with a local database. Using Prisma Accelerate client extension in development and production [#using-prisma-accelerate-client-extension-in-development-and-production]
Using Prisma Accelerate client extension in development Accelerate does not work with a local database. However, in a development environment, you can still use Prisma Client with the Accelerate client extension. This setup will not provide Accelerate's connection pooling and caching features. The following steps outline how to use Prisma ORM and Prisma Accelerate with a local PostgreSQL database. 1. Update the `DATABASE_URL` environment variable with your local database's connection string: ```bash DATABASE_URL="postgres://username:password@127.0.0.1:5432/localdb" ``` 2. Generate a Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 3. Set up Prisma Client with the Accelerate client extension: ```typescript import { PrismaClient } from "@prisma/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient().$extends(withAccelerate()); ``` > The extended instance of Prisma Client will use the local database. Hence, Prisma Accelerate will not be used in your development environment to respond to your Prisma Client queries. Using Prisma Accelerate client extension in production If an Accelerate connection string is used as the `DATABASE_URL` environment variable, Prisma Client will route your queries through Accelerate. Using Prisma Accelerate locally in an edge function [#using-prisma-accelerate-locally-in-an-edge-function] When using an edge function, e.g., [Vercel's edge runtime](https://vercel.com/docs/functions/runtimes/edge-runtime), for your development environment, update your Prisma Client import as follows: ```typescript import { PrismaClient } from "@prisma/client/edge"; ``` Generally, edge function environments lack native support for existing APIs enabling TCP-based database connections. Prisma Accelerate provides a connection string that allows querying your database over HTTP, a protocol supported in all edge runtimes. ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate # Static IP (/docs/accelerate/static-ip) Location: Accelerate > Static IP You can enable static IP for Accelerate when your security setup requires IP allowlisting or if you're implementing firewalls that only permit access from trusted IPs, ensuring controlled and secure database connections. Result of enabling static IP Accelerate with a database using IP allowlisting > [!NOTE] > To enable static IP support for Accelerate within an existing or a new project environment, your workspace will need to be on our Pro or Business plans. Take a look at the [pricing page](https://www.prisma.io/pricing#accelerate) for more information. Enable static IP in Accelerate [#enable-static-ip-in-accelerate] You can opt-in to use static IP for Accelerate in the [Platform Console](https://pris.ly/pdp) in two ways: 1. When enabling Accelerate for your project environment: [#1-when-enabling-accelerate-for-your-project-environment] 1. Specify your database connection string and connection pool region. 2. Enable static IP by toggling the **Static IP** switch in the **Network restrictions** section. 3. Click on the **Enable Accelerate** button. 2. For projects already using Accelerate: [#2-for-projects-already-using-accelerate] 1. Navigate to the Accelerate **Settings** tab in the project environment. 2. Enable static IP by toggling the **Static IP** switch in the **Network restrictions** section. Enabling static IP for Accelerate will provide you with a list of static IPv4 and IPv6 addresses. Once you have these addresses, configure your database firewall to allow incoming connections only from these IPs and any other trusted IPs that need access to your database. > [!NOTE] > Since you cannot enable static IP for an existing Accelerate-enabled environment, we recommend opting for static IP when enabling Accelerate in a new environment. Use the same database URL as your existing Accelerate environment to instantly access static IP support for Accelerate. ## Related pages - [`Caching queries`](https://www.prisma.io/docs/accelerate/caching): Learn everything you need to know to use Accelerate's global database caching - [`Compare Accelerate`](https://www.prisma.io/docs/accelerate/compare): Learn how Prisma Accelerate compares to other connection poolers like pgbouncer - [`Connection Pooling`](https://www.prisma.io/docs/accelerate/connection-pooling): Learn about everything you need to know to use Accelerate's connection pooling - [`Evaluating`](https://www.prisma.io/docs/accelerate/evaluating): Learn about evaluating Prisma Accelerate - [`Examples`](https://www.prisma.io/docs/accelerate/examples): Check out ready-to-run examples for Prisma Accelerate # Build faster with Prisma + AI (/docs/ai) Location: Build faster with Prisma + AI In the era of AI, where code is increasingly written by agents, ensuring clarity, type safety, and reliable infrastructure is essential. With 5+ years of leadership in the TypeScript ecosystem, Prisma ORM and Prisma Postgres provide the proven foundation for AI-assisted development. Get started [#get-started] Run the following command to bootstrap your database with a prompt: #### npm ```bash npx prisma init --prompt "Create a habit tracker application" ``` #### pnpm ```bash pnpm dlx prisma init --prompt "Create a habit tracker application" ``` #### yarn ```bash yarn dlx prisma init --prompt "Create a habit tracker application" ``` #### bun ```bash bunx --bun prisma init --prompt "Create a habit tracker application" ``` AI Coding Tools [#ai-coding-tools] Prisma ORM and Prisma Postgres integrate seamlessly with your AI coding tools. Check out our documentation with tips and tricks for working with Prisma in various AI editors. * [Cursor](/ai/tools/cursor) - Define project-specific rules and use your schema as context to generate accurate queries and code. * [Codex](/ai/tools/codex) - Install the Prisma Codex plugin with Prisma ORM skills and the remote Prisma MCP server. * [Windsurf](/ai/tools/windsurf) - Automate your database workflows by generating schemas, queries, and seed data in this AI-powered editor. * [Github Copilot](/ai/tools/github-copilot) - Get Prisma-aware code suggestions, run CLI commands from chat, and query the Prisma docs. * [ChatGPT](/ai/tools/chatgpt) - Learn how to connect the Prisma MCP server to ChatGPT to manage your databases with natural language. Agent Skills [#agent-skills] AI agents often generate outdated Prisma v6 code. Install Prisma Skills to give your agent accurate, up-to-date v7 knowledge - CLI commands, Client API, upgrade guides, database setup, and Prisma Postgres workflows. #### npm ```bash npx skills add prisma/skills ``` #### pnpm ```bash pnpm dlx skills add prisma/skills ``` #### yarn ```bash yarn dlx skills add prisma/skills ``` #### bun ```bash bunx --bun skills add prisma/skills ``` * [Available skills and setup](/ai/tools/skills) - See all available skills and learn how to install them. MCP server [#mcp-server] With Prisma's MCP server, your AI tool can take database actions on your behalf: Provisioning a new Prisma Postgres instance, creating database backups and executing SQL queries are just a few of its capabilities. ```json title="Integrate in AI tool" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` * [Capabilities and tools](/ai/tools/mcp-server#tools) - Discover all the tools that make up the capabilities of the Prisma MCP server. * [Integrating in AI tools](/ai/tools/mcp-server#integrating-in-ai-tools) - Learn how to integrate Prisma's MCP server in your favorite AI tool, such as Cursor, Claude, Warp, and more. * [How we built it](https://www.prisma.io/blog/about-mcp-servers-and-how-we-built-one-for-prisma) - Read this technical deep dive about the MCP protocol and how we built the Prisma MCP server. Vibe Coding Tutorials [#vibe-coding-tutorials] Build complete, production-ready applications from scratch with AI assistance. * [Build a Linktree Clone SaaS](/ai/tutorials/linktree-clone) - A complete vibe coding tutorial: build a full Linktree clone SaaS with Next.js, Prisma Postgres, and Clerk auth using AI assistance. Resources [#resources] * [Vibe Coding with Limits](https://www.prisma.io/blog/vibe-coding-with-limits-how-to-build-apps-in-the-age-of-ai) - How to Build Apps in the Age of AI * [Vibe Coding an E-commerce App](https://www.prisma.io/blog/vibe-coding-with-prisma-mcp-and-nextjs) - with Prisma MCP and Next.js * [Integrating the Vercel AI SDK](/guides/integrations/ai-sdk) - in a Next.js application Integrations [#integrations] * [Automate with Pipedream](https://pipedream.com/apps/prisma-management-api) - Connect Prisma Postgres to 2,800+ apps for powerful automation * [Firebase Studio](/guides/postgres/idx) - Prompt your application with Firebase Studio & Prisma Postgres ## Related pages - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows - [`Management API`](https://www.prisma.io/docs/management-api): Programmatically manage your Prisma Postgres databases, projects, and workspaces with the Management API # debug (/docs/cli/debug) Location: CLI > debug The `prisma debug` command prints information helpful for debugging and bug reports. > [!NOTE] > Available from version 5.6.0 and newer. Usage [#usage] ```bash prisma debug [options] ``` Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Examples [#examples] Display debug information [#display-debug-information] #### npm ```bash npx prisma debug ``` #### pnpm ```bash pnpm dlx prisma debug ``` #### yarn ```bash yarn dlx prisma debug ``` #### bun ```bash bunx --bun prisma debug ``` Output: ```text -- Prisma schema -- Path: /prisma/schema.prisma -- Local cache directory for engines files -- Path: /.cache/prisma -- Environment variables -- When not set, the line is dimmed and no value is displayed. When set, the line is bold and the value is inside the `` backticks. For general debugging - CI: - DEBUG: - NODE_ENV: - RUST_LOG: - RUST_BACKTRACE: - NO_COLOR: - TERM: `xterm-256color` - NODE_TLS_REJECT_UNAUTHORIZED: - NO_PROXY: - http_proxy: - HTTP_PROXY: - https_proxy: - HTTPS_PROXY: For hiding messages - PRISMA_DISABLE_WARNINGS: - PRISMA_HIDE_PREVIEW_FLAG_WARNINGS: - PRISMA_HIDE_UPDATE_MESSAGE: For downloading engines - PRISMA_ENGINES_MIRROR: - PRISMA_BINARIES_MIRROR (deprecated): - PRISMA_ENGINES_CHECKSUM_IGNORE_MISSING: - BINARY_DOWNLOAD_VERSION: For custom engines - PRISMA_SCHEMA_ENGINE_BINARY: - PRISMA_MIGRATION_ENGINE_BINARY: For Prisma Client - PRISMA_SHOW_ALL_TRACES: For Prisma Migrate - PRISMA_SCHEMA_DISABLE_ADVISORY_LOCK: For Prisma Studio - BROWSER: -- Terminal is interactive? -- true -- CI detected? -- false ``` Use with older versions [#use-with-older-versions] If using an older Prisma version: #### npm ```bash npx prisma@latest debug ``` #### pnpm ```bash pnpm dlx prisma@latest debug ``` #### yarn ```bash yarn dlx prisma@latest debug ``` #### bun ```bash bunx --bun prisma@latest debug ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema - [`init`](https://www.prisma.io/docs/cli/init): Set up a new Prisma project in the current directory # format (/docs/cli/format) Location: CLI > format The `prisma format` command formats your Prisma schema file. It validates, formats, and persists the schema. Usage [#usage] ```bash prisma format [options] ``` Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Examples [#examples] Format the default schema [#format-the-default-schema] #### npm ```bash npx prisma format ``` #### pnpm ```bash pnpm dlx prisma format ``` #### yarn ```bash yarn dlx prisma format ``` #### bun ```bash bunx --bun prisma format ``` Output on success: ```text Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Formatted prisma/schema.prisma in 116ms ``` Format a specific schema [#format-a-specific-schema] #### npm ```bash npx prisma format --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma format --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma format --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma format --schema=./alternative/schema.prisma ``` Error output [#error-output] If the schema has validation errors, formatting will fail: ```text Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Schema validation error - Error (query-engine-node-api library) Error code: P1012 error: The preview feature "unknownFeatureFlag" is not known. Expected one of: [...] schema.prisma:3 | 2 | provider = "prisma-client" 3 | previewFeatures = ["unknownFeatureFlag"] | Validation Error Count: 1 ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema - [`init`](https://www.prisma.io/docs/cli/init): Set up a new Prisma project in the current directory # generate (/docs/cli/generate) Location: CLI > generate The `prisma generate` command generates assets like Prisma Client based on the [`generator`](/orm/prisma-schema/overview/generators) and [`data model`](/orm/prisma-schema/data-model/models) blocks defined in your `schema.prisma` file. Usage [#usage] ```bash prisma generate [options] ``` How it works [#how-it-works] 1. Inspects the current directory to find a Prisma schema 2. Generates a customized Prisma Client based on your schema into the output directory specified in the generator block Prerequisites [#prerequisites] Add a generator definition in your `schema.prisma` file: ```prisma generator client { provider = "prisma-client" output = "./generated" } ``` Options [#options] | Option | Description | | ------------------ | ------------------------------------------------------ | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `--sql` | Generate typed SQL module | | `--watch` | Watch the Prisma schema and regenerate after changes | | `--generator` | Generator to use (can be provided multiple times) | | `--no-hints` | Hide hint messages (still outputs errors and warnings) | | `--require-models` | Do not allow generating a client without models | Examples [#examples] Generate Prisma Client [#generate-prisma-client] #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` Output: ```text ✔ Generated Prisma Client to ./node_modules/.prisma/client in 61ms You can now start using Prisma Client in your code: import { PrismaClient } from '../prisma/generated/client' const prisma = new PrismaClient() ``` Generate with a custom schema path [#generate-with-a-custom-schema-path] #### npm ```bash npx prisma generate --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma generate --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma generate --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma generate --schema=./alternative/schema.prisma ``` Watch mode [#watch-mode] Automatically regenerate when the schema changes: #### npm ```bash npx prisma generate --watch ``` #### pnpm ```bash pnpm dlx prisma generate --watch ``` #### yarn ```bash yarn dlx prisma generate --watch ``` #### bun ```bash bunx --bun prisma generate --watch ``` Output: ```text Watching... /home/prismauser/prisma/schema.prisma ✔ Generated Prisma Client to ./node_modules/.prisma/client in 45ms ``` Generate specific generators [#generate-specific-generators] Run only specific generators: #### npm ```bash npx prisma generate --generator client ``` #### pnpm ```bash pnpm dlx prisma generate --generator client ``` #### yarn ```bash yarn dlx prisma generate --generator client ``` #### bun ```bash bunx --bun prisma generate --generator client ``` Multiple generators: #### npm ```bash npx prisma generate --generator client --generator zod_schemas ``` #### pnpm ```bash pnpm dlx prisma generate --generator client --generator zod_schemas ``` #### yarn ```bash yarn dlx prisma generate --generator client --generator zod_schemas ``` #### bun ```bash bunx --bun prisma generate --generator client --generator zod_schemas ``` Generated assets [#generated-assets] The `prisma-client` generator creates a customized client for working with your database. You can [customize the output folder](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider) using the `output` field in the generator block. ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`init`](https://www.prisma.io/docs/cli/init): Set up a new Prisma project in the current directory # CLI Overview (/docs/cli) Location: CLI Overview The Prisma CLI provides commands for: * **Project setup**: Initialize new Prisma projects * **Code generation**: Generate Prisma Client and other artifacts * **Database management**: Pull schemas, push changes, seed data * **Migrations**: Create, apply, and manage database migrations * **Development tools**: Local database servers, schema validation, formatting Installation [#installation] The Prisma CLI is available as an npm package. Install it as a development dependency: #### npm ```bash npm install prisma --save-dev ``` #### pnpm ```bash pnpm add prisma --save-dev ``` #### yarn ```bash yarn add prisma --dev ``` #### bun ```bash bun add prisma --dev ``` Usage [#usage] ```bash prisma [command] ``` Commands [#commands] | Command | Description | | --------------------------- | ---------------------------------------------------- | | [`init`](/cli/init) | Set up Prisma for your app | | [`dev`](/cli/dev) | Start a local Prisma Postgres server for development | | [`generate`](/cli/generate) | Generate artifacts (e.g. Prisma Client) | | [`db`](/cli/db) | Manage your database schema and lifecycle | | [`migrate`](/cli/migrate) | Migrate your database | | [`studio`](/cli/studio) | Browse your data with Prisma Studio | | [`validate`](/cli/validate) | Validate your Prisma schema | | [`format`](/cli/format) | Format your Prisma schema | | [`version`](/cli/version) | Display Prisma version info | | [`debug`](/cli/debug) | Display Prisma debug info | Global flags [#global-flags] These flags are available for all commands: | Flag | Description | | ------------------- | ----------------------------------- | | `--help`, `-h` | Show help information for a command | | `--preview-feature` | Run Preview Prisma commands | Using a HTTP proxy [#using-a-http-proxy] Prisma CLI supports custom HTTP proxies. This is useful when behind a corporate firewall. Set one of these environment variables: * `HTTP_PROXY` or `http_proxy`: Proxy URL for HTTP traffic (e.g., `http://localhost:8080`) * `HTTPS_PROXY` or `https_proxy`: Proxy URL for HTTPS traffic (e.g., `https://localhost:8080`) ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows - [`Management API`](https://www.prisma.io/docs/management-api): Programmatically manage your Prisma Postgres databases, projects, and workspaces with the Management API # init (/docs/cli/init) Location: CLI > init The `prisma init` command bootstraps a fresh Prisma project within the current directory. Usage [#usage] ```bash prisma init [options] ``` The command creates a `prisma` directory containing a `schema.prisma` file. By default, the project is configured for [local Prisma Postgres](/postgres/database/local-development), but you can choose a different database using the `--datasource-provider` option. Options [#options] | Option | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------- | | `-h`, `--help` | Display help message | | `--db` | Provision a fully managed Prisma Postgres database on the Prisma Data Platform | | `--datasource-provider` | Define the datasource provider: `postgresql`, `mysql`, `sqlite`, `sqlserver`, `mongodb`, or `cockroachdb` | | `--generator-provider` | Define the generator provider to use (default: `prisma-client`) | | `--preview-feature` | Define a preview feature to use (can be specified multiple times) | | `--output` | Define Prisma Client generator output path | | `--url` | Define a custom datasource URL | Flags [#flags] | Flag | Description | | -------------- | ----------------------------------------------- | | `--with-model` | Add an example model to the created schema file | Examples [#examples] Set up a new Prisma project (default) [#set-up-a-new-prisma-project-default] Sets up a new project configured for local Prisma Postgres: #### npm ```bash npx prisma init ``` #### pnpm ```bash pnpm dlx prisma init ``` #### yarn ```bash yarn dlx prisma init ``` #### bun ```bash bunx --bun prisma init ``` Specify a datasource provider [#specify-a-datasource-provider] Set up a new project with MySQL as the datasource provider: #### npm ```bash npx prisma init --datasource-provider mysql ``` #### pnpm ```bash pnpm dlx prisma init --datasource-provider mysql ``` #### yarn ```bash yarn dlx prisma init --datasource-provider mysql ``` #### bun ```bash bunx --bun prisma init --datasource-provider mysql ``` Specify a generator provider [#specify-a-generator-provider] Set up a project with the legacy `prisma-client-js` generator instead of the default `prisma-client` generator: #### npm ```bash npx prisma init --generator-provider prisma-client-js ``` #### pnpm ```bash pnpm dlx prisma init --generator-provider prisma-client-js ``` #### yarn ```bash yarn dlx prisma init --generator-provider prisma-client-js ``` #### bun ```bash bunx --bun prisma init --generator-provider prisma-client-js ``` Specify preview features [#specify-preview-features] Set up a project with specific preview features enabled: #### npm ```bash npx prisma init --preview-feature metrics ``` #### pnpm ```bash pnpm dlx prisma init --preview-feature metrics ``` #### yarn ```bash yarn dlx prisma init --preview-feature metrics ``` #### bun ```bash bunx --bun prisma init --preview-feature metrics ``` Multiple preview features: #### npm ```bash npx prisma init --preview-feature views --preview-feature metrics ``` #### pnpm ```bash pnpm dlx prisma init --preview-feature views --preview-feature metrics ``` #### yarn ```bash yarn dlx prisma init --preview-feature views --preview-feature metrics ``` #### bun ```bash bunx --bun prisma init --preview-feature views --preview-feature metrics ``` Specify a custom output path [#specify-a-custom-output-path] Set up a project with a custom output path for Prisma Client: #### npm ```bash npx prisma init --output ./generated-client ``` #### pnpm ```bash pnpm dlx prisma init --output ./generated-client ``` #### yarn ```bash yarn dlx prisma init --output ./generated-client ``` #### bun ```bash bunx --bun prisma init --output ./generated-client ``` Specify a custom datasource URL [#specify-a-custom-datasource-url] Set up a project with a specific database URL: #### npm ```bash npx prisma init --url mysql://user:password@localhost:3306/mydb ``` #### pnpm ```bash pnpm dlx prisma init --url mysql://user:password@localhost:3306/mydb ``` #### yarn ```bash yarn dlx prisma init --url mysql://user:password@localhost:3306/mydb ``` #### bun ```bash bunx --bun prisma init --url mysql://user:password@localhost:3306/mydb ``` Add an example model [#add-an-example-model] Set up a project with an example `User` model: #### npm ```bash npx prisma init --with-model ``` #### pnpm ```bash pnpm dlx prisma init --with-model ``` #### yarn ```bash yarn dlx prisma init --with-model ``` #### bun ```bash bunx --bun prisma init --with-model ``` Provision a Prisma Postgres database [#provision-a-prisma-postgres-database] Create a new project with a managed Prisma Postgres database: #### npm ```bash npx prisma init --db ``` #### pnpm ```bash pnpm dlx prisma init --db ``` #### yarn ```bash yarn dlx prisma init --db ``` #### bun ```bash bunx --bun prisma init --db ``` This requires authentication with the [Prisma Data Platform Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=cli). Generated files [#generated-files] After running `prisma init`, you'll have the following files: prisma/schema.prisma [#prismaschemaprisma] The Prisma schema file where you define your data model: ```prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } ``` prisma.config.ts [#prismaconfigts] A TypeScript configuration file for Prisma: ```typescript import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` .env [#env] Environment variables file for your project: ```bash DATABASE_URL="postgresql://user:password@localhost:5432/mydb" ``` .gitignore [#gitignore] Git ignore file configured for Prisma projects: ```bash node_modules .env /generated/prisma ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # studio (/docs/cli/studio) Location: CLI > studio The `prisma studio` command starts a local web server with a web app to interactively browse and manage your data. Usage [#usage] ```bash prisma studio [options] ``` > [!NOTE] > Supported databases > > Prisma Studio currently supports PostgreSQL, MySQL, and SQLite. Support for CockroachDB and MongoDB is not available yet but may be added in future releases. Prerequisites [#prerequisites] Configure your database connection in `prisma.config.ts`: ```prisma file=schema.prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "sqlite" } ``` ```typescript file=prisma.config.ts import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Options [#options] | Option | Description | Default | | ----------------- | ---------------------------------------------------- | -------------- | | `-h`, `--help` | Display help message | | | `-p`, `--port` | Port number to start Studio on | `5555` | | `-b`, `--browser` | Browser to auto-open Studio in | System default | | `--config` | Custom path to your Prisma config file | | | `--url` | Database connection string (overrides Prisma config) | | Examples [#examples] Start Studio on the default port [#start-studio-on-the-default-port] #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` Start Studio on a custom port [#start-studio-on-a-custom-port] #### npm ```bash npx prisma studio --port 7777 ``` #### pnpm ```bash pnpm dlx prisma studio --port 7777 ``` #### yarn ```bash yarn dlx prisma studio --port 7777 ``` #### bun ```bash bunx --bun prisma studio --port 7777 ``` Start Studio in a specific browser [#start-studio-in-a-specific-browser] #### npm ```bash npx prisma studio --browser firefox ``` #### pnpm ```bash pnpm dlx prisma studio --browser firefox ``` #### yarn ```bash yarn dlx prisma studio --browser firefox ``` #### bun ```bash bunx --bun prisma studio --browser firefox ``` Or using the `BROWSER` environment variable: ```bash BROWSER=firefox prisma studio ``` Start Studio without opening a browser [#start-studio-without-opening-a-browser] #### npm ```bash npx prisma studio --browser none ``` #### pnpm ```bash pnpm dlx prisma studio --browser none ``` #### yarn ```bash yarn dlx prisma studio --browser none ``` #### bun ```bash bunx --bun prisma studio --browser none ``` Start Studio with a custom config file [#start-studio-with-a-custom-config-file] #### npm ```bash npx prisma studio --config=./prisma.config.ts ``` #### pnpm ```bash pnpm dlx prisma studio --config=./prisma.config.ts ``` #### yarn ```bash yarn dlx prisma studio --config=./prisma.config.ts ``` #### bun ```bash bunx --bun prisma studio --config=./prisma.config.ts ``` Start Studio with a direct database connection string [#start-studio-with-a-direct-database-connection-string] #### npm ```bash npx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### pnpm ```bash pnpm dlx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### yarn ```bash yarn dlx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### bun ```bash bunx --bun prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # validate (/docs/cli/validate) Location: CLI > validate The `prisma validate` command validates the [Prisma Schema Language](/orm/prisma-schema/overview) of your Prisma schema file. Usage [#usage] ```bash prisma validate [options] ``` Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Examples [#examples] Validate the default schema [#validate-the-default-schema] #### npm ```bash npx prisma validate ``` #### pnpm ```bash pnpm dlx prisma validate ``` #### yarn ```bash yarn dlx prisma validate ``` #### bun ```bash bunx --bun prisma validate ``` Output on success: ```text Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma The schema at /absolute/path/prisma/schema.prisma is valid ``` Validate a specific schema [#validate-a-specific-schema] #### npm ```bash npx prisma validate --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma validate --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma validate --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma validate --schema=./alternative/schema.prisma ``` Validate with a config file [#validate-with-a-config-file] #### npm ```bash npx prisma validate --config=./prisma.config.ts ``` #### pnpm ```bash pnpm dlx prisma validate --config=./prisma.config.ts ``` #### yarn ```bash yarn dlx prisma validate --config=./prisma.config.ts ``` #### bun ```bash bunx --bun prisma validate --config=./prisma.config.ts ``` Error output [#error-output] If the schema has validation errors: ```text Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Schema validation error - Error (query-engine-node-api library) Error code: P1012 error: The preview feature "unknownFeatureFlag" is not known. Expected one of: [...] schema.prisma:3 | 2 | provider = "prisma-client" 3 | previewFeatures = ["unknownFeatureFlag"] | Validation Error Count: 1 ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # version (/docs/cli/version) Location: CLI > version The `prisma version` command outputs information about your current Prisma version, platform, and engine binaries. Usage [#usage] ```bash prisma version [options] ``` Or use the shorthand: ```bash prisma -v [options] ``` Options [#options] | Option | Description | | -------------- | ----------------------------------------- | | `-h`, `--help` | Display help message | | `--json` | Output version information in JSON format | Examples [#examples] Display version information [#display-version-information] #### npm ```bash npx prisma version ``` #### pnpm ```bash pnpm dlx prisma version ``` #### yarn ```bash yarn dlx prisma version ``` #### bun ```bash bunx --bun prisma version ``` Output: ```text Environment variables loaded from .env prisma : 2.21.0-dev.4 @prisma/client : 2.21.0-dev.4 Current platform : windows Query Engine : query-engine 2fb8f444d9cdf7c0beee7b041194b42d7a9ce1e6 Migration Engine : migration-engine-cli 2fb8f444d9cdf7c0beee7b041194b42d7a9ce1e6 Format Binary : prisma-fmt 60ba6551f29b17d7d6ce479e5733c70d9c00860e Default Engines Hash : 60ba6551f29b17d7d6ce479e5733c70d9c00860e Studio : 0.365.0 ``` Display version using shorthand [#display-version-using-shorthand] #### npm ```bash npx prisma -v ``` #### pnpm ```bash pnpm dlx prisma -v ``` #### yarn ```bash yarn dlx prisma -v ``` #### bun ```bash bunx --bun prisma -v ``` Display version as JSON [#display-version-as-json] #### npm ```bash npx prisma version --json ``` #### pnpm ```bash pnpm dlx prisma version --json ``` #### yarn ```bash yarn dlx prisma version --json ``` #### bun ```bash bunx --bun prisma version --json ``` Output: ```json { "prisma": "2.21.0-dev.4", "@prisma/client": "2.21.0-dev.4", "current-platform": "windows", "query-engine": "query-engine 60ba6551f29b17d7d6ce479e5733c70d9c00860e", "migration-engine": "migration-engine-cli 60ba6551f29b17d7d6ce479e5733c70d9c00860e", "format-binary": "prisma-fmt 60ba6551f29b17d7d6ce479e5733c70d9c00860e", "default-engines-hash": "60ba6551f29b17d7d6ce479e5733c70d9c00860e", "studio": "0.365.0" } ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # Concepts (/docs/console/concepts) Location: Console > Concepts The Console workflows are based on four main concepts: * [**User account**](#user-account): In order to use Prisma products, you need to have a Console user account. A *user* will typically create one user account to manage all their workspaces, projects and resources. The *user* can also be invited to join other workspaces to collaborate on the projects in that workspace. * [**Workspaces**](#workspace): A user account can belong to multiple workspaces. A workspace typically represents a *team* of individuals working together on one or more projects. **Billing is on a workspace level**, i.e. the invoice for a workspace at the end of the month captures all costs associated with the projects in that workspace. * [**Projects**](#project): A project belongs to a workspace. It typically represents the *application* or *service* a team is working on. * [**Resources**](#resources): Resources represent the actual services or databases within a project. For example, in Prisma Postgres, each project can contain multiple databases. For Accelerate, resources might correspond to different environments (like `Development`, `Staging`, or `Production`). **Connection strings are provisioned at the resource level**, and products are configured per resource as well (e.g., the database connection string used for Accelerate). Here is a visual illustration of how these concepts relate to each other: How the concepts of the Console (user account, workspaces, projects, and resources) relate to each other User account [#user-account] A user account is the prerequisite for any interactions with Prisma products. You can use it to manage your workspaces (and their projects). A user account can be invited to collaborate on workspaces created by other users as well. If you need to delete your user account, go [here](/console/more/support#deleting-your-pdp-account). Workspace [#workspace] You can create several workspaces. A workspace is an isolated space to host projects. A workspace can have multiple user accounts associated with it so that multiple users can collaborate on the projects in the workspace. In each workspace, you can: * view and manage all projects (and their resources) in that workspace. * manage billing, i.e. select a [subscription plan](https://www.prisma.io/pricing?utm_source=docs\&utm_medium=platform-docs), configure payment methods, or view the invoice history. * view the usage of your enabled Prisma products across all projects in that workspace. * invite other users to collaborate in the workspace. * access [Query Insights](/query-insights) to measure query performance and receive AI-powered recommendations (available with Prisma Postgres). Project [#project] In each workspace, you can create several projects. A project typically represents an application (a product or service). You typically have one [Prisma schema](/orm/prisma-schema/overview) per project. In each project, you can: * view and manage all resources (like databases) in that project. The number of projects you can create in a workspace depends on the [subscription plan](https://www.prisma.io/pricing?utm_source=docs\&utm_medium=platform-docs) configured in that workspace. Resources [#resources] Resources represent the actual services or databases within a project. The type of resources available depends on the Prisma products you're using: * **For Prisma Postgres**: Each project can contain multiple databases. These databases are the primary resources you'll manage. * **For Accelerate**: Resources typically correspond to different deployment stages (like `Development`, `Staging`, or `Production`). In each project, you can: * Create and manage multiple resources (databases or environments) * Generate connection strings specific to each resource * Configure product-specific settings: * **For Prisma Postgres databases**: * View database metrics and performance * Configure connection settings * Manage database users and permissions * **For Accelerate resources**: * Set your database connection string * Configure the region for connection pooling * Adjust connection pool size and performance settings * Set query duration and response size limits * Enable static IP for secure connections The number of resources you can create in a project depends on your [subscription plan](https://www.prisma.io/pricing?utm_source=docs\&utm_medium=platform-docs). ## Related pages - [`Getting Started`](https://www.prisma.io/docs/console/getting-started): Quick start guide for setting up and using the Prisma Console # Getting Started (/docs/console/getting-started) Location: Console > Getting Started This guide walks you through setting up your Console account and creating your first project. Prerequisites [#prerequisites] * A GitHub account (for authentication) * A Prisma project (optional, but recommended) Step 1: Create your account [#step-1-create-your-account] 1. Go to [console.prisma.io/login](https://console.prisma.io/login?utm_source=docs\&utm_medium=content\&utm_content=console) 2. Click **Sign in with GitHub** 3. Authorize Prisma Console to access your GitHub account You now have a Console account with a default workspace. Step 2: Set up a workspace [#step-2-set-up-a-workspace] When you create an account, a default workspace is automatically created for you. You can create additional workspaces for different teams or organizations. Create a workspace (optional) [#create-a-workspace-optional] To create an additional workspace: 1. Click the workspace dropdown in the top navigation 2. Click **Create Workspace** 3. Enter a name for your workspace 4. Click **Create** Step 3: Create a project [#step-3-create-a-project] Projects organize your databases and environments within a workspace. Using the Console web interface [#using-the-console-web-interface] 1. Navigate to your workspace 2. Click **Create Project** 3. Enter a project name 4. Click **Create** Step 4: Create a resource [#step-4-create-a-resource] Resources are the actual databases or environments within your project. For Prisma Postgres [#for-prisma-postgres] 1. Navigate to your project 2. Click **Create Database** 3. Enter a database name 4. Select a region 5. Click **Create** For Accelerate [#for-accelerate] 1. Navigate to your project 2. Click **Create Environment** 3. Enter an environment name (e.g., "production") 4. Click **Create** Step 5: Generate a connection string [#step-5-generate-a-connection-string] Connection strings authenticate your application's requests to Prisma products. Using the Console web interface [#using-the-console-web-interface-1] 1. Navigate to your resource (database or environment) 2. Click **Connection Strings** tab 3. Click **Create Connection String** 4. Enter a name for the connection string 5. Copy the connection string and store it securely 6. Click **Done** Step 6: Use the connection string in your application [#step-6-use-the-connection-string-in-your-application] Add the connection string to your `.env` file: ```bash # For Accelerate DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=YOUR_API_KEY" ``` Next steps [#next-steps] * Learn more about [Console concepts](/console/concepts) * Explore [database metrics](/console/features/metrics) * Check out the [CLI reference](/cli/console) ## Related pages - [`Concepts`](https://www.prisma.io/docs/console/concepts): Understand the core concepts of the Prisma Console: user accounts, workspaces, projects, and resources # Console (/docs/console) Location: Console Overview [#overview] The [Console](https://console.prisma.io/login?utm_source=docs\&utm_medium=content\&utm_content=console) enables you to manage and configure your projects that use Prisma products, and helps you integrate them into your application: * [Query Insights](/query-insights): Inspect slow queries, connect Prisma calls to SQL, and apply focused fixes. * [Prisma Postgres](/postgres): A managed PostgreSQL database that is optimized for Prisma ORM. Getting started [#getting-started] To start using Prisma products, you'll need to: 1. Create a Console account 2. Set up a workspace for your team 3. Create a project for your application 4. Generate connection strings for your resources Learn more in the [Getting Started](/console/getting-started) guide. Core concepts [#core-concepts] The Console is organized around four main concepts: * **[User account](/console/concepts#user-account)**: Your personal account to manage workspaces and projects * **[Workspaces](/console/concepts#workspace)**: Team-level container where billing is managed * **[Projects](/console/concepts#project)**: Application-level container within a workspace * **[Resources](/console/concepts#resources)**: Actual services or databases within a project (databases for Prisma Postgres) Read more about [Console concepts](/console/concepts). Console CLI [#console-cli] In addition to the web interface, the Prisma CLI provides another way to interact with your Console account and manage Prisma products. This can be useful for programmatic access, such as integrating into CI workflows. Learn more about the [Console CLI commands](/cli/console). ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows - [`Management API`](https://www.prisma.io/docs/management-api): Programmatically manage your Prisma Postgres databases, projects, and workspaces with the Management API # Guides (/docs/guides) Location: 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. Quick start [#quick-start] Scaffold a new project with Prisma ORM and Prisma Postgres already set up: #### npm ```bash npm create prisma@latest ``` #### pnpm ```bash pnpm create prisma@latest ``` #### yarn ```bash yarn create prisma@latest ``` #### bun ```bash bun create prisma@latest ``` Pick your framework and options from the prompts. To skip prompts use `--yes`, to set a framework upfront use `--template` (`next`, `hono`, `svelte`, `astro`, `nuxt`, `tanstack-start`, `nestjs`, `elysia`, `turborepo`). Getting started [#getting-started] * [Next.js](/guides/frameworks/nextjs) - Learn how to use Prisma ORM in a Next.js app and deploy it to Vercel * [Hono](/guides/frameworks/hono) - Learn how to use Prisma ORM in a Hono app * [SvelteKit](/guides/frameworks/sveltekit) - Learn how to use Prisma ORM in a SvelteKit app ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Management API`](https://www.prisma.io/docs/management-api): Programmatically manage your Prisma Postgres databases, projects, and workspaces with the Management API # Writing guides (/docs/guides/making-guides) Location: Guides > Writing guides Introduction [#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 [#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 [#guide-structure] Required frontmatter [#required-frontmatter] Every guide must include the following frontmatter at the top of the file: ```mdx --- title: '[Descriptive title]' description: '[One-sentence summary of what the guide covers]' --- ``` * `title`: A clear, descriptive title (e.g., "Next.js", "Multiple databases", "GitHub Actions") * `description`: A one-sentence summary that describes what you'll learn or accomplish * `image`: A unique header image for social media sharing (coordinate with the design team) All frontmatter fields should use sentence case. Required sections [#required-sections] 1. **Introduction** (H2: `##`) * Brief overview of what the guide covers * What the reader will learn/accomplish * Link to any example repositories or related resources on GitHub 2. **Prerequisites** (H2: `##`) * Required software/tools with version numbers (e.g., "Node.js 20+") * Required accounts (e.g., "A Prisma Data Platform account") * Keep it concise - only list what's truly necessary 3. **Main content sections** (H2: `##`) * Use numbered steps (e.g., "## 1. Set up your project", "## 2. Install and Configure Prisma") * Use numbered subsections (e.g., "### 2.1. Install dependencies", "### 2.2. Define your Prisma Schema") * Each step should build on previous steps * Include all commands and code snippets needed 4. **Next steps** (H2: `##`) * What to do after completing the guide * Related guides or documentation (with links) * Additional resources Writing style and voice [#writing-style-and-voice] General principles [#general-principles] * Write in a clear, conversational tone * Use active voice and present tense * Address the reader directly using "you" (e.g., "You'll learn how to...") * Avoid jargon and explain technical terms when necessary * Be concise but thorough * Guide readers step-by-step through the process Code examples [#code-examples] * Include complete, runnable code examples * Use syntax highlighting with language specification * Include file paths in code block metadata using `title=` * Use ` ```bash title=".env" ` for `.env` files so inline `# [!code ++]`, `# [!code --]`, and `# [!code highlight]` annotations render correctly * Reserve ` ```text ` for other plain-text files that do not need Fumadocs code annotations * Use comments sparingly - only when needed to explain complex logic * Use ` ```npm ` for package manager commands (auto-converts to pnpm/yarn/bun) * Use ` ```bash ` for shell commands and `.env` files * Use ` ```text ` for other plain text files * Use ` ```typescript `, ` ```prisma `, ` ```json ` for respective languages Example with file path: ```typescript title="src/lib/prisma.ts" import { PrismaClient } from "../generated/prisma"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter, }); export default prisma; ``` Example showing changes: ```typescript title="prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Formatting conventions [#formatting-conventions] * Use backticks for inline code: * File names: `` `schema.prisma` `` * Directory names: `` `prisma/` `` * Code elements: `` `PrismaClient` `` * Package manager commands: Use ` ```npm ` blocks (see [Package manager commands](#package-manager-commands)) * Use admonitions for important information: ```markdown :::info Context or background information ::: :::note Important details to remember ::: :::warning Critical information or gotchas ::: :::tip Helpful suggestions or best practices ::: ``` * Use proper heading hierarchy (never skip levels) * Use numbered sections (e.g., "## 1. Setup", "### 1.1. Install") * Link to other documentation pages using relative paths (e.g., `[Database drivers](/orm/core-concepts/supported-databases/database-drivers)`) Guide categories [#guide-categories] | Category | Directory | Description | Examples | | ------------------- | ------------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Framework** | `guides/frameworks/` | Integrate Prisma with frameworks | [Next.js](/guides/frameworks/nextjs), [NestJS](/guides/frameworks/nestjs), [SvelteKit](/guides/frameworks/sveltekit) | | **Deployment** | `guides/deployment/` | Deploy apps and set up monorepos | [Turborepo](/guides/deployment/turborepo), [Cloudflare Workers](/guides/deployment/cloudflare-workers) | | **Integration** | `guides/integrations/` | Use Prisma with platforms and tools | [GitHub Actions](/guides/integrations/github-actions), [Supabase](/guides/integrations/supabase-accelerate) | | **Database** | `guides/database/` | Database patterns and migrations | [Multiple databases](/guides/database/multiple-databases), [Data migration](/guides/database/data-migration) | | **Authentication** | `guides/authentication/` | Authentication patterns with Prisma | [Auth.js + Next.js](/guides/authentication/authjs/nextjs), [Better Auth + Next.js](/guides/authentication/better-auth/nextjs), [Clerk + Next.js](/guides/authentication/clerk/nextjs) | | **Prisma Postgres** | `guides/postgres/` | Prisma Postgres features | [Vercel](/guides/postgres/vercel), [Netlify](/guides/postgres/netlify), [Viewing data](/guides/postgres/viewing-data) | | **Migration** | `guides/switch-to-prisma-orm/` | Switch from other ORMs | [From Mongoose](/guides/switch-to-prisma-orm/from-mongoose), [From Drizzle](/guides/switch-to-prisma-orm/from-drizzle) | Common patterns [#common-patterns] Package manager commands [#package-manager-commands] Use ` ```npm ` code blocks for package manager commands. These automatically convert to other package managers (pnpm, yarn, bun) in the UI: #### npm ```bash npm install prisma --save-dev ``` #### pnpm ```bash pnpm add prisma --save-dev ``` #### yarn ```bash yarn add prisma --dev ``` #### bun ```bash bun add prisma --dev ``` Environment variables [#environment-variables] Show `.env` file examples using ` ```bash title=".env" ` blocks: ```bash title=".env" DATABASE_URL="postgresql://user:password@localhost:5432/mydb" ``` If you need to show changes in an `.env` file, use bash comments for the Fumadocs annotations: ```bash title=".env" DATABASE_URL="postgresql://user:password@localhost:5432/mydb" # [!code --] DATABASE_URL="postgresql://user:password@db.example.com:5432/mydb" # [!code ++] ``` Database provider compatibility [#database-provider-compatibility] Include an info admonition when commands or code are PostgreSQL-specific: ```markdown :::info If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). ::: ``` Prisma Client instantiation [#prisma-client-instantiation] Show the standard pattern for creating a Prisma Client with database adapters: ```typescript title="lib/prisma.ts" import { PrismaClient } from "../generated/prisma"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter, }); export default prisma; ``` Include a warning about connection pooling: ```markdown :::warning We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently. ::: ``` Best practices [#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 Guide template [#guide-template] Use this template as a starting point for new guides. The template includes common sections and patterns used across Prisma guides. Basic template structure [#basic-template-structure] Copy this template for a new guide: ````markdown --- title: '[Your guide title]' description: '[One-sentence summary of what you'll learn]' image: '/img/guides/[guide-name]-cover.png' --- ## Introduction [Brief overview of what this guide covers and what you'll accomplish. Include a link to an example repository if available.] ## Prerequisites - [Node.js 20+](https://nodejs.org) - [Any other prerequisites] ## 1. Set up your project [Instructions for creating or setting up the project] ```npm # Example command npx create-next-app@latest my-app cd my-app ``` ## 2. Install and Configure Prisma ### 2.1. Install dependencies To get started with Prisma, you'll need to install a few dependencies: ```npm npm install prisma tsx @types/pg --save-dev ``` ```npm npm install @prisma/client @prisma/adapter-pg dotenv pg ``` :::info If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). ::: Once installed, initialize Prisma in your project: ```npm npx prisma init --output ../generated/prisma ``` :::info `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. ::: This will create: - A `prisma` directory with a `schema.prisma` file - A Prisma Postgres database - A `.env` file containing the `DATABASE_URL` - A `prisma.config.ts` file for configuration Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: ```npm npx create-db ``` ### 2.2. Define your Prisma Schema In the `prisma/schema.prisma` file, add your models: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] posts Post[] // [!code ++] } // [!code ++] model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] published Boolean @default(false) // [!code ++] authorId Int // [!code ++] author User @relation(fields: [authorId], references: [id]) // [!code ++] } // [!code ++] ``` ### 2.3. Run migrations and generate Prisma Client Create the database tables: ```npm npx prisma migrate dev --name init ``` Then generate Prisma Client: ```npm npx prisma generate ``` ## 3. [Integration-specific steps] [Add framework or platform-specific integration steps here] ## Next steps Now that you've completed this guide, you can: - [Suggestion 1] - [Suggestion 2] - [Related guide 1](/path/to/guide) - [Related guide 2](/path/to/guide) For more information: - [Prisma documentation](/orm) - [Related documentation] ```` Adding guides to navigation [#adding-guides-to-navigation] Guides are organized by category in subdirectories. To add a guide to the navigation, you need to update the appropriate `meta.json` file. Main categories [#main-categories] The main guide categories are listed in `meta.json`: ```json title="apps/docs/content/docs/guides/meta.json" { "title": "Guides", "root": true, "icon": "NotebookTabs", "pages": [ "index", "frameworks", "deployment", "authentication", "integrations", "postgres", "database", "switch-to-prisma-orm", "upgrade-prisma-orm" ] } ``` Adding a guide to a category [#adding-a-guide-to-a-category] To add a guide to a category (e.g., `frameworks`), edit the category's `meta.json` file: ```json title="apps/docs/content/docs/guides/frameworks/meta.json" { "title": "Frameworks", "defaultOpen": true, "pages": [ "nextjs", "astro", "nuxt", "your-new-guide" // [!code ++] ] } ``` The page name should match your `.mdx` filename without the extension. For example, if your file is `your-new-guide.mdx`, add `"your-new-guide"` to the `pages` array. Next steps [#next-steps] After reading this guide, you can: * Start writing your own guide using the provided template * Review existing guides in the category you're contributing to * Coordinate with the design team for a unique header image * Submit your guide for review # Using API Clients (/docs/management-api/api-clients) Location: Management API > Using API Clients This guide shows you how to configure popular API clients to work with the Management API using OAuth 2.0 authentication. Download the Postman collection to import all endpoints with OAuth2 auth pre-configured. Compatible with Postman, Yaak, Insomnia, and other clients that support the Postman Collection v2.1 format. Postman [#postman] Postman is a popular API client with testing, collaboration, and automation features for working with REST APIs. Prerequisites [#prerequisites] Before you begin, make sure you have: * A [Prisma Console account](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) * [Postman installed](https://www.postman.com/downloads/) 1. Create an OAuth2 Application [#1-create-an-oauth2-application] First, you'll need to register an OAuth2 application in Prisma Console: 1. Navigate to [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) and log in 2. Click the **🧩 Integrations** tab in the left sidebar 3. Under the "Published Applications" section, click **New Application** 4. Fill in your application details: * **Name**: Postman API Client * **Description**: Brief description of your application *(Optional)* * **Redirect URI**: `https://oauth.pstmn.io/v1/callback` 5. Click **Continue** 6. **Important**: Copy your Client ID and Client Secret immediately and store them securely > [!NOTE] > The redirect URI `https://oauth.pstmn.io/v1/callback` is Postman's default callback URL when using the "Authorize using browser" option. 2. Configure OAuth 2.0 in Postman [#2-configure-oauth-20-in-postman] Now you'll set up authentication in Postman: 1. Open Postman and create a new HTTP request 2. Set the request method to **POST** 3. Set the URL to `https://api.prisma.io/v1/projects` 4. Navigate to the **Authorization** tab 5. Set **Auth Type** to **OAuth 2.0** 6. Under **Configure New Token**, enter the following values: | Parameter | Value | | -------------------- | ------------------------------------ | | Token Name | Management API Token | | Grant Type | Authorization Code | | Callback URL | `https://oauth.pstmn.io/v1/callback` | | Authorize in Browser | `true` *(checked)* | | Auth URL | `https://auth.prisma.io/authorize` | | Access Token URL | `https://auth.prisma.io/token` | | Client ID | `your-client-id` | | Client Secret | `your-client-secret` | | Scope | `workspace:admin` | 7. Click **Get New Access Token** 8. A browser window will open and have you complete the authorization flow 9. Return to Postman and click **Use Token** to attach it to your request 10. Verify that your new token appears under **Current Token** at the top of the Authorization tab 3. Make your first request [#3-make-your-first-request] With authentication configured, you can now create a project: 1. In the request body, select **raw** and **JSON** format 2. Add the following JSON payload: ```json { "name": "My Postman Database", "region": "us-east-1" } ``` 3. Click **Send** You should receive a successful response confirming your project creation. Insomnia [#insomnia] Insomnia is an open-source API client with a clean interface for testing and debugging HTTP requests. Prerequisites [#prerequisites-1] Before you begin, make sure you have: * A [Prisma Console account](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) * [Insomnia installed](https://insomnia.rest/download/) 1. Create an OAuth2 Application [#1-create-an-oauth2-application-1] First, you'll need to register an OAuth2 application in Prisma Console: 1. Navigate to [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) and log in 2. Click the **🧩 Integrations** tab in the left sidebar 3. Under the "Published Applications" section, click **New Application** 4. Fill in your application details: * **Name**: Insomnia API Client * **Description**: Brief description of your application *(Optional)* * **Redirect URI**: `https://app.insomnia.rest/oauth/redirect` 5. Click **Continue** 6. **Important**: Copy your Client ID and Client Secret immediately and store them securely > [!NOTE] > Insomnia uses `https://app.insomnia.rest/oauth/redirect` as the default OAuth callback URL for local authentication flows. 2. Configure OAuth 2.0 in Insomnia [#2-configure-oauth-20-in-insomnia] Now you'll set up authentication in Insomnia: 1. Open Insomnia and create a new HTTP request 2. Set the request method to **POST** 3. Set the URL to `https://api.prisma.io/v1/projects` 4. Navigate to the **Auth** tab 5. Set the authentication type to **OAuth 2.0** 6. Under **Configuration**, enter the following values: | Parameter | Value | | -------------------------------- | ------------------------------------------ | | Grant Type | Authorization Code | | Authorization URL | `https://auth.prisma.io/authorize` | | Access Token URL | `https://auth.prisma.io/token` | | Client ID | `your-client-id` | | Client Secret | `your-client-secret` | | Redirect URL | `https://app.insomnia.rest/oauth/redirect` | | Scope *(Under Advanced Options)* | `workspace:admin` | 7. Click **Fetch Tokens** 8. A browser window will open and have you complete the authorization flow 9. Return to Insomnia and verify that the access token has been retrieved 10. The token will be automatically attached to your requests 3. Make your first request [#3-make-your-first-request-1] With authentication configured, you can now create a project: 1. Navigate to the **Body** tab and select **JSON** format 2. Add the following JSON payload: ```json { "name": "My Insomnia Database", "region": "us-east-1" } ``` 3. Click **Send** You should receive a successful response confirming your project creation. Yaak [#yaak] Yaak is a lightweight, open-source, and offline API client that works with Git. Prerequisites [#prerequisites-2] Before you begin, make sure you have: * A [Prisma Console account](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) * [Yaak installed](https://yaak.app) 1. Create an OAuth2 Application [#1-create-an-oauth2-application-2] First, you'll need to register an OAuth2 application in Prisma Console: 1. Navigate to [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) and log in 2. Click the **🧩 Integrations** tab in the left sidebar 3. Under the "Published Applications" section, click **New Application** 4. Fill in your application details: * **Name**: Yaak API Client * **Description**: Brief description of your application *(Optional)* * **Redirect URI**: `https://devnull.yaak.app/callback` 5. Click **Continue** 6. **Important**: Copy your Client ID and Client Secret immediately and store them securely > [!NOTE] > The redirect URI can be any valid URL. Yaak intercepts the OAuth callback regardless of the redirect URI, as long as it matches what's registered with the provider. 2. Configure OAuth 2.0 in Yaak [#2-configure-oauth-20-in-yaak] Now you'll set up authentication in Yaak: 1. Open Yaak and create a new HTTP request 2. Set the request method to **POST** 3. Set the URL to `https://api.prisma.io/v1/projects` 4. Navigate to the **Auth** tab 5. Set the authentication type to **OAuth 2.0** 6. Enter the following values: | Parameter | Value | | ----------------- | ----------------------------------- | | Grant Type | Authorization Code | | Authorization URL | `https://auth.prisma.io/authorize` | | Token URL | `https://auth.prisma.io/token` | | Client ID | `your-client-id` | | Client Secret | `your-client-secret` | | Redirect URL | `https://devnull.yaak.app/callback` | | Scope | `workspace:admin` | 7. Click **Get Token** 8. A browser window will open and have you complete the authorization flow 9. Return to Yaak and verify that the access token has been retrieved 10. The token will be automatically attached to your requests 3. Make your first request [#3-make-your-first-request-2] With authentication configured, you can now create a project: 1. Navigate to the **Body** tab and select **JSON** format 2. Add the following JSON payload: ```json { "name": "My Yaak Database", "region": "us-east-1" } ``` 3. Click **Send** You should receive a successful response confirming your project creation. ## Related pages - [`Authentication`](https://www.prisma.io/docs/management-api/authentication): Learn how to authenticate with the Prisma Management API using service tokens or OAuth 2.0 - [`Getting Started`](https://www.prisma.io/docs/management-api/getting-started): Get started with the Prisma Management API by creating your first project and database - [`Partner Integration`](https://www.prisma.io/docs/management-api/partner-integration): Build partner integrations that provision and transfer Prisma Postgres databases to users - [`SDK`](https://www.prisma.io/docs/management-api/sdk): A TypeScript SDK for the Prisma Data Platform Management API. Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh # Authentication (/docs/management-api/authentication) Location: Management API > Authentication The Management API supports two authentication methods: * **Service Tokens** - Simple bearer tokens for server-to-server integrations * **OAuth 2.0** - For user-facing applications requiring user consent Service tokens [#service-tokens] Service tokens are the simplest way to authenticate. They're ideal for scripts, CI/CD pipelines, and backend services. Creating a Service token [#creating-a-service-token] 1. Navigate to [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) and log in 2. Select your workspace 3. Go to **Settings → Service Tokens** 4. Click **New Service Token** 5. Copy the generated token immediately and store it securely Using a Service token [#using-a-service-token] Include the token in the `Authorization` header: ```bash curl -X GET "https://api.prisma.io/v1/workspaces" \ -H "Authorization: Bearer your-service-token" ``` Or with the SDK: ```typescript import { createManagementApiClient } from "@prisma/management-api-sdk"; const client = createManagementApiClient({ token: "your-service-token", }); ``` > [!WARNING] > Service tokens never expire > > Service tokens do not have an expiration date. While this provides convenience for long-running integrations, it also means these tokens require careful security management. OAuth 2.0 [#oauth-20] OAuth 2.0 is required for applications that act on behalf of users. The API uses OAuth 2.0 with PKCE for secure authentication. PKCE Support [#pkce-support] The OAuth implementation supports Proof Key for Code Exchange (PKCE) using the S256 code challenge method: * **Public clients** (no client secret): PKCE is **mandatory** * **Confidential clients** (with client secret): PKCE is **optional**, but if you start the flow with PKCE, it must be completed with PKCE This provides enhanced security, especially for mobile and single-page applications that cannot securely store client secrets. Creating an OAuth Application [#creating-an-oauth-application] 1. Navigate to [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) and log in 2. Click the **Integrations** tab in the left sidebar 3. Under "Published Applications", click **New Application** 4. Fill in your application details: * **Name**: Your application name * **Description**: Brief description *(optional)* * **Redirect URI**: Your callback URL (e.g., `https://your-app.com/auth/callback`) 5. Click **Continue** 6. Copy your **Client ID** and **Client Secret** immediately > [!NOTE] > Development redirect URIs > > For local development, the following redirect URIs are accepted with any port via wildcard matching: > > * `localhost` (e.g., `http://localhost:3000/callback`) > * `127.0.0.1` (e.g., `http://127.0.0.1:3000/callback`) > * `[::1]` - IPv6 loopback (e.g., `http://[::1]:3000/callback`) OAuth Endpoints [#oauth-endpoints] | Endpoint | URL | | ------------- | --------------------------------------------------------------- | | Authorization | `https://auth.prisma.io/authorize` | | Token | `https://auth.prisma.io/token` | | Discovery | `https://auth.prisma.io/.well-known/oauth-authorization-server` | > [!NOTE] > The discovery endpoint provides OAuth server metadata that can be used for automatic client configuration. Many OAuth libraries support automatic discovery using this endpoint. Available Scopes [#available-scopes] | Scope | Description | | ----------------- | ---------------------------------------------- | | `workspace:admin` | Full access to workspace resources | | `offline_access` | Enables refresh tokens for long-lived sessions | Token Lifetimes [#token-lifetimes] | Token Type | Expiration | | -------------- | ---------- | | Access tokens | 1 hour | | Refresh tokens | 90 days | OAuth Authorization Flow [#oauth-authorization-flow] 1. Redirect users to authorize [#1-redirect-users-to-authorize] Redirect users to the authorization endpoint with the following query parameters: | Parameter | Description | | --------------- | ------------------------------------------------------------------- | | `client_id` | Your OAuth application's Client ID | | `redirect_uri` | The callback URL where users will be redirected after authorization | | `response_type` | Must be `code` for the authorization code flow | | `scope` | Permissions to request (e.g., `workspace:admin`) | ``` https://auth.prisma.io/authorize?client_id=$CLIENT_ID&redirect_uri=$REDIRECT_URI&response_type=code&scope=workspace:admin ``` This will redirect the user to the Prisma authorization page where they can grant your application access to their workspace. 2. Receive the authorization code [#2-receive-the-authorization-code] After authorization, users are redirected to your callback URL with a `code` parameter: ``` https://your-app.com/callback?code=abc123... ``` 3. Exchange the code for an access token [#3-exchange-the-code-for-an-access-token] ```bash curl -X POST https://auth.prisma.io/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "client_id=$CLIENT_ID" \ -d "client_secret=$CLIENT_SECRET" \ -d "code=$CODE" \ -d "grant_type=authorization_code" \ -d "redirect_uri=$REDIRECT_URI" ``` The response will include an access token that can be used to make authenticated requests to the Management API: ```json { "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600 } ``` 4. Use the access token [#4-use-the-access-token] ```bash curl -X GET "https://api.prisma.io/v1/workspaces" \ -H "Authorization: Bearer $ACCESS_TOKEN" ``` Token Refresh [#token-refresh] If you requested the `offline_access` scope, you'll receive a refresh token. Use it to obtain new access tokens: ```bash curl -X POST https://auth.prisma.io/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "client_id=$CLIENT_ID" \ -d "client_secret=$CLIENT_SECRET" \ -d "refresh_token=$REFRESH_TOKEN" \ -d "grant_type=refresh_token" ``` > [!NOTE] > Refresh token rotation > > Refresh tokens use single-use rotation with replay attack detection. When you exchange a refresh token for a new access token, you'll receive a new refresh token in the response. The old refresh token is immediately invalidated. If an invalidated refresh token is used again, it indicates a potential security breach, and the system will revoke all tokens associated with that authorization. Using OAuth with the SDK [#using-oauth-with-the-sdk] The SDK handles the OAuth flow automatically. See the [SDK documentation](/management-api/sdk#oauth-authentication-flow) for implementation details. Using API Clients [#using-api-clients] You can also authenticate using popular API clients like Postman, Insomnia, or Yaak. See the [Using API Clients](/management-api/api-clients) guide for step-by-step instructions. ## Related pages - [`Getting Started`](https://www.prisma.io/docs/management-api/getting-started): Get started with the Prisma Management API by creating your first project and database - [`Partner Integration`](https://www.prisma.io/docs/management-api/partner-integration): Build partner integrations that provision and transfer Prisma Postgres databases to users - [`SDK`](https://www.prisma.io/docs/management-api/sdk): A TypeScript SDK for the Prisma Data Platform Management API. Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh - [`Using API Clients`](https://www.prisma.io/docs/management-api/api-clients): Use the Management API with popular API clients like Postman, Insomnia, and Yaak # Getting Started (/docs/management-api/getting-started) Location: Management API > Getting Started This guide walks you through setting up a basic TypeScript project that uses the Management API to create a new Prisma Console project with a Prisma Postgres database, and print out all connection details. You'll authenticate via a service token, set up your environment, and run a script to interact with the API. Prerequisites [#prerequisites] * Node.js and `npm` installed * A [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) account 1. Create a service token in Prisma Console [#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 [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api) 2. Navigate to the **Settings** page of your workspace and select **Service Tokens** 3. Click **New Service Token** 4. Copy and save the generated service token securely, you'll use it in step 2.2. 2. Set up your project directory [#2-set-up-your-project-directory] 2.1. Create a basic TypeScript project [#21-create-a-basic-typescript-project] Open your terminal and run the following commands: ```bash mkdir management-api-demo cd management-api-demo ``` Next, initialize npm and install dependencies required for using TypeScript: #### npm ```bash npm init npm install tsx typescript @types/node --save-dev touch index.ts ``` #### pnpm ```bash pnpm init pnpm add tsx typescript @types/node --save-dev touch index.ts ``` #### yarn ```bash yarn init yarn add tsx typescript @types/node --dev touch index.ts ``` #### bun ```bash bun init bun add tsx typescript @types/node --dev touch 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 [#22-configure-service-token-environment-variable] Create your `.env` file: ```bash touch .env ``` Next, install the [`dotenv`](https://github.com/motdotla/dotenv) library for loading environment variables from the `.env` file: #### npm ```bash npm install dotenv ``` #### pnpm ```bash pnpm add dotenv ``` #### yarn ```bash yarn add dotenv ``` #### bun ```bash bun add dotenv ``` Finally, add your service token (from step 1.) to `.env`: ```bash PRISMA_SERVICE_TOKEN="ey..." ``` 2.3. Install the axios library for HTTP request [#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 ```bash npm install axios ``` #### pnpm ```bash pnpm add axios ``` #### yarn ```bash yarn add axios ``` #### bun ```bash bun add 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 [#3-programmatically-create-a-new-project-with-a-database] Paste the following code into `index.ts`: ```ts import axios from "axios"; import dotenv from "dotenv"; // Load environment variables dotenv.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 script const 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: #### npm ```bash npx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### bun ```bash bunx --bun tsx index.ts ``` ```text no-copy 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 [#conclusion] You have now set up a TypeScript project that interacts with the 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. ## Related pages - [`Authentication`](https://www.prisma.io/docs/management-api/authentication): Learn how to authenticate with the Prisma Management API using service tokens or OAuth 2.0 - [`Partner Integration`](https://www.prisma.io/docs/management-api/partner-integration): Build partner integrations that provision and transfer Prisma Postgres databases to users - [`SDK`](https://www.prisma.io/docs/management-api/sdk): A TypeScript SDK for the Prisma Data Platform Management API. Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh - [`Using API Clients`](https://www.prisma.io/docs/management-api/api-clients): Use the Management API with popular API clients like Postman, Insomnia, and Yaak # Management API (/docs/management-api) Location: Management API Base URL [#base-url] ``` https://api.prisma.io/v1 ``` Append an endpoint path to construct the full URL. For example: `https://api.prisma.io/v1/projects/{projectId}` An interactive [OpenAPI 3.1 specification](https://api.prisma.io/v1/swagger-editor) is available for exploring endpoints and request/response formats. Getting Started [#getting-started] * **[Getting Started](/management-api/getting-started)** - Create your first project and database * **[Authentication](/management-api/authentication)** - OAuth 2.0 and service tokens setup * **[SDK](/management-api/sdk)** - TypeScript SDK with built-in OAuth and automatic token refresh * **[Using API Clients](/management-api/api-clients)** - Use with Postman, Insomnia, and Yaak * **[Partner Integration](/management-api/partner-integration)** - Build integrations that provision and transfer databases ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # Partner Integration (/docs/management-api/partner-integration) Location: Management API > Partner Integration This guide walks you through building a partner integration with the 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. > [!NOTE] > 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 [#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 you 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 authenticate provisioning calls with a service token for your workspace, and use OAuth 2 to obtain an access token for the user during the claim flow. * **Tokens**: There are two main types of tokens: * **Service token**: Issued to your partner integration, scoped to provision and manage databases on your own workspace. * **OAuth 2 access token**: Obtained via OAuth 2 when a user authenticates with your app; it is scoped to the user's workspace and used to transfer project/database ownership to that workspace. How to become a partner [#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**: You can obtain your OAuth credentials in the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api). See the [next section](#get-oauth-credentials) for details. For a complete list of available endpoints and details on request/response formats, see the [Prisma Management API documentation](/management-api). Get OAuth credentials [#get-oauth-credentials] To obtain a client ID and client secret, you need go through this flow: 1. Open the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=management-api). 2. Click the 🧩 **Integrations** tab in the sidenav. 3. In the **Published Applications** section, click **New Application** button to start the flow for creating a new OAuth app. 4. Enter a **Name**, **Description** and **Callback URL** for your OAuth app. 5. Click **Continue**. On the next screen, you can access and save the client ID and client secret for your OAuth app. Provisioning a database as a Partner [#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 service token to authenticate API requests from your backend. 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: ```ts 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 [#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 [#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 [#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: ```ts 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 [#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 [#3-finishing-the-claim-flow] Your backend should now: 1. **Exchange the authorization code for a user access token**: ```ts 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: ```ts const transferResponse = await fetch(`https://api.prisma.io/v1/projects/${project_id}/transfer`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${PRISMA_SERVICE_TOKEN}`, }, body: JSON.stringify({ recipientAccessToken: tokenData.access_token }), }); ``` If the transfer is successful, the database is now owned by the user's workspace. Conclusion [#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](/management-api). ## Related pages - [`Authentication`](https://www.prisma.io/docs/management-api/authentication): Learn how to authenticate with the Prisma Management API using service tokens or OAuth 2.0 - [`Getting Started`](https://www.prisma.io/docs/management-api/getting-started): Get started with the Prisma Management API by creating your first project and database - [`SDK`](https://www.prisma.io/docs/management-api/sdk): A TypeScript SDK for the Prisma Data Platform Management API. Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh - [`Using API Clients`](https://www.prisma.io/docs/management-api/api-clients): Use the Management API with popular API clients like Postman, Insomnia, and Yaak # SDK (/docs/management-api/sdk) Location: Management API > SDK Overview [#overview] The [`@prisma/management-api-sdk`](https://www.npmjs.com/package/@prisma/management-api-sdk) is a TypeScript SDK for the [Prisma Data Platform Management API](/management-api). Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh. Based on the [public OpenAPI 3.1 specification](https://api.prisma.io/v1/swagger-editor). Installation [#installation] #### npm ```bash npm install @prisma/management-api-sdk ``` #### pnpm ```bash pnpm add @prisma/management-api-sdk ``` #### yarn ```bash yarn add @prisma/management-api-sdk ``` #### bun ```bash bun add @prisma/management-api-sdk ``` Basic usage [#basic-usage] For usage with an existing access or [service token](/management-api/authentication#service-tokens). Making API calls [#making-api-calls] The client provides fully typed methods for all API endpoints: ```typescript import { createManagementApiClient } from "@prisma/management-api-sdk"; const client = createManagementApiClient({ token: "your-access-token", }); // List workspaces const { data: workspaces, error } = await client.GET("/v1/workspaces"); // Get a specific project const { data: project } = await client.GET("/v1/projects/{id}", { params: { path: { id: "project-id" } }, }); // Create a new project const { data: newProject } = await client.POST("/v1/workspaces/{workspaceId}/projects", { params: { path: { workspaceId: "workspace-id" } }, body: { name: "My New Project" }, }); // Create a new database const { data: newDatabase } = await client.POST("/v1/projects/{projectId}/databases", { params: { path: { projectId: "project-id" } }, body: { name: "my-new-db-instance", region: "us-east-1", isDefault: true, }, }); // Delete a database const { error: deleteError } = await client.DELETE("/v1/databases/{databaseId}", { params: { path: { databaseId: "database-id" } }, }); ``` Customizing the client [#customizing-the-client] You can override any `ClientOptions` from `openapi-fetch`, including `baseUrl`, `headers`, and other fetch options: ```typescript import { createManagementApiClient } from "@prisma/management-api-sdk"; // Override baseUrl and add custom headers const client = createManagementApiClient({ token: "your-access-token", baseUrl: "https://api.example.com", headers: { "X-Custom-Header": "value", }, }); ``` > [!NOTE] > If you provide both `token` and `headers.Authorization`, the `headers.Authorization` takes precedence. The `baseUrl` defaults to `https://api.prisma.io` if not provided. Advanced usage [#advanced-usage] For applications that need [OAuth authentication](#oauth-authentication-flow), automatic token refresh, and token storage management, use the full SDK. OAuth authentication flow [#oauth-authentication-flow] The SDK uses OAuth 2.0 with PKCE for secure authentication. The flow is stateless - you're responsible for storing the `state` and `verifier` between the login URL generation and callback handling. 1. Create the SDK instance [#1-create-the-sdk-instance] ```typescript import { createManagementApiSdk, type TokenStorage } from "@prisma/management-api-sdk"; // Implement token storage for your environment const tokenStorage: TokenStorage = { async getTokens() { const stored = localStorage.getItem("prisma-tokens"); return stored ? JSON.parse(stored) : null; }, async setTokens(tokens) { localStorage.setItem("prisma-tokens", JSON.stringify(tokens)); }, async clearTokens() { localStorage.removeItem("prisma-tokens"); }, }; // Create the SDK instance const api = createManagementApiSdk({ clientId: "your-oauth-client-id", redirectUri: "https://your-app.com/auth/callback", tokenStorage, }); ``` 2. Initiate login [#2-initiate-login] Generate the OAuth login URL. The returned `state` and `verifier` must be stored (e.g., in a session or cookie) for use when handling the callback: ```typescript const { url, state, verifier } = await api.getLoginUrl({ scope: "workspace:admin offline_access", additionalParams: { utm_source: "my-app", utm_medium: "login", }, }); // Store state and verifier for the callback (e.g., in session storage) sessionStorage.setItem("oauth-state", state); sessionStorage.setItem("oauth-verifier", verifier); // Redirect user to the login URL window.location.href = url; ``` 3. Handle the callback [#3-handle-the-callback] When the user is redirected back to your app, retrieve the stored `state` and `verifier` and pass them to `handleCallback`. On success, tokens are automatically stored via your `tokenStorage` implementation: ```typescript // In your callback route handler const callbackUrl = window.location.href; // Retrieve the stored values const expectedState = sessionStorage.getItem("oauth-state"); const verifier = sessionStorage.getItem("oauth-verifier"); // Clean up stored values sessionStorage.removeItem("oauth-state"); sessionStorage.removeItem("oauth-verifier"); try { await api.handleCallback({ callbackUrl, verifier, expectedState, }); // Tokens are now stored in tokenStorage and the client is ready to use console.log("Login successful!"); } catch (error) { if (error instanceof AuthError) { console.error("Authentication failed:", error.message); } } ``` 4. Make API calls [#4-make-api-calls] The client automatically includes authentication headers and refreshes tokens when they expire. Use `api.client` with the same methods shown in [Basic usage](#making-api-calls). 5. Logout [#5-logout] ```typescript await api.logout(); // Clears stored tokens ``` Token storage interface [#token-storage-interface] Implement this interface to handle token persistence in your environment: ```typescript interface TokenStorage { /** Provide the stored tokens to the SDK */ getTokens(): Promise; /** Store new or updated tokens when the SDK has successfully authenticated or refreshed tokens */ setTokens(tokens: Tokens): Promise; /** Clear the tokens when the user logs out or the refresh token is invalid */ clearTokens(): Promise; } type Tokens = { /** The workspace ID that these tokens are valid for (extracted from the access token) */ workspaceId: string; /** The access token for API requests */ accessToken: string; /** The refresh token for obtaining new access tokens (only present if scope includes 'offline_access') */ refreshToken?: string; }; ``` Example: VS Code Extension [#example-vs-code-extension] ```typescript const tokenStorage: TokenStorage = { async getTokens() { const workspaceId = await context.secrets.get("workspaceId"); const accessToken = await context.secrets.get("accessToken"); const refreshToken = await context.secrets.get("refreshToken"); if (!workspaceId || !accessToken) return null; return { workspaceId, accessToken, refreshToken: refreshToken || undefined }; }, async setTokens(tokens) { await context.secrets.store("workspaceId", tokens.workspaceId); await context.secrets.store("accessToken", tokens.accessToken); if (tokens.refreshToken) { await context.secrets.store("refreshToken", tokens.refreshToken); } }, async clearTokens() { await context.secrets.delete("workspaceId"); await context.secrets.delete("accessToken"); await context.secrets.delete("refreshToken"); }, }; ``` Example: Node.js CLI [#example-nodejs-cli] ```typescript import { readFile, writeFile, unlink } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; const tokenPath = join(homedir(), ".prisma", "credentials.json"); const tokenStorage: TokenStorage = { async getTokens() { try { const data = await readFile(tokenPath, "utf-8"); return JSON.parse(data); } catch { return null; } }, async setTokens(tokens) { await writeFile(tokenPath, JSON.stringify(tokens, null, 2)); }, async clearTokens() { await unlink(tokenPath).catch(() => {}); }, }; ``` For other environments: * **VS Code extensions** - Use `context.secrets` for secure storage * **Stateless web servers** - Store PKCE state/verifier in encrypted cookies or a database Automatic token refresh [#automatic-token-refresh] The SDK automatically handles token refresh when a refresh token is available (requires `offline_access` scope): * When a request returns 401, the SDK refreshes the access token using the refresh token * Concurrent requests during refresh are queued and resolved once refresh completes * If refresh fails due to an invalid refresh token, tokens are cleared and `AuthError` is thrown with `refreshTokenInvalid: true` * If no refresh token is available, an `AuthError` is thrown with the message "No refresh token available. Please log in again." API reference [#api-reference] createManagementApiClient(options) [#createmanagementapiclientoptions] Creates a raw API client without authentication handling. Useful if you want to manage authentication yourself or use a service token. **Parameters:** * `options.token?: string` - Access token (automatically converted to `Authorization: Bearer ${token}` header) * `options.baseUrl?: string` - Base URL for API requests (defaults to `https://api.prisma.io`) * `options.headers?: Record` - Additional headers * Other `ClientOptions` from `openapi-fetch` are also supported **Returns:** A typed API client for making requests. createManagementApiSdk(config) [#createmanagementapisdkconfig] Creates a Management API SDK instance with OAuth authentication and automatic token refresh. **Parameters:** ```typescript type ManagementApiClientConfig = { // Required clientId: string; // OAuth client ID redirectUri: string; // OAuth redirect URI tokenStorage: TokenStorage; // Optional (with defaults) apiBaseUrl?: string; // Default: 'https://api.prisma.io' authBaseUrl?: string; // Default: 'https://auth.prisma.io' }; ``` **Returns:** An object with: * `client` - The typed API client for making requests * `getLoginUrl(options)` - Generate OAuth login URL with specified scope * `handleCallback(options)` - Handle OAuth callback and store tokens via `tokenStorage` * `logout()` - Clear stored tokens Error handling [#error-handling] The SDK exports two error classes: AuthError [#autherror] Thrown for authentication-related errors: * OAuth callback errors (includes `error_description` when available) * Invalid or missing tokens * Token refresh failures ```typescript import { AuthError } from "@prisma/management-api-sdk"; try { await api.handleCallback({ callbackUrl, verifier, expectedState }); } catch (error) { if (error instanceof AuthError) { if (error.refreshTokenInvalid) { // Token is invalid/expired, user needs to log in again const { url } = await api.getLoginUrl({ scope: "workspace:admin offline_access" }); // redirect to url... } else { // Other auth errors (e.g., "access_denied: User cancelled") console.error("Auth error:", error.message); } } } ``` FetchError [#fetcherror] Thrown for network-related errors. Includes the original error as `cause` for debugging: ```typescript import { FetchError } from "@prisma/management-api-sdk"; try { const { data } = await client.GET("/v1/workspaces"); } catch (error) { if (error instanceof FetchError) { console.error("Network error:", error.message); console.error("Cause:", error.cause); // Original error for debugging } } ``` TypeScript types [#typescript-types] The SDK exports all API types generated from the OpenAPI spec: ```typescript import type { paths, components } from "@prisma/management-api-sdk"; // Access response types type Workspace = components["schemas"]["Workspace"]; type Project = components["schemas"]["Project"]; ``` ## Related pages - [`Authentication`](https://www.prisma.io/docs/management-api/authentication): Learn how to authenticate with the Prisma Management API using service tokens or OAuth 2.0 - [`Getting Started`](https://www.prisma.io/docs/management-api/getting-started): Get started with the Prisma Management API by creating your first project and database - [`Partner Integration`](https://www.prisma.io/docs/management-api/partner-integration): Build partner integrations that provision and transfer Prisma Postgres databases to users - [`Using API Clients`](https://www.prisma.io/docs/management-api/api-clients): Use the Management API with popular API clients like Postman, Insomnia, and Yaak # Prisma ORM (/docs/orm) Location: Prisma ORM Prisma ORM is [open-source](https://github.com/prisma/prisma) and consists of: * [**Prisma Client**](/orm/prisma-client): Auto-generated, type-safe **ORM interface** * [**Prisma Migrate**](/orm/prisma-migrate): Database migration system * [**Prisma Studio**](https://www.prisma.io/studio): GUI to view and edit your data Prisma Client works with any Node.js or TypeScript backend, whether you're deploying to traditional servers, serverless functions, or microservices. Why Prisma ORM [#why-prisma-orm] Traditional database tools force a tradeoff between **productivity** and **control**. Raw SQL gives full control but is error-prone and lacks type safety. Traditional ORMs improve productivity but abstract too much, leading to the [object-relational impedance mismatch](https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch) and performance pitfalls like the n+1 problem. Prisma takes a different approach: * **Type-safe queries** validated at compile time with full autocompletion * **Thinking in objects** without the complexity of mapping relational data * **Plain JavaScript objects** returned from queries, not complex model instances * **Single source of truth** in the Prisma schema for database and application models * **Healthy constraints** that prevent common pitfalls and anti-patterns When to use Prisma [#when-to-use-prisma] **Prisma is a good fit if you:** * Build server-side applications (REST, GraphQL, gRPC, serverless) * Value type safety and developer experience * Work in a team and want a clear, declarative schema * Need migrations, querying, and data modeling in one toolkit **Consider alternatives if you:** * Need full control over every SQL query (use raw SQL drivers) * Want a no-code backend (use a BaaS like Supabase or Firebase) * Need an auto-generated CRUD GraphQL API (use Hasura or PostGraphile) How it works [#how-it-works] 1. Define your schema [#1-define-your-schema] The [Prisma schema](/orm/prisma-schema/overview) defines your data models and database connection: ```prisma datasource db { provider = "postgresql" } generator client { provider = "prisma-client" output = "./generated" } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` 2. Configure your connection [#2-configure-your-connection] Create a `prisma.config.ts` file in your project root: ```ts title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 3. Run migrations [#3-run-migrations] Use [Prisma Migrate](/orm/prisma-migrate) to create and apply migrations: #### npm ```bash npx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### bun ```bash bunx --bun prisma migrate dev ``` Or [introspect](/orm/prisma-schema/introspection) an existing database: #### npm ```bash npx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### bun ```bash bunx --bun prisma db pull ``` 4. Query with Prisma Client [#4-query-with-prisma-client] Generate and use the type-safe client: #### npm ```bash npm install @prisma/client npx prisma generate ``` #### pnpm ```bash pnpm add @prisma/client pnpm dlx prisma generate ``` #### yarn ```bash yarn add @prisma/client yarn dlx prisma generate ``` #### bun ```bash bun add @prisma/client bun x prisma generate ``` ```ts import { PrismaClient } from "./generated/client"; // Import the driver adapter for your specific database (example uses PostgreSQL) import { PrismaPg } from "@prisma/adapter-pg"; // Initialize the adapter according to your driver's requirements const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }); // Pass the adapter instance to PrismaClient const prisma = new PrismaClient({ adapter }); // Find all users with their posts const users = await prisma.user.findMany({ include: { posts: true }, }); // Create a user with a post const user = await prisma.user.create({ data: { email: "alice@prisma.io", posts: { create: { title: "Hello World" }, }, }, }); ``` > [!NOTE] > Prisma 7 Connection Requirements [#prisma-7-connection-requirements] > > Starting with **Prisma 7**, providing a [driver adapter](/orm/core-concepts/supported-databases/database-drivers) is mandatory for direct database connections. This change standardizes database connectivity across Node.js, Serverless, and Edge environments. > > If you use Prisma Accelerate, instantiate Prisma Client with `accelerateUrl` and the Accelerate extension instead of a driver adapter. > > To ensure compatibility: > > * **Install an adapter:** Use the specific package for your database (e.g., `@prisma/adapter-pg`, `@prisma/adapter-mysql`, etc.). > * **Enable ESM:** Your `package.json` must include `"type": "module"`. > > For detailed instructions, see the [V7 Upgrade Guide](/guides/upgrade-prisma-orm/v7). Next steps [#next-steps] * [**Prisma schema**](/orm/prisma-schema/overview) - Learn the schema language * [**Prisma Client**](/orm/prisma-client) - Explore the query API ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # Best Postgres for AI apps (/docs/postgres/best-postgres-for-ai-apps) Location: Postgres > Best Postgres for AI apps AI apps have a different database profile than traditional web apps. Requests burst unpredictably, the same embeddings get retrieved repeatedly, inference runs at the edge, and agents increasingly need direct database access. Most managed Postgres services weren't designed with those patterns in mind. Here's how Prisma Postgres handles them. Built-in connection pooling [#built-in-connection-pooling] Serverless inference endpoints open a new database connection per invocation. At any meaningful load, that exhausts your Postgres connection limit fast. Prisma Postgres includes connection pooling by default — no pgBouncer to configure, no sidecar to run. Your connection string already points to the pooler. Nothing extra to set up. Query caching for RAG pipelines [#query-caching-for-rag-pipelines] Users asking similar questions trigger semantically similar retrievals. Without caching, every request is a full round-trip to the database. Prisma Postgres includes globally distributed query caching via Prisma Accelerate — opt in per query: ```ts title="app.ts" const chunks = await prisma.documentChunk.findMany({ where: { documentId, similarity: { gte: 0.8 } }, cacheStrategy: { ttl: 60, swr: 30 }, }) ``` Repeated retrievals are served from edge nodes close to your users instead of from the database region. Edge-native connectivity [#edge-native-connectivity] Standard Postgres TCP drivers don't work in Cloudflare Workers, Vercel Edge Functions, or Deno Deploy. Prisma Postgres ships `@prisma/ppg`, a serverless driver that connects over HTTP — no workarounds needed. See [Serverless driver](/postgres/database/serverless-driver) for setup. pgvector for embeddings [#pgvector-for-embeddings] Prisma Postgres supports the `pgvector` extension for storing and querying vector embeddings natively in Postgres. You can keep your embeddings alongside your application data without a separate vector store. See [Postgres extensions](/postgres/database/postgres-extensions) for how to enable it. MCP server for agent workflows [#mcp-server-for-agent-workflows] AI agents (Claude, Cursor, or custom) can connect to Prisma Postgres via the Prisma MCP server to introspect schemas, run queries, apply migrations, and manage environments — without raw SQL access. See [Prisma MCP server](/ai/tools/mcp-server) for setup. At a glance [#at-a-glance] | | Prisma Postgres | Neon | Supabase | | ------------------------------- | --------------------------- | -------------------------------- | ------------------------------- | | **Built-in connection pooling** | Yes, included by default | Yes, PgBouncer-compatible | Yes, Supavisor pooler | | **Query-level caching** | Yes — global via Accelerate | No native query cache | No native query cache | | **Serverless / edge driver** | Yes — `@prisma/ppg` | Yes — `@neondatabase/serverless` | Partial, requires configuration | | **pgvector support** | Yes | Yes | Yes | | **MCP server** | Yes — official first-party | Yes — Neon MCP server | Yes — Supabase MCP server | | **Database branching** | No | Yes | Limited | | **Free tier** | Yes | Yes | Yes | The query caching row is the differentiator for AI workloads. If you're building RAG pipelines or anything with repeated retrieval patterns, that column matters. Get started [#get-started] #### npm ```bash npm create prisma@latest ``` #### pnpm ```bash pnpm create prisma@latest ``` #### yarn ```bash yarn create prisma@latest ``` #### bun ```bash bun create prisma@latest ``` Or provision from the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=postgres) and grab your connection string. * [Connect to Prisma Postgres](/postgres/database/connecting-to-your-database) * [Enable query caching](/accelerate/caching) * [Use the serverless driver at the edge](/postgres/database/serverless-driver) * [Enable pgvector](/postgres/database/postgres-extensions) * [Set up the Prisma MCP server](/ai/tools/mcp-server) ## Related pages - [`create-db`](https://www.prisma.io/docs/postgres/npx-create-db): Learn how to provision temporary Prisma Postgres databases with create-db - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Error reference`](https://www.prisma.io/docs/postgres/error-reference): Error reference documentation for Prisma Postgres - [`Import from existing database`](https://www.prisma.io/docs/postgres/import-from-existing-database): Choose the right path to import data from PostgreSQL or MySQL into Prisma Postgres. - [`Prisma Postgres FAQ`](https://www.prisma.io/docs/postgres/faq): Common questions and answers about Prisma Postgres # Error reference (/docs/postgres/error-reference) Location: Postgres > Error reference When working with Prisma Postgres, you may encounter errors often highlighted by specific error codes during development and operations. It is important to understand the meaning of these errors, why they occur, and how to resolve them in order to ensure the smooth operation of your applications. This guide aims to provide insights and steps to troubleshoot specific error codes encountered with Prisma Postgres. P6009 (ResponseSizeLimitExceeded) [#p6009-responsesizelimitexceeded] This error is triggered when the response size from a database query exceeds the configured query response size limit. We've implemented this restriction to safeguard your application performance, as retrieving data over `5MB` can significantly slow down your application due to multiple network layers. Typically, transmitting more than `5MB` of data is common when conducting ETL (Extract, Transform, Load) operations. However, for other scenarios such as transactional queries, real-time data fetching for user interfaces, bulk data updates, or aggregating large datasets for analytics outside of ETL contexts, it should generally be avoided. These use cases, while essential, can often be optimized to work within the configured query response size limit, ensuring smoother performance and a better user experience. Possible causes for P6009 [#possible-causes-for-p6009] Transmitting images/files in response [#transmitting-imagesfiles-in-response] This error may arise if images or files stored within your table are being fetched, resulting in a large response size. Storing assets directly in the database is generally discouraged because it significantly impacts database performance and scalability. In addition to performance, it makes database backups slow and significantly increases the cost of storing routine backups. **Suggested solution:** Configure the query response size limit to be larger. If the limit is still exceeded, consider storing the image or file in a BLOB store like [Cloudflare R2](https://developers.cloudflare.com/r2/), [AWS S3](https://aws.amazon.com/pm/serv-s3/), or [Cloudinary](https://cloudinary.com/). These services allow you to store assets optimally and return a URL for access. Instead of storing the asset directly in the database, store the URL, which will substantially reduce the response size. Over-fetching of data [#over-fetching-of-data] In certain cases, a large number of records or fields are unintentionally fetched, which results in exceeding the configured query response size limit. This could happen when [the `where` clause](/orm/reference/prisma-client-reference#where) in the query is incorrect or entirely missing. **Suggested solution:** Configure the query response size limit to be larger. If the limit is still exceeded, double-check that the `where` clause is filtering data as expected. To prevent fetching too many records, consider using [pagination](/orm/prisma-client/queries/pagination). Additionally, use the [`select`](/orm/reference/prisma-client-reference#select) clause to return only the necessary fields, reducing the response size. Fetching a large volume of data [#fetching-a-large-volume-of-data] In many data processing workflows, especially those involving ETL (Extract-Transform-Load) processes or scheduled CRON jobs, there's a need to extract large amounts of data from data sources (like databases, APIs, or file systems) for analysis, reporting, or further processing. If you are running an ETL/CRON workload that fetches a huge chunk of data for analytical processing then you might run into this limit. **Suggested solution:** Configure the query response size limit to be larger. If the limit is exceeded, consider splitting your query into batches. This approach ensures that each batch fetches only a portion of the data, preventing you from exceeding the size limit for a single operation. P6004 (QueryTimeout) [#p6004-querytimeout] This error occurs when a database query fails to return a response within the configured query timeout limit. The query timeout limit includes the duration of waiting for a connection from the pool, network latency to the database, and the execution time of the query itself. We enforce this limit to prevent unintentional long-running queries that can overload system resources. > [!NOTE] > The time for Prisma Postgres's cross-region networking is excluded from the configured query timeout limit. Possible causes for P6004 [#possible-causes-for-p6004] This error could be caused by numerous reasons. Some of the prominent ones are: High traffic and insufficient connections [#high-traffic-and-insufficient-connections] If the application is receiving very high traffic and there are not a sufficient number of connections available to the database, then the queries would need to wait for a connection to become available. This situation can lead to queries waiting longer than the configured query timeout limit for a connection, ultimately triggering a timeout error if they do not get serviced within this duration. **Suggested solution**: Review and possibly increase the `connection_limit` specified in the connection string parameter when setting up Accelerate in a platform environment. This limit should align with your database's maximum number of connections. By default, the connection limit is set to 10 unless a different `connection_limit` is specified in your database connection string. Long-running queries [#long-running-queries] Queries may be slow to respond, hitting the configured query timeout limit even when connections are available. This could happen if a very large amount of data is being fetched in a single query or if appropriate indexes are missing from the table. **Suggested solution**: Configure the query timeout limit to be larger. If the limit is exceeded, identify the slow-running queries and fetch only the necessary data. Use the `select` clause to retrieve specific fields and avoid fetching unnecessary data. Additionally, consider adding appropriate indexes to improve query efficiency. You might also isolate long-running queries into separate environments to prevent them from affecting transactional queries. Database resource contention [#database-resource-contention] A common yet challenging issue is when other services operating on the same database perform heavy analytics or data processing tasks, significantly consuming database resources. These operations can monopolize database connections and processing power, leading to a scenario where even simple queries cannot be executed in a timely manner. This "busy" or "noisy" database environment can cause queries that are typically fast to run slowly or even timeout, particularly during periods of high activity from other services. Users often rely on CPU and memory usage metrics to gauge database load, which can be misleading. While these are important indicators, they might not fully represent the database's operational state. Direct metrics like the number of reads, writes, and wait times offer a clearer view of the database's performance and should be monitored closely. A noticeable degradation in these metrics, especially in the absence of changes to the queries or data model, suggests that external pressures are affecting database performance. **Suggested solution**: If normally quick queries are intermittently slow or timing out without any modifications to them, it's probable that competing queries are exerting pressure on the same database tables. To diagnose this, adopt monitoring tools or leverage your database's inherent capabilities to observe reads, writes, and wait times. Such monitoring will unveil activity patterns or spikes that align with the observed performance dips. Moreover, it's crucial to periodically scrutinize and refine essential queries and verify that tables are properly indexed. This proactive approach minimizes the vulnerability of these queries to slowdowns caused by competing workloads. P6008 (ConnectionError|EngineStartError) [#p6008-connectionerrorenginestarterror] This error indicates that Prisma ORM cannot establish a connection to your Prisma Postgres database, potentially due to several reasons. Possible causes for P6008 [#possible-causes-for-p6008] Unreachable Database Host/Port [#unreachable-database-hostport] If the database's server address (hostname) and port are incorrect or unreachable then you may encounter this error. **Suggested solution:** Verify the hostname/port of the database connection string that was provided while creating the project. Additionally, attempt to connect to the database using a Database GUI tool (e.g., [Prisma Studio](https://www.prisma.io/studio), [TablePlus](https://tableplus.com/), or [DataGrip](https://www.jetbrains.com/datagrip/)) for further investigation. Incorrect username/password/database name [#incorrect-usernamepassworddatabase-name] This error can happen when the wrong credentials are provided, preventing it from establishing a connection to your database. **Suggested solution:** Verify the correctness of your database's username, password, and name in the connection string provided to Prisma Postgres. Ensure that these credentials match those required by your database. Testing the connection using a direct database GUI tool can also help in confirming if the provided credentials are correct. P5011 (TooManyRequests) [#p5011-toomanyrequests] This error occurs when Prisma Postgres detects a high volume of requests that surpasses allowable thresholds. It acts as a protective measure to safeguard both Prisma Postgres and your underlying database from excessive load. Possible causes for P5011 [#possible-causes-for-p5011] Aggressive retry loops [#aggressive-retry-loops] If your application retries queries immediately or with minimal delay, especially after receiving certain errors, the rapid accumulation of requests can surpass the threshold. **Suggested solution:** * Implement an exponential backoff strategy. Rather than retrying immediately or with a fixed delay, gradually increase the delay period after each failed attempt. Sudden traffic spikes [#sudden-traffic-spikes] Unpredicted traffic surges (for example, during product launches, flash sales, or viral growth events) can cause the threshold to be met and result into `P5011`. **Suggested solution:** * Monitor traffic and resource usage. If you anticipate a surge, please contact [support](/console/more/support) for capacity planning and potential configuration adjustments. Prolonged or planned high workloads [#prolonged-or-planned-high-workloads] Certain processes, such as bulk data imports, ETL operations, or extended CRON jobs, can generate continuous high query volume over time. **Suggested solution:** * Use batching or chunking techniques to break large operations into smaller parts. * Establish throttling or scheduling to distribute the load more evenly. ## Related pages - [`Best Postgres for AI apps`](https://www.prisma.io/docs/postgres/best-postgres-for-ai-apps): Why Prisma Postgres works well for AI and LLM workloads — built-in pooling, query caching, edge connectivity, pgvector, and MCP support. - [`create-db`](https://www.prisma.io/docs/postgres/npx-create-db): Learn how to provision temporary Prisma Postgres databases with create-db - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Import from existing database`](https://www.prisma.io/docs/postgres/import-from-existing-database): Choose the right path to import data from PostgreSQL or MySQL into Prisma Postgres. - [`Prisma Postgres FAQ`](https://www.prisma.io/docs/postgres/faq): Common questions and answers about Prisma Postgres # Prisma Postgres FAQ (/docs/postgres/faq) Location: Postgres > Prisma Postgres FAQ Common questions about how Prisma Postgres works, how queries are billed, and how it integrates with the Prisma ORM. General [#general] Can I use Prisma Postgres without Prisma ORM? [#can-i-use-prisma-postgres-without-prisma-orm] Yes, you can use Prisma Postgres with any database library or tool via a [direct connection](/postgres/database/connection-pooling). You can find examples of using Prisma Postgres with various ORMs below: * [Prisma ORM](https://github.com/prisma/prisma-examples/tree/latest/databases/prisma-postgres) * [Drizzle](https://github.com/prisma/prisma-examples/tree/latest/databases/drizzle-prisma-postgres) * [Kysely](https://github.com/prisma/prisma-examples/tree/latest/databases/kysely-prisma-postgres) * [TypeORM](https://github.com/prisma/prisma-examples/tree/latest/databases/typeorm-prisma-postgres) How do I switch from GitHub login to email and password login? [#how-do-i-switch-from-github-login-to-email-and-password-login] If you previously signed up using GitHub and want to switch to email and password login, follow these steps: 1. Verify Your GitHub Email Address * Check the primary email address associated with your GitHub account (e.g., from your GitHub profile or notification settings). 2. Create a New Email/Password Account * Go to the email/password sign-up page. * Use the *same email address* linked to your GitHub account to create the new account. * Our system will automatically connect your new email/password account to your existing data. 3. Test Your Login * Log out and try logging in with your email and the password you just created. If you encounter any issues, please contact our support team for help linking your accounts. VS Code does not recognize the $extends method [#vs-code-does-not-recognize-the-extends-method] If you add the Prisma Client extension for Accelerate to an existing project that is currently open in VS Code, the editor might not immediately recognize the `$extends` method. This might be an issue with the TypeScript server not yet recognizing the regenerated Prisma Client. To resolve this, you need to restart TypeScript. 1. In VS Code, open the Command Palette. You can do so when you press F1 or select **View** > **Command Palette**. 2. Enter `typescript` and select and run the **TypeScript: Restart TS server** command. VS Code should now recognize the `$extends` method. What regions is Prisma Postgres available in? [#what-regions-is-prisma-postgres-available-in] Prisma Postgres is currently available in the following regions: | Region Code | Location | | ---------------- | -------------- | | `us-west-1` | San Francisco | | `us-east-1` | North Virginia | | `eu-west-3` | Paris | | `eu-central-1` | Frankfurt | | `ap-northeast-1` | Tokyo | | `ap-southeast-1` | Singapore | We're continuously working to expand regional support. If you'd like to request a specific region, reach out to us via [Discord](https://pris.ly/discord). Pricing [#pricing] Prisma Postgres bills based on *operations* and *storage* consumed. Visit the [pricing page](https://www.prisma.io/pricing) for details and our [blog post explaining operations-based billing](https://www.prisma.io/blog/operations-based-billing) for a detailed explanation on what an operation is and how this pricing model works. What is an operation? [#what-is-an-operation] An operation is counted each time you interact with your database. Read, write, simple or complex. It all simply counts as one. An operation can be: * a Prisma ORM query (when using Prisma ORM) * a SQL query (when using a [direct connection](/postgres/database/connecting-to-your-database)) Does query execution time affect pricing in Prisma Postgres? [#does-query-execution-time-affect-pricing-in-prisma-postgres] No, cost for Prisma Postgres is based solely on the *number of operations*, not the amount of compute required to execute them. Whether a query takes 10ms or 10sec to execute, its pricing impact remains the same. How does pricing differ between using Prisma ORM and direct TCP connections? [#how-does-pricing-differ-between-using-prisma-orm-and-direct-tcp-connections] The fundamental principle of operations-based pricing remains the same for Prisma ORM and [direct connections](/postgres/database/connecting-to-your-database). However, depending on whether you use Prisma ORM or direct SQL to interact with your database, an operation is something different: * when using Prisma ORM: a query sent with Prisma Client (e.g. `prisma.user.findMany()`) * when using another tool: a SQL query sent via the direct connection (e.g. `SELECT * from "User"`) Note that a single Prisma ORM query may translate into multiple SQL queries which may make using Prisma ORM more economical than direct SQL. Do read and write queries cost the same? [#do-read-and-write-queries-cost-the-same] Yes, read and write queries are counted equally as *operations* and are billed the same way. Does a SELECT 1 query count as a billable operation? [#does-a-select-1-query-count-as-a-billable-operation] Yes, a query like `SELECT 1` counts as an operation and will be billed accordingly (even if no actual data is accessed in the query). How can I estimate the number of operations in Prisma ORM? [#how-can-i-estimate-the-number-of-operations-in-prisma-orm] You can estimate your operation usage in Prisma ORM by integrating an application performance monitoring tool like Prometheus. What strategies can I use to optimize cost per operation? [#what-strategies-can-i-use-to-optimize-cost-per-operation] Prisma Postgres bills by operation. The more you can perform using a single operation, the lower your bill. Some tips to reduce the number of operations: * [**Batch your writes**](/orm/prisma-client/queries/transactions#bulk-operations) with `createMany`, `updateMany`, or `deleteMany` instead of looping over single-row calls. ```ts // One operation, three users await prisma.user.createMany({ data: [{ name: "Alice" }, { name: "Bob" }, { name: "Carol" }], }); ``` * **Use nested-relation helpers** such as [`connectOrCreate`](/orm/reference/prisma-client-reference#connectorcreate) or [`set`](/orm/reference/prisma-client-reference#set) to create or link related records in a single operation. ```ts // Post and (if needed) its author, all in one request await prisma.post.create({ data: { title: "Hello World", author: { connectOrCreate: { where: { email: "alice@example.com" }, create: { name: "Alice", email: "alice@example.com" }, }, }, }, }); ``` * **Prefer regular (array) [transactions](/orm/prisma-client/queries/transactions#transaction-api) over [interactive transactions](/orm/prisma-client/queries/transactions#interactive-transactions)** when the individual queries don't depend on each other. ```ts // Interactive transaction: counted as 2 operations await prisma.$transaction(async (tx) => { await tx.user.create({ data: { name: "Alice" } }); await tx.post.create({ data: { title: "Hello", authorId: 1 } }); }); // Array transaction: counted as 1 operation await prisma.$transaction([ prisma.user.create({ data: { name: "Alice" } }), prisma.post.create({ data: { title: "Hello", authorId: 1 } }), ]); ``` If a later query needs the result of an earlier one (for example, you need the user ID you just created), stick with an interactive transaction for correctness. Otherwise, batching and array transactions let you collapse multiple queries into a single billed operation, keeping both your operation count, and your cost down. Is there a sample workload to estimate my expected charges? [#is-there-a-sample-workload-to-estimate-my-expected-charges] We will demonstrate three example workloads and estimate bills for small, medium, and large workloads. Each combine a realistic number of monthly active users (MAUs), a typical level of daily activity per user, and a rounded storage footprint. We will use the following equations to estimate the monthly bill: ``` total_ops = MAUs x actions_per_user_per_day x 30 billable_ops = total_ops - included_ops_for_plan ops_cost = (billable_ops ÷ 1_000_000) x plan_rate billable_storage_GB = storage_used_GB - free_storage_for_plan storage_cost = billable_storage_GB x storage_rate_for_plan total_monthly_cost = ops_cost + storage_cost + base_plan_fee ``` > [!NOTE] > You can use your own MAU count, activity level, and storage used to project costs on any plan using the equations above. We will associate each workload with a paid plan and its corresponding pricing details, for example, the **Starter plan** for the small workload, the **Pro plan** for the medium workload, and the **Business plan** for the large workload. Then we will apply the equations to the example workloads to generate a rough estimate of a monthly bill. For example: > [!NOTE] > Pricing details > > Here are the details for each pricing plan: > > * **Starter plan** - $8 per million operations > * Base plan fee - $10 per month > * Included operations - 1,000,000 > * Storage - 10 GB free then $2 per additional GB > * **Pro plan** - $2 per million operations > * Base plan fee - $49.00 per month > * Included operations - 10,000,000 > * Storage - 50 GB free then $1.5 per additional GB > * **Business plan** - $1 per million operations > * Base plan fee - $129.00 per month > * Included operations - 50,000,000 > * Storage - 100 GB free then $1 per additional GB > > We also have a Free plan, but we are leaving it out in the following calculations because it's intended for evaluation only and is not meant for production workloads. You can also learn more about the pricing details for each plan on the [pricing page](https://www.prisma.io/pricing?utm_source=docs). **Example of a small workload on the Starter plan**: A hobby or early-stage side-project with \~`500` MAUs. Each user performs \~`10` actions per day, and the entire database uses \~`0.5` GB of storage. Based on the assumptions, you would calculate the monthly bill using the following equations: * `total_ops` = `500` x `10` x `30` = `150000` * `billable_ops` = `0` (150,000 operations is below the 1 million free operations) * `ops_cost` = $`0` * `storage_cost` = $`0` (0.5 GB is below the 10 GB storage already included) * `base_plan_fee` = $`10` `total_monthly_cost` = $`10.00` per month **Example of a medium workload on the Pro plan**: A growing SaaS product serving \~`5000` MAUs. Power users average \~`40` actions per day, and the app stores \~`6` GB of data. Based on the assumptions, you would calculate the monthly bill using the following equations: * `total_ops` = `5000` x `40` x `30` = `6000000` * `billable_ops` = `0` (6 million operations is below the 10 million free operations) * `ops_cost` = $`0` * `storage_cost` = $`0` (6 GB is below the 50 GB storage already included) * `base_plan_fee` = $`49.00` `total_monthly_cost` = $`49.00` per month **Example of a large workload on the Business plan**: A production-grade, consumer-facing application handling \~`50000` MAUs. Heavy usage with \~`60` actions per user per day drives significant traffic, and the dataset reaches \~`40` GB. Based on the assumptions, you would calculate the monthly bill using the following equations: * `total_ops` = `50000` x `60` x `30` = `90000000` * `billable_ops` = `90000000` - `50000000` = `40000000` * `ops_cost` = (`40000000` ÷ `1000000`) = `40.00` x $`1` = $`40.00` * `storage_cost` = $`0.00` (40 GB is below the 100 GB storage already included) * `base_plan_fee` = $`129.00` `total_monthly_cost` = $`40.00` + $`129.00` = $`169.00` per month Are cached operations billed the same? [#are-cached-operations-billed-the-same] Every request, whether it hits the database or is served from cache, counts as an operation. Prisma Postgres use a flat per-operation price and never charge for egress traffic, so a cached response doesn't incur any extra or reduced fee. This unified rate keeps the billing model predictable and avoids per-request complexity. How do I upgrade my plan if I am using Prisma Postgres via Vercel? [#how-do-i-upgrade-my-plan-if-i-am-using-prisma-postgres-via-vercel] If you installed Prisma Postgres through the [Vercel Marketplace integration](/guides/postgres/vercel), the same [Prisma Postgres pricing plans](https://www.prisma.io/pricing) apply and your usage is billed through your Vercel account. To upgrade your plan via Vercel, follow these steps: * Open your [Vercel](https://vercel.com/) Dashboard. * Go to the **Integrations** tab in your Vercel Team. * Click **Manage** on the Prisma Integration. * Navigate to the **Settings** tab. * Under Current Installation Plan Level, click **Change Plan**. * Select the plan you want to upgrade to. Caching [#caching] Prisma Postgres includes built-in connection pooling and global caching. These features improve performance by optimizing how your queries are routed and cached. How does Prisma Postgres's cache layer know what region to fetch the cache from? [#how-does-prisma-postgress-cache-layer-know-what-region-to-fetch-the-cache-from] Under the hood, Prisma Postgres's cache layer uses Cloudflare, which uses [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/) for network addressing and routing. An incoming request will be routed to the nearest data center or "node" in their network that has the capacity to process the request efficiently. To learn more about how this works, we recommend looking into [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/). How can I invalidate a cache for Prisma Postgres? [#how-can-i-invalidate-a-cache-for-prisma-postgres] You can invalidate the cache on-demand via the [`$accelerate.invalidate` API](/accelerate/reference/api-reference#accelerateinvalidate) if you're on a [paid plan](https://www.prisma.io/pricing#accelerate), or you can invalidate your entire cache, on a project level, a maximum of five times a day. This limit is set based on [your plan](https://www.prisma.io/pricing). You can manage this via the Accelerate configuration page. How is Prisma Postgres's caching layer different from other caching tools, such as Redis? [#how-is-prisma-postgress-caching-layer-different-from-other-caching-tools-such-as-redis] The caching layer of Prisma Postgres: * Is a *specialized* cache that allows you to optimize data access in code at the query level with a cache strategy. On the other hand, tools such as Redis and Memcached are *general-purpose* caches designed to be adaptable and flexible. * Is a managed service that reduces the time, risk, and engineering effort of building and maintaining a cache service. * Is globally distributed, by default, reducing the latency of your queries. Other cache tools would require additional configuration to make them available globally. When should I not use Prisma Postgres's caching features? [#when-should-i-not-use-prisma-postgress-caching-features] The caching layer of Prisma Postgres is a global data cache and connection pool that allows you to optimize data access in code at the query level. While caching with Prisma Postgres can greatly boost the performance of your app, it may not always the best choice for your use case. This global cache feature may not be a good fit for your app if: * Your app is exclusively used within a specific region and both your application server and database are situated in that same region on the same network. For example, database queries will likely be much faster if your application server and database are in the same region and network. However, If your application server is in different regions or networks from your database, the cache nodes will speed up your queries because the data will be cached in the closest data center to your application. * Your application data *always* needs to be up-to-date on retrieval, making it difficult to establish a reasonable cache strategy. What is the maximum allowed value for the ttl parameter when configuring cacheStrategy? [#what-is-the-maximum-allowed-value-for-the-ttl-parameter-when-configuring-cachestrategy] The [Time-to-live](/accelerate/caching) (`ttl`) parameter can be set for up to a *year*. However, it's important to note that items within the cache may be evicted if they are not frequently accessed. Based on our experimentation, we’ve seen cache items persist for around 18 hours. While items may remain in the cache for an extended period if they are actively accessed, there is no guarantee. > [!NOTE] > Even frequently accessed items may occasionally be evicted from the cache. It's unlikely for an item to survive for up to or longer than a month, regardless of its activity level. Why do I sometimes see unexpected cache behavior? [#why-do-i-sometimes-see-unexpected-cache-behavior] Prisma Postgres's cache layer performs best when it observes a higher load from a project. Many cache operations, such as committing data to cache and refreshing stale data, happen asynchronously. When benchmarking the cache layer, we recommend doing so with loops or a load testing approach. This will mimic higher load scenarios better and reduce outliers from low frequency operations. Prisma operations are sent to Prisma Postgres over HTTP. As a result, the first request to Prisma Postgres must establish an HTTP handshake and may have additional latency as a result. We're exploring ways to reduce this initial request latency in the future. What regions are Prisma Postgres's cache nodes available in? [#what-regions-are-prisma-postgress-cache-nodes-available-in] Prisma Postgres's cache layer runs on Cloudflare's network and cache hits are served from Cloudflare's 300+ locations. You can find the regions where Prisma Postgres's cache nodes are available here: [https://www.cloudflare.com/network/](https://www.cloudflare.com/network/). How long does it take to invalidate a cache query result? [#how-long-does-it-take-to-invalidate-a-cache-query-result] As the cache needs to be cleared globally, it is difficult to provide a specific time frame. However, the cached data is eventually consistent and typically propagates to all PoPs within a few seconds. In very rare cases, it may take longer. Here is a [demo app](https://pris.ly/test-cache-invalidation) to test the time it takes to invalidate a cache query result. What is the difference between Invalidate and Revalidate? [#what-is-the-difference-between-invalidate-and-revalidate] **Invalidate**: The cache entry is deleted, and new data will be fetched on the next request, causing a cache miss. This removes stale data but may lead to slower responses until the cache is repopulated. **Revalidate**: The cache entry is updated proactively, ensuring the next request uses fresh data from the cache. This keeps the cache valid and maintains faster response times by avoiding cache misses. What is on-demand cache invalidation? [#what-is-on-demand-cache-invalidation] [On-demand cache invalidation](/accelerate/caching) lets applications instantly update specific cached data when it changes, instead of waiting for regular cache refresh cycles. This keeps information accurate and up-to-date for users. When should I use the cache invalidate API? [#when-should-i-use-the-cache-invalidate-api] The [cache invalidate API](/accelerate/caching) is essential when data consistency cannot wait for the cache’s standard expiration or revalidation. Key use cases include: * **Content updates**: When critical changes occur, such as edits to a published article, product updates, or profile modifications, that need to be visible immediately. * **Inventory management**: In real-time applications, like inventory or booking systems, where stock levels, availability, or reservation statuses must reflect the latest information. * **High-priority data**: For time-sensitive data, like breaking news or urgent notifications, where it’s essential for users to see the most current information right away. Using on-demand cache invalidation in these scenarios helps keep only the necessary data refreshed, preserving system performance while ensuring accurate, up-to-date information for users. Connection pooling [#connection-pooling] Can I increase the query duration and response size limits for my Prisma Postgres instance? [#can-i-increase-the-query-duration-and-response-size-limits-for-my-prisma-postgres-instance] Yes, you can increase your Prisma Postgres limits based on your subscription plan. Here are the configurable limits: | Limit | Free | Starter | Pro Plan | Business Plan | | ------------------------------------ | ---------------- | ---------------- | ---------------- | ---------------- | | **Query timeout** | Up to 10 seconds | Up to 10 seconds | Up to 20 seconds | Up to 60 seconds | | **Interactive transactions timeout** | Up to 15 seconds | Up to 15 seconds | Up to 30 seconds | Up to 90 seconds | | **Response size** | Up to 5 MB | Up to 5 MB | Up to 10 MB | Up to 20 MB | Check the [pricing page](https://www.prisma.io/pricing) for more details on the available plans and their corresponding limits. > [!WARNING] > While you can increase these limits based on your subscription plan, it's *still* recommended to optimize your database operations. [Learn more in our troubleshooting guide.](/postgres/error-reference) Query Insights [#query-insights] [Query Insights](/query-insights) is built into Prisma Postgres and helps you identify slow queries, understand their cost, and decide what to fix. I only see raw SQL — how do I see my Prisma ORM queries? [#i-only-see-raw-sql--how-do-i-see-my-prisma-orm-queries] By default, Query Insights shows raw SQL. To also see the Prisma ORM operation that generated each query (model name, action, and query shape), install the `@prisma/sqlcommenter-query-insights` package: ```bash npm install @prisma/sqlcommenter-query-insights ``` Then pass it to the `comments` option in your `PrismaClient` constructor: ```ts import { prismaQueryInsights } from "@prisma/sqlcommenter-query-insights"; import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient({ adapter: myAdapter, comments: [prismaQueryInsights()], }); ``` This annotates every query with a SQL comment containing the model, action, and parameterized query shape. Query Insights uses these annotations to map SQL back to the Prisma call that generated it. Let your AI agent handle setup [#let-your-ai-agent-handle-setup] Copy this prompt into your AI coding assistant: ``` Install and configure @prisma/sqlcommenter-query-insights in my project so I can see Prisma ORM queries in Query Insights. Docs: https://www.prisma.io/docs/query-insights ``` Does Query Insights alter my queries or schema? [#does-query-insights-alter-my-queries-or-schema] No. Query Insights is read-only — it observes query behavior but does not rewrite queries or modify your Prisma schema. Can I use Query Insights in production? [#can-i-use-query-insights-in-production] Query Insights is designed primarily for development and debugging. Running it in production is possible but not recommended, as the SQL comment annotations add a small overhead to every query. ## Related pages - [`Best Postgres for AI apps`](https://www.prisma.io/docs/postgres/best-postgres-for-ai-apps): Why Prisma Postgres works well for AI and LLM workloads — built-in pooling, query caching, edge connectivity, pgvector, and MCP support. - [`create-db`](https://www.prisma.io/docs/postgres/npx-create-db): Learn how to provision temporary Prisma Postgres databases with create-db - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Error reference`](https://www.prisma.io/docs/postgres/error-reference): Error reference documentation for Prisma Postgres - [`Import from existing database`](https://www.prisma.io/docs/postgres/import-from-existing-database): Choose the right path to import data from PostgreSQL or MySQL into Prisma Postgres. # Import from existing database (/docs/postgres/import-from-existing-database) Location: Postgres > Import from existing database Use this page to choose the right import path for moving an existing database into Prisma Postgres. Choose your source database [#choose-your-source-database] * [Import from PostgreSQL](/prisma-postgres/import-from-existing-database-postgresql) * [Import from MySQL](/prisma-postgres/import-from-existing-database-mysql) Before you start [#before-you-start] * Create a Prisma Postgres database first. * Gather the connection details for your existing database. * Use a [direct connection](/postgres/database/connecting-to-your-database) when importing data into Prisma Postgres. Related pages [#related-pages] * [Connecting to your database](/postgres/database/connecting-to-your-database) * [Prisma Postgres overview](/postgres) * [Create a database with `create-db`](/postgres/npx-create-db) ## Related pages - [`Best Postgres for AI apps`](https://www.prisma.io/docs/postgres/best-postgres-for-ai-apps): Why Prisma Postgres works well for AI and LLM workloads — built-in pooling, query caching, edge connectivity, pgvector, and MCP support. - [`create-db`](https://www.prisma.io/docs/postgres/npx-create-db): Learn how to provision temporary Prisma Postgres databases with create-db - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Error reference`](https://www.prisma.io/docs/postgres/error-reference): Error reference documentation for Prisma Postgres - [`Prisma Postgres FAQ`](https://www.prisma.io/docs/postgres/faq): Common questions and answers about Prisma Postgres # Prisma Postgres (/docs/postgres) Location: Prisma Postgres [Prisma Postgres](https://www.prisma.io/postgres?utm_source=docs) is a managed PostgreSQL database with built-in connection pooling, query caching, and edge runtime support. Use this page to choose a connection path and get started quickly. What's included [#whats-included] Everything below is included with every Prisma Postgres database. No extra services to configure. * **Connection pooling** — A dedicated PgBouncer instance runs alongside your database. You don't need to set one up or manage it. Works automatically for serverless and edge deployments. See [Connection pooling](/postgres/database/connection-pooling). * **Query caching** — Add a `cacheStrategy` to any Prisma ORM query to cache results at the edge, using TTL or stale-while-revalidate. See [Caching](/accelerate/caching). * **Edge and serverless support** — Connect from Cloudflare Workers, Vercel Edge Functions, and other edge runtimes via the [serverless driver](/postgres/database/serverless-driver), which uses HTTP instead of TCP. * **Automated backups** — Daily backups with point-in-time recovery. See [Backups](/postgres/database/backups). Getting started [#getting-started] Create a database [#create-a-database] New to Prisma Postgres? Start here. - [Create a temporary database with create-db](/postgres/npx-create-db): Create a temporary Prisma Postgres database in one command. - [Prisma Postgres quickstart with Prisma ORM](/prisma-orm/quickstart/prisma-postgres): Set up Prisma ORM and connect it to Prisma Postgres. Get your connection string [#get-your-connection-string] In [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=postgres), open your database and click **Connect to your database** to copy connection URLs. Choose a connection type [#choose-a-connection-type] Prisma ORM (recommended default) [#prisma-orm-recommended-default] Use Prisma ORM for migrations and type-safe queries. - [Prisma Postgres quickstart](/prisma-orm/quickstart/prisma-postgres): Get started with the recommended Prisma ORM workflow. Any PostgreSQL client or ORM [#any-postgresql-client-or-orm] Use Prisma Postgres with `psql`, GUI tools, `node-postgres`, or other ORMs. - [Kysely quickstart](/prisma-postgres/quickstart/kysely): Connect Prisma Postgres from Kysely. - [Drizzle ORM quickstart](/prisma-postgres/quickstart/drizzle-orm): Connect Prisma Postgres from Drizzle ORM. - [TypeORM quickstart](/prisma-postgres/quickstart/typeorm): Connect Prisma Postgres from TypeORM. - [Connecting to your database](/postgres/database/connecting-to-your-database): Choose the right connection string for Prisma ORM, PostgreSQL tools, and serverless runtimes. Serverless and edge runtimes [#serverless-and-edge-runtimes] Use the serverless driver for HTTP/WebSocket connectivity in edge or constrained runtimes. * [Serverless driver (`@prisma/ppg`)](/postgres/database/serverless-driver) Local development [#local-development] Run Prisma Postgres locally with `prisma dev`, then switch to cloud when ready. * [Local development](/postgres/database/local-development) Manage [#manage] * [Connecting to your database](/postgres/database/connecting-to-your-database) * [Connection pooling](/postgres/database/connection-pooling) * [Caching](/accelerate/caching) * [Backups](/postgres/database/backups) * [PostgreSQL extensions](/postgres/database/postgres-extensions) * [Troubleshooting](/postgres/troubleshooting) * [FAQ](/postgres/faq) Billing and limits [#billing-and-limits] Prisma Postgres uses usage-based pricing and includes spend controls. * [Pricing](https://www.prisma.io/pricing) * [Operations-based billing explained](https://www.prisma.io/blog/operations-based-billing?utm_source=docs) * [FAQ: estimating costs](/postgres/faq#is-there-a-sample-workload-to-estimate-my-expected-charges) In Prisma Console, you can track usage, set spend limits, and view billing details. Billing and Usage dashboard metrics. Technical details [#technical-details] Prisma Postgres is based on **PostgreSQL v17** and uses a unikernel-based architecture. Learn more: [Prisma Postgres: Building a modern PostgreSQL service](https://pris.ly/ppg-early-access?utm_source=docs). > [!NOTE] > Note > > Postgres, PostgreSQL, and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada and are used with permission. ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # create-db (/docs/postgres/npx-create-db) Location: Postgres > create-db [`create-db`](https://create-db.prisma.io/) is an open-source CLI tool that provisions temporary [Prisma Postgres](/postgres) databases with a single command. * **Fast setup:** No sign-up required to create a temporary production-ready Prisma Postgres database. * **Lifetime:** Each database is available for *24 hours* by default. * **Keep for free:** You can *claim* a database (via the URL provided in the CLI output) to make it permanent. Prerequisites [#prerequisites] To use `npx create-db`, you need: * **Node.js** version `16` or higher (we recommend the latest LTS version). * **npm** (comes with Node.js) to run `npx` commands. **A Prisma Data Platform account is not required** to create a temporary database. However, if you want to keep a database permanently, you can claim it ([details below](#claiming-your-database)). Option 1: Using the web interface (recommended) [#option-1-using-the-web-interface-recommended] The [create-db web application](https://create-db.prisma.io) provides a browser-based interface for creating and managing your databases. Key features: [#key-features] * No installation required - works directly in your web browser * Visual interface for database management * Easy connection string display and copying * Built-in schema viewer and editor * Direct integration with Prisma Studio * Simple database claiming workflow Getting started: [#getting-started] 1. Visit [create-db.prisma.io](https://create-db.prisma.io) in your web browser 2. Click "Create with the web interface" 3. Modify your schema and interact with the Studio 4. Copy the provided connection strings for your project 5. Claim your database to make it permanent Option 2: Using the CLI [#option-2-using-the-cli] You can create a database using one of the following options: Option 1: Quick start with default settings [#option-1-quick-start-with-default-settings] Run the following command in your terminal: #### npm ```bash npx create-db@latest ``` #### pnpm ```bash pnpm dlx create-db@latest ``` #### yarn ```bash yarn dlx create-db@latest ``` #### bun ```bash bunx --bun create-db@latest ```
* The `@latest` tag automatically downloads and runs the latest version of the tool, hence, no global installation required. * After a few seconds, you'll receive **connection strings** for both Prisma ORM projects and standard PostgreSQL. * The default region is `us-east-1`. You can specify the region where you want to provision the database in using the `--region` flag. See [the section below](#available-cli-options) to view all the CLI options. Option 2: Choose a region interactively [#option-2-choose-a-region-interactively] If you want to select a region manually: #### npm ```bash npx create-db@latest --interactive ``` #### pnpm ```bash pnpm dlx create-db@latest --interactive ``` #### yarn ```bash yarn dlx create-db@latest --interactive ``` #### bun ```bash bunx --bun create-db@latest --interactive ```
* This opens a region selection menu (for example, `us-east-1`, `eu-west-3`). * Alternatively, you can use the shorthand `-i`: #### npm ```bash npx create-db@latest -i ``` #### pnpm ```bash pnpm dlx create-db@latest -i ``` #### yarn ```bash yarn dlx create-db@latest -i ``` #### bun ```bash bunx --bun create-db@latest -i ``` To view all options and regions: #### npm ```bash npx create-db@latest --help ``` #### pnpm ```bash pnpm dlx create-db@latest --help ``` #### yarn ```bash yarn dlx create-db@latest --help ``` #### bun ```bash bunx --bun create-db@latest --help ``` CLI output walkthrough [#cli-output-walkthrough] Here is an example output: ``` ┌ 🚀 Creating a Prisma Postgres database │ │ Provisioning a temporary database in us-east-1... │ It will be automatically deleted in 24 hours, but you can claim it. ◇ Database created successfully! │ ● Database Connection │ Connection String: │ postgresql://:@db.prisma.io:5432/postgres │ ◆ Claim your database → │ Keep your database for free: │ https://create-db.prisma.io?projectID=proj_... └ ``` Once you have the output, take the connection string and add it to your `.env` file as `DATABASE_URL`: ```text DATABASE_URL="postgresql://:@db.prisma.io:5432/postgres" ``` You can now follow the [Prisma Postgres quickstart guide](/prisma-orm/quickstart/prisma-postgres) to connect your Prisma project to this database. If you're using other tools or libraries, use the standard PostgreSQL connection string with any PostgreSQL-compatible client, such as `psql`, `pgAdmin`, `node-postgres`, or an ORM of your choice. Detailed instructions are available in [Connecting to your database](/postgres/database/connecting-to-your-database). Claiming your database [#claiming-your-database] By default, databases created with `npx create-db` are **temporary** and will be automatically deleted after **24 hours**. You can prevent this by **claiming the database** using the claim URL shown in the CLI output: ``` ◆ Claim your database → │ │ Want to keep your database? Claim for free: │ │ https://create-db.prisma.io?projectID=proj_... │ │ Your database will be deleted on 7/24/2025, 2:25:41 AM if not claimed. ``` To claim your database and make it permanent: 1. Copy the **claim URL** from the CLI output. 2. Open it in your browser and click **Claim database**. 3. Sign in to your [Prisma Data Platform account](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=postgres) (or create one if you don’t have it yet). 4. Choose a **Workspace** that has capacity for creating new projects. 5. Click **Authorize Prisma Create DB** to confirm. 6. You’ll be redirected to a success page. Then, click **Go use your database** to view and manage the claimed database in your workspace. When you claim a database: * It's moved into your Prisma Data Platform account workspace. * It's no longer auto-deleted after 24 hours. * You can continue using it as a permanent database instance. Available CLI options [#available-cli-options] Here are the CLI flags for the `npx create-db` command: | Flag | Shorthand | Description | | --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `--region` | `-r` | Specify a region.
**Available regions:** `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `eu-west-3`, `us-east-1`, `us-west-1` | | `--interactive` | `-i` | Run in interactive mode (select region from a list). | | `--json` | `-j` | Output machine-readable JSON and exit. | | `--help` | `-h` | Show this help message. | To view all CLI options use the `--help` or `-h` flag: #### npm ```bash npx create-db@latest --help ``` #### pnpm ```bash pnpm dlx create-db@latest --help ``` #### yarn ```bash yarn dlx create-db@latest --help ``` #### bun ```bash bunx --bun create-db@latest --help ``` ``` npx create-db@latest [options] Options: --region , -r Specify a region Available regions: ap-southeast-1, ap-northeast-1, eu-central-1, eu-west-3, us-east-1, us-west-1 --interactive, -i Run in interactive mode --help, -h Show this help message ``` ## Related pages - [`Best Postgres for AI apps`](https://www.prisma.io/docs/postgres/best-postgres-for-ai-apps): Why Prisma Postgres works well for AI and LLM workloads — built-in pooling, query caching, edge connectivity, pgvector, and MCP support. - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Error reference`](https://www.prisma.io/docs/postgres/error-reference): Error reference documentation for Prisma Postgres - [`Import from existing database`](https://www.prisma.io/docs/postgres/import-from-existing-database): Choose the right path to import data from PostgreSQL or MySQL into Prisma Postgres. - [`Prisma Postgres FAQ`](https://www.prisma.io/docs/postgres/faq): Common questions and answers about Prisma Postgres # Troubleshooting (/docs/postgres/troubleshooting) Location: Postgres > Troubleshooting This guide helps resolve common issues when working with Prisma Postgres. The --db option is not recognized when running prisma init [#the---db-option-is-not-recognized-when-running-prisma-init] Problem [#problem] Running the following command fails because the `--db` option is not recognized: #### npm ```bash npx prisma init --db ``` #### pnpm ```bash pnpm dlx prisma init --db ``` #### yarn ```bash yarn dlx prisma init --db ``` #### bun ```bash bunx --bun prisma init --db ``` Cause [#cause] This can occur due to npx caching. If you've previously run `npx prisma init`, your machine may be using an outdated cached version that doesn't recognize the `--db` flag because it was only introduced in a later version of Prisma ORM. Solution [#solution] Explicitly run the `latest` Prisma CLI version: #### npm ```bash npx prisma@latest init --db ``` #### pnpm ```bash pnpm dlx prisma@latest init --db ``` #### yarn ```bash yarn dlx prisma@latest init --db ``` #### bun ```bash bunx --bun prisma@latest init --db ``` This ensures that you're using the most up-to-date CLI, preventing issues with outdated command syntax. Workspace plan limit reached when running prisma init --db [#workspace-plan-limit-reached-when-running-prisma-init---db] Problem [#problem-1] When running the command: #### npm ```bash npx prisma@latest init --db ``` #### pnpm ```bash pnpm dlx prisma@latest init --db ``` #### yarn ```bash yarn dlx prisma@latest init --db ``` #### bun ```bash bunx --bun prisma@latest init --db ``` You may encounter the following error message in your logs: ``` Workspace plan limit reached for feature "Project". ``` Cause [#cause-1] Your default [workspace](/console/concepts#workspace) project limit has been reached. Solution [#solution-1] To resolve this issue, consider the following options: * Configure a different Workspace as your default—one that has available capacity for additional projects. * Delete unused projects or databases from your current default Workspace to free up space. * Ensure that you are logged into the correct account in the Prisma CLI. For more details on authentication and account management, please refer to the [Prisma CLI documentation](/cli/console). * [Upgrade to a plan](/postgres#billing-and-limits) that supports more projects in your default Workspace. Implementing one or more of these solutions should help you overcome the plan limit issue. ## Related pages - [`Best Postgres for AI apps`](https://www.prisma.io/docs/postgres/best-postgres-for-ai-apps): Why Prisma Postgres works well for AI and LLM workloads — built-in pooling, query caching, edge connectivity, pgvector, and MCP support. - [`create-db`](https://www.prisma.io/docs/postgres/npx-create-db): Learn how to provision temporary Prisma Postgres databases with create-db - [`Database`](https://www.prisma.io/docs/postgres/database): Overview of Prisma Postgres database operations, connections, pooling, backups, and query analysis. - [`Error reference`](https://www.prisma.io/docs/postgres/error-reference): Error reference documentation for Prisma Postgres - [`Import from existing database`](https://www.prisma.io/docs/postgres/import-from-existing-database): Choose the right path to import data from PostgreSQL or MySQL into Prisma Postgres. # Query Insights (/docs/query-insights) Location: Query Insights Query Insights is built into Prisma Postgres and helps you understand which queries are slow, why they are expensive, and what to change next. It does not automatically rewrite your queries or schema. > [!NOTE] > Query Insights replaces Prisma Optimize and is now included with Prisma Postgres at no extra cost. You can try it today in the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=query-insights). Dashboard [#dashboard] The main Query Insights view gives you a live summary of query activity for your database. At the top of the page, you can inspect: * Average latency over the selected period * Queries per second * A time-based chart for each metric * Hover values for exact timestamps and measurements * Playback controls for stepping through captured activity This makes it easier to see whether a problem is steady, bursty, or tied to a short window of activity. Query list [#query-list] Below the charts, Query Insights shows a list of grouped queries. Each row includes: * Latency * Executions * Reads * Last seen * The SQL statement shape You can use the controls above the table to: * Filter results by table * Sort the list to surface the most important queries first * Focus on repeated, high-read, or recently executed statements This view is the fastest way to identify which query patterns deserve investigation first. Query detail [#query-detail] Selecting a query opens a detail view for that statement. The detail view shows: * A stat summary describing the query's table, execution count, average latency, and reads per call * The full SQL statement * An AI-generated analysis explaining whether the query needs optimization and why * A copyable prompt you can paste directly into your editor or an AI coding assistant to apply the suggested fix The AI analysis describes the likely cause of the performance issue, the specific change it recommends, and the expected impact. The copyable prompt includes your actual query along with context, so you can paste it into your editor or a tool like Cursor, Copilot, or Claude and get a concrete code change without switching context. > [!NOTE] > Treat the AI analysis as a starting point, not a final answer. Review any suggested change before shipping it. Prisma ORM attribution [#prisma-orm-attribution] When using Prisma ORM, Query Insights can trace the full chain from your application code to the SQL it generates. This means you can see which `prisma.*` call produced a slow query, even when a single Prisma call expands into multiple SQL statements. For raw SQL or queries issued outside Prisma ORM, Query Insights still shows full SQL behavior, but ORM-level attribution requires the steps below. Setup [#setup] To enable ORM attribution, install the `@prisma/sqlcommenter-query-insights` package: ```bash npm install @prisma/sqlcommenter-query-insights ``` Then pass it to the `comments` option in your `PrismaClient` constructor: ```ts import "dotenv/config"; import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import { prismaQueryInsights } from "@prisma/sqlcommenter-query-insights"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); export const prisma = new PrismaClient({ adapter: adapter, comments: [prismaQueryInsights()], }) ``` This adds SQL comment annotations to queries so Query Insights can map SQL statements back to the Prisma calls that generated them. It is built on top of the [SQL comments](/orm/prisma-client/observability-and-logging/sql-comments) feature in Prisma Client. Availability [#availability] Query Insights is included with Prisma Postgres at no extra cost. You can try it today in the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=query-insights). Typical issues [#typical-issues] Query Insights is most useful when it connects a database symptom to a concrete code change. | Issue | What you might see | Typical fix | | ------------------ | ------------------------------------ | ------------------------------------------- | | N+1 queries | High query count for one request | Use nested reads, batching, or joins | | Missing indexes | High reads relative to rows returned | Add the right index for the filter pattern | | Over-fetching | Wide rows or large payloads | Use `select` to fetch fewer fields | | Offset pagination | Reads grow on deeper pages | Switch to cursor pagination | | Large nested reads | High reads and large payloads | Limit fields, limit depth, or split queries | | Repeated queries | The same statement shape runs often | Cache or reuse results when appropriate | How to use it [#how-to-use-it] When an endpoint gets slow, Query Insights gives you a practical workflow: 1. Open Query Insights and scan the latency and queries-per-second charts. 2. Sort or filter the query list to isolate the expensive statement. 3. Open the query detail view. 4. Read the AI analysis and inspect the SQL. 5. Copy the suggested prompt and paste it into your editor. 6. Review the suggested change, then apply it in code or schema. 7. Re-run the workload and compare the same signals again. In most cases, the next change falls into one of these buckets: * Change the Prisma query shape * Add or adjust an index * Return fewer fields or fewer rows * Cache repeated work Example [#example] A common example is an N+1 pattern: ```ts const users = await prisma.user.findMany({ select: { id: true, name: true, email: true }, }); for (const user of users) { await prisma.post.findMany({ where: { authorId: user.id }, select: { id: true, title: true }, }); } ``` Query Insights would typically show: * One query to load users * Many repeated queries to load posts * A high execution count for the same statement shape * More reads and latency than the route should need In this case, the likely fix is to load the related posts in one nested read: ```ts const usersWithPosts = await prisma.user.findMany({ select: { id: true, name: true, email: true, posts: { select: { id: true, title: true, }, }, }, }); ``` The same pattern applies to other issues. Query Insights helps you identify the expensive query shape, understand why it is expensive, and choose the next change to verify. Next steps [#next-steps] * Review [Connection pooling](/postgres/database/connection-pooling) for high-concurrency workloads * Use [Connecting to your database](/postgres/database/connecting-to-your-database) when choosing connection strings for other tools * See [Prisma Client query optimization](/orm/prisma-client/queries/advanced/query-optimization-performance) for related Prisma ORM patterns ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # Getting Started (/docs/studio/getting-started) Location: Studio > Getting Started Installation [#installation] Prisma Studio comes bundled with the Prisma CLI. To get started, make sure you have Node.js installed, then install the Prisma CLI: #### npm ```bash npm install -g prisma ``` #### pnpm ```bash pnpm add -g prisma ``` #### yarn ```bash yarn global add prisma ``` #### bun ```bash bun add --global prisma ``` Launching Studio [#launching-studio] With a Prisma Project [#with-a-prisma-project] If you have an existing Prisma project, navigate to your project directory and run: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` This will start the Studio server and open it in your default browser at `http://localhost:5555`. Without a Prisma Project [#without-a-prisma-project] You can also use Studio with any database by providing a connection string: #### npm ```bash npx prisma studio --url="postgresql://user:password@localhost:5432/yourdb" ``` #### pnpm ```bash pnpm dlx prisma studio --url="postgresql://user:password@localhost:5432/yourdb" ``` #### yarn ```bash yarn dlx prisma studio --url="postgresql://user:password@localhost:5432/yourdb" ``` #### bun ```bash bunx --bun prisma studio --url="postgresql://user:password@localhost:5432/yourdb" ``` Connecting to Your Database [#connecting-to-your-database] 1. **Using environment variables**: Create a `.env` file in your project root with your database URL: ``` DATABASE_URL="postgresql://user:password@localhost:5432/yourdb" ``` Then run: `npx prisma studio` 2. **Using command line**: ```bash npx prisma studio --url="your-database-connection-string" ``` Basic Usage [#basic-usage] Browsing Data [#browsing-data] * The left sidebar lists all your database tables * Click on a table to view its data * Use the search bar to quickly find tables or columns Editing Data [#editing-data] * **Edit cells**: Double-click any cell to edit its value * **Add records**: Click the "+" button to add a new record * **Delete records**: Select records using checkboxes and click the trash icon Filtering and Sorting [#filtering-and-sorting] * Click the filter icon to add filters * Click on column headers to sort the table * Use the search box to filter records by any field Common Tasks [#common-tasks] Viewing Table Relationships [#viewing-table-relationships] * Related tables are shown as expandable rows * Click the "+" icon to view related records Exporting Data [#exporting-data] * Use the export button to download data as CSV or JSON * Select specific columns to include in the export Next Steps [#next-steps] * Learn how to [embed Studio in your application](/studio/integrations/embedding) * Discover [VS Code integration](/studio/integrations/vscode-integration) features # Prisma Studio (/docs/studio) Location: Prisma Studio [Prisma Studio](https://www.prisma.io/studio) works with or without Prisma ORM and supports the following workflows: * Viewing and editing data in a spreadsheet-like interface * Real-time schema introspection * Embedding directly into your Next.js applications * VS Code integration for in-editor database management Supported databases [#supported-databases] * PostgreSQL * MySQL * SQLite Quick start [#quick-start] #### npm ```bash # With Prisma project npx prisma studio # With direct database connection npx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### pnpm ```bash # With Prisma project pnpm dlx prisma studio # With direct database connection pnpm dlx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### yarn ```bash # With Prisma project yarn dlx prisma studio # With direct database connection yarn dlx prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` #### bun ```bash # With Prisma project bun x prisma studio # With direct database connection bun x prisma studio --url="postgresql://user:password@localhost:5432/dbname" ``` Getting started [#getting-started] * [Getting Started](/studio/getting-started) - Learn how to set up and use Prisma Studio to manage your database * [Embed Studio](/studio/integrations/embedding) - Learn how to embed Prisma Studio in your own applications * [Studio in VS Code](/studio/integrations/vscode-integration) - Learn how to use Prisma Studio directly in VS Code ## Related pages - [`Build faster with Prisma + AI`](https://www.prisma.io/docs/ai): Build faster with Prisma and AI coding tools like Cursor, Codex, and ChatGPT - [`Choose a setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to start using Prisma ORM or Prisma Postgres in a new or existing project. - [`CLI Overview`](https://www.prisma.io/docs/cli): The Prisma CLI is the command-line interface for Prisma ORM. Use it to initialize projects, generate Prisma Client, manage databases, run migrations, and more - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Guides`](https://www.prisma.io/docs/guides): A collection of guides for various tasks and workflows # From the CLI (/docs/prisma-postgres/from-the-cli) Location: Prisma Postgres > From the CLI This page provides a step-by-step guide for Prisma Postgres after setting it up with `prisma init` and `npx create-db`: 1. Set up a TypeScript app with Prisma ORM 2. Migrate the schema of your database 3. Query your database from TypeScript Prerequisites [#prerequisites] This guide assumes you initialized Prisma with `prisma init` and created a Prisma Postgres database with `npx create-db`: #### npm ```bash npx prisma@latest init npx create-db ``` #### pnpm ```bash pnpm dlx prisma@latest init pnpm dlx create-db ``` #### yarn ```bash yarn dlx prisma@latest init yarn dlx create-db ``` #### bun ```bash bunx --bun prisma@latest init bun x create-db ``` Once these commands have terminated: * The `prisma/` folder was created with an empty `schema.prisma` file. * The `DATABASE_URL` env var was set in a `.env` file. * The `prisma.config.ts` file was created with the default configuration. * You have a Prisma Postgres connection string to paste into `.env`. 1. Organize your project directory [#1-organize-your-project-directory] > [!NOTE] > If you ran the `prisma init` command inside a folder where you want your project to live, you can skip this step and [proceed to the next section](/prisma-postgres/from-the-cli#2-set-up-your-project). If you ran the command outside your intended project directory (e.g., in your home folder or another location), you need to move the generated `prisma` folder and the `.env` file into a dedicated project directory. Create a new folder (e.g. `hello-prisma`) where you want your project to live and move the necessary files into it: ```bash mkdir hello-prisma mv .env ./hello-prisma/ mv prisma ./hello-prisma/ ``` Navigate into your project folder: ```bash cd ./hello-prisma ``` Now that your project is in the correct location, continue with the setup. 2. Set up your project [#2-set-up-your-project] 2.1. Set up TypeScript [#21-set-up-typescript] Initialize a TypeScript project and add the Prisma CLI as a development dependency: #### npm ```bash npm init ``` #### pnpm ```bash pnpm init ``` #### yarn ```bash yarn init ``` #### bun ```bash bun init ``` #### npm ```bash npm install typescript tsx @types/node @types/pg -D ``` #### pnpm ```bash pnpm add typescript tsx @types/node @types/pg -D ``` #### yarn ```bash yarn add typescript tsx @types/node @types/pg --dev ``` #### bun ```bash bun add typescript tsx @types/node @types/pg --dev ``` This creates a `package.json` file with an initial setup for your TypeScript app. Next, initialize TypeScript with a `tsconfig.json` file in the project: #### npm ```bash npx tsc --init ``` #### pnpm ```bash pnpm dlx tsc --init ``` #### yarn ```bash yarn dlx tsc --init ``` #### bun ```bash bunx --bun tsc --init ``` 2.2. Configure ESM support [#22-configure-esm-support] Update `tsconfig.json` for ESM compatibility: ```json title="tsconfig.json" { "compilerOptions": { "module": "ESNext", "moduleResolution": "bundler", "target": "ES2023", "strict": true, "esModuleInterop": true, "ignoreDeprecations": "6.0" } } ``` Update `package.json` to enable ESM: ```json title="package.json" { "type": "module" // [!code ++] } ``` 2.3. Set up Prisma ORM [#23-set-up-prisma-orm] Install the required dependencies to use Prisma Postgres: #### npm ```bash npm install prisma --save-dev npm install @prisma/client @prisma/adapter-pg pg dotenv ``` #### pnpm ```bash pnpm add prisma --save-dev pnpm add @prisma/client @prisma/adapter-pg pg dotenv ``` #### yarn ```bash yarn add prisma --dev yarn add @prisma/client @prisma/adapter-pg pg dotenv ``` #### bun ```bash bun add prisma --dev bun add @prisma/client @prisma/adapter-pg pg dotenv ``` Here's what each package does: * **`prisma`** - The Prisma CLI for running commands like `prisma migrate` and `prisma generate` * **`@prisma/client`** - The Prisma Client library for querying your database * **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/core-concepts/supported-databases/postgresql#using-driver-adapters) that connects Prisma Client to your database * **`pg`** - The node-postgres database driver * **`@types/pg`** - TypeScript type definitions for node-postgres * **`dotenv`** - Loads environment variables from your `.env` file 2.4. Review the generated prisma.config.ts [#24-review-the-generated-prismaconfigts] The `prisma init` command automatically created a `prisma.config.ts` file that looks like this: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 2.5. Create a script to query the database [#25-create-a-script-to-query-the-database] Create an `index.ts` file in the root directory, this will be used to query your application with Prisma ORM: ```bash touch index.ts ``` 3. Migrate the database schema [#3-migrate-the-database-schema] Update your `prisma/schema.prisma` file to include the `User` and `Post` models: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int } ``` After adding the models, migrate your database using [Prisma Migrate](/orm/prisma-migrate): #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` This command creates the database tables based on your schema. Now run the following command to generate the Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 4. Send queries with Prisma ORM [#4-send-queries-with-prisma-orm] 4.1. Instantiate Prisma Client [#41-instantiate-prisma-client] Create a `lib/prisma.ts` file to instantiate Prisma Client with the driver adapter: ```typescript title="lib/prisma.ts" import "dotenv/config"; import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "../generated/prisma/client"; const connectionString = `${process.env.DATABASE_URL}`; const adapter = new PrismaPg({ connectionString }); const prisma = new PrismaClient({ adapter }); export { prisma }; ``` > [!NOTE] > If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/postgres/database/serverless-driver#use-with-prisma-orm). 4.2. Write your first query [#42-write-your-first-query] Paste the following boilerplate into `index.ts`: ```ts title="index.ts" import { prisma } from "./lib/prisma"; async function main() { // ... you will write your Prisma ORM queries here } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` This code contains a `main` function that's invoked at the end of the script. It also instantiates `PrismaClient` which you'll use to send queries to your database. 4.3. Create a new User record [#43-create-a-new-user-record] Let's start with a small query to create a new `User` record in the database and log the resulting object to the console. Add the following code to your `index.ts` file: ```ts title="index.ts" import { prisma } from "./lib/prisma"; async function main() { const user = await prisma.user.create({ // [!code ++] data: { // [!code ++] name: "Alice", // [!code ++] email: "alice@prisma.io", // [!code ++] }, // [!code ++] }); // [!code ++] console.log(user); // [!code ++] } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` Next, execute the script with the following command: #### npm ```bash npx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### bun ```bash bunx --bun tsx index.ts ``` ```text no-copy { id: 1, email: 'alice@prisma.io', name: 'Alice' } ``` Great job, you just created your first database record with Prisma Postgres! 🎉 4.4. Retrieve all User records [#44-retrieve-all-user-records] Prisma ORM offers various queries to read data from your database. In this section, you'll use the `findMany` query that returns *all* the records in the database for a given model. Delete the previous Prisma ORM query and add the new `findMany` query instead: ```ts title="index.ts" import { prisma } from "./lib/prisma"; async function main() { const users = await prisma.user.findMany(); // [!code ++] console.log(users); // [!code ++] } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` Execute the script again: #### npm ```bash npx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### bun ```bash bunx --bun tsx index.ts ``` ```text no-copy [{ id: 1, email: 'alice@prisma.io', name: 'Alice' }] ``` Notice how the single `User` object is now enclosed with square brackets in the console. That's because the `findMany` returned an array with a single object inside. 4.5. Explore relation queries [#45-explore-relation-queries] One of the main features of Prisma ORM is the ease of working with [relations](/orm/prisma-schema/data-model/relations). In this section, you'll learn how to create a `User` and a `Post` record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the `include` option. First, adjust your script to include the nested query: ```ts title="index.ts" import { prisma } from "./lib/prisma"; async function main() { const user = await prisma.user.create({ // [!code ++] data: { // [!code ++] name: "Bob", // [!code ++] email: "bob@prisma.io", // [!code ++] posts: { // [!code ++] create: [ // [!code ++] { // [!code ++] title: "Hello World", // [!code ++] published: true, // [!code ++] }, // [!code ++] { // [!code ++] title: "My second post", // [!code ++] content: "This is still a draft", // [!code ++] }, // [!code ++] ], // [!code ++] }, // [!code ++] }, // [!code ++] }); // [!code ++] console.log(user); // [!code ++] } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` Run the query by executing the script again: #### npm ```bash npx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### bun ```bash bunx --bun tsx index.ts ``` ```text no-copy { id: 2, email: 'bob@prisma.io', name: 'Bob' } ``` In order to also retrieve the `Post` records that belong to a `User`, you can use the `include` option via the `posts` relation field: ```ts title="index.ts" import { prisma } from "./lib/prisma"; async function main() { const usersWithPosts = await prisma.user.findMany({ // [!code ++] include: { // [!code ++] posts: true, // [!code ++] }, // [!code ++] }); // [!code ++] console.dir(usersWithPosts, { depth: null }); // [!code ++] } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` Run the script again to see the results of the nested read query: #### npm ```bash npx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### bun ```bash bunx --bun tsx index.ts ``` ```text no-copy [ { id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] }, { id: 2, email: 'bob@prisma.io', name: 'Bob', posts: [ { id: 1, title: 'Hello World', content: null, published: true, authorId: 2 }, { id: 2, title: 'My second post', content: 'This is still a draft', published: false, authorId: 2 } ] } ] ``` This time, you're seeing two `User` objects being printed. Both of them have a `posts` field (which is empty for `"Alice"` and populated with two `Post` objects for `"Bob"`) that represents the `Post` records associated with them. Next steps [#next-steps] You just got your feet wet with a basic Prisma Postgres setup. Check out the official [Quickstart](/prisma-orm/quickstart/prisma-postgres). View and edit data in Prisma Studio [#view-and-edit-data-in-prisma-studio] Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command: #### npm ```bash npx prisma studio --config ./prisma.config.ts ``` #### pnpm ```bash pnpm dlx prisma studio --config ./prisma.config.ts ``` #### yarn ```bash yarn dlx prisma studio --config ./prisma.config.ts ``` #### bun ```bash bunx --bun prisma studio --config ./prisma.config.ts ``` With Prisma Postgres, you can also directly use Prisma Studio inside the [Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) by selecting the **Studio** tab in your project. Build a fullstack app with Next.js [#build-a-fullstack-app-with-nextjs] Learn how to use Prisma Postgres in a fullstack app: * [Build a fullstack app with Next.js 15](/guides/frameworks/nextjs) * [Next.js 15 example app](https://github.com/prisma/nextjs-prisma-postgres-demo) (including authentication) Explore ready-to-run examples [#explore-ready-to-run-examples] Check out the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more. These examples use SQLite by default but you can follow the instructions in the project README to switch to Prisma Postgres in a few simple steps. ## Related pages - [`Import from MySQL`](https://www.prisma.io/docs/prisma-postgres/import-from-existing-database-mysql): Learn how to import data from an existing MySQL database into Prisma Postgres - [`Import from PostgreSQL`](https://www.prisma.io/docs/prisma-postgres/import-from-existing-database-postgresql): Learn how to import data from an existing PostgreSQL database into Prisma Postgres # Import from MySQL (/docs/prisma-postgres/import-from-existing-database-mysql) Location: Prisma Postgres > Import from MySQL This guide provides step-by-step instructions for importing data from an existing MySQL database into Prisma Postgres. You can accomplish this migration in four steps: 1. Create a new Prisma Postgres database. 2. Connect directly to a Prisma Postgres instance using a [direct connection](/postgres/database/connecting-to-your-database). 3. Migrate your MySQL data to Prisma Postgres using [pgloader](https://pgloader.io/). 4. Configure your Prisma project for Prisma Postgres. Prerequisites [#prerequisites] * The connection URL to your existing MySQL database. * A [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) account. * Node.js 18+ installed. * [pgloader](https://pgloader.io/) installed. > [!NOTE] > Make sure your PostgreSQL tools match the Prisma Postgres version > > Prisma Postgres runs PostgreSQL 17. Your `pgloader` and any other PostgreSQL tools you use need to be compatible with PostgreSQL 17. We recommend attempting this migration in a separate git development branch. 1. Create a new Prisma Postgres database [#1-create-a-new-prisma-postgres-database] Follow these steps to create a new Prisma Postgres database: 1. Log in to [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) and open the Console. 2. In a [workspace](/console/concepts#workspace) of your choice, click the **New project** button. 3. Type a name for your project in the **Name** field, e.g. **hello-ppg**. 4. In the **Prisma Postgres** section, click the **Get started** button. 5. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. 6. Click the **Create project** button. Once your database is\*\* \*\*provisioned, find your direct Prisma Postgres connection string: 1. Navigate to your active Prisma Postgres instance. 2. Click the **Connection Strings** tab in the project's sidenav. 3. Click the **Create connection string** button. 4. In the popup, provide a **Name** for the connection string and click **Create**. 5. Copy the connection string starting with `postgres://`, this is your direct connection string. Save the connection string, as you'll need it in step 3. 2. Prepare your direct connection string [#2-prepare-your-direct-connection-string] In this step, you'll use the [direct connection string](/postgres/database/connecting-to-your-database) you obtained in step 1 to connect to your Prisma Postgres instance. Your direct connection string should look like this: ```text postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require ``` You'll use this connection string in the next step when configuring pgloader. 3. Migrate your MySQL data to Prisma Postgres using pgloader [#3-migrate-your-mysql-data-to-prisma-postgres-using-pgloader] Now that you have an active connection to your Prisma Postgres instance, you'll use [pgloader](https://pgloader.io/) to export data from your MySQL database to Prisma Postgres. Open a separate terminal window and create a `config.load` file: ```bash touch config.load ``` Open the `config.load` file in your preferred text editor and copy-paste the following configuration: ```text title="config.load" LOAD DATABASE FROM mysql://username:password@host:PORT/database_name INTO postgres://__USER__:__PASSWORD__@db.prisma.io:5432/?sslmode=require WITH quote identifiers, -- preserve table/column name case by quoting them include drop, create tables, create indexes, reset sequences ALTER SCHEMA 'database_name' RENAME TO 'public'; ``` Make sure to update the following details in the `config.load` file: * `FROM` url (MySQL database URL): * Replace `username`, `password`, `host`, `PORT`, and `database_name` with the actual connection details for your MySQL database. * Ensure that your connection string includes `useSSL=true` if SSL is required, for example: `mysql://username:password@host:PORT/database_name?useSSL=true`. Note that when using PlanetScale, appending `sslaccept=strict` will not work. * `INTO` url (Postgres database URL): * Update this with your direct connection string from above, replacing the `__USER__` and `__PASSWORD__` placeholders. * Update the `database_name` in `ALTER SCHEMA 'database_name' RENAME TO 'public';` to exactly match the `database_name` in your MySQL connection string. After saving the configuration file with your updated credentials, in the same terminal window, execute the following command: ```bash pgloader config.load ``` You should see a log similar to this, which confirms the successful migration of your data: ```bash LOG report summary reset table name errors rows bytes total time ------------------------- --------- --------- --------- -------------- fetch meta data 0 9 2.546s Create Schemas 0 0 0.325s Create SQL Types 0 0 0.635s Create tables 0 6 5.695s Set Table OIDs 0 3 0.328s ------------------------- --------- --------- --------- -------------- public.post 0 8 0.5 kB 4.255s public."user" 0 4 0.1 kB 2.775s public._prisma_migrations 0 1 0.2 kB 4.278s ------------------------- --------- --------- --------- -------------- COPY Threads Completion 0 4 5.095s Index Build Completion 0 5 9.601s Create Indexes 0 5 4.116s Reset Sequences 0 2 4.540s Primary Keys 0 3 2.917s Create Foreign Keys 0 1 1.121s Create Triggers 0 0 0.651s Install Comments 0 0 0.000s ------------------------- --------- --------- --------- -------------- Total import time ✓ 13 0.8 kB 28.042s ``` If you see output like this, it means your data has been successfully exported to your Prisma Postgres instance. You can also use [Prisma Studio](/guides/postgres/viewing-data#viewing-and-editing-data-in-prisma-studio) to verify whether the migration was successful: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` 4. Configure your Prisma project for Prisma Postgres [#4-configure-your-prisma-project-for-prisma-postgres] After migrating your data, you need to set up your Prisma project to work with Prisma Postgres. The steps differ depending on whether you were already using Prisma ORM. If you were not previously using Prisma ORM [#if-you-were-not-previously-using-prisma-orm] Initialize Prisma in your project by running `npx prisma init` in your project directory. This creates a `prisma` folder with a `schema.prisma` file and `.env` file (if not already present). In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): ```text title=".env" no-copy DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` [Introspect](/orm/prisma-schema/introspection) your newly migrated database by running: #### npm ```bash npx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### bun ```bash bunx --bun prisma db pull ``` This command updates your `schema.prisma` file with models representing your migrated tables, so you can start using [Prisma Client](/orm/prisma-client/setup-and-configuration/introduction) to query your data or [Prisma Migrate](/orm/prisma-migrate/getting-started) to manage future changes. Congratulations! You've successfully migrated your MySQL database to Prisma Postgres and configured your Prisma project. Your migration tutorial is now complete. > [!NOTE] > For a comprehensive guide on getting started with Prisma and Prisma Postgres, see [start from scratch with Prisma and Prisma Postgres](/prisma-orm/quickstart/prisma-postgres). If you were already using Prisma ORM [#if-you-were-already-using-prisma-orm] In your `schema.prisma` file, change the `provider` in the `datasource` block from `mysql` to `postgresql`: ```prisma title="schema.prisma" datasource db { provider = "mysql" // [!code --] provider = "postgres" // [!code ++] } ``` In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): ```text title=".env" no-copy DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` Introspect your newly migrated Prisma Postgres database and generate Prisma Client: #### npm ```bash npx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### bun ```bash bunx --bun prisma db pull ``` This command refreshes your Prisma models based on the new database schema. If you were using [Prisma Migrate](/orm/prisma-migrate/getting-started) before: * Delete your existing `migrations` folder in the `prisma` directory. * [Baseline your database](/orm/prisma-migrate/workflows/baselining#baselining-a-database) to begin creating new migrations. Congratulations! You've successfully migrated your MySQL database to Prisma Postgres and configured your Prisma project. Your migration tutorial is now complete. If you encounter any issues during the migration, please don't hesitate to reach out to us on [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=conclusion) or via [X](https://pris.ly/x?utm_source=docs\&utm_medium=conclusion). ## Related pages - [`From the CLI`](https://www.prisma.io/docs/prisma-postgres/from-the-cli): Start building a Prisma application with a Prisma Postgres database from the CLI - [`Import from PostgreSQL`](https://www.prisma.io/docs/prisma-postgres/import-from-existing-database-postgresql): Learn how to import data from an existing PostgreSQL database into Prisma Postgres # Import from PostgreSQL (/docs/prisma-postgres/import-from-existing-database-postgresql) Location: Prisma Postgres > Import from PostgreSQL This guide provides step-by-step instructions for importing data from an existing PostgreSQL database into Prisma Postgres. You can accomplish this migration in three steps: 1. Create a new Prisma Postgres database. 2. Export your existing data via `pg_dump`. 3. Import the previously exported data into Prisma Postgres via `pg_restore`. In the third step, you will be using a [direct connection](/postgres/database/connecting-to-your-database) to securely connect to your Prisma Postgres database to run `pg_restore`. Prerequisites [#prerequisites] * The connection URL to your existing PostgreSQL database * A [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) account * Node.js 18+ installed * PostgreSQL CLI Tools (`pg_dump`, `pg_restore`) for creating and restoring backups > [!NOTE] > Make sure your PostgreSQL tools match the Prisma Postgres version > > Prisma Postgres runs PostgreSQL 17. Your `pg_dump` and `pg_restore` tools need to be version 17 to ensure compatibility. You can check your version by running `pg_dump --version` or `pg_restore --version`. 1. Create a new Prisma Postgres database [#1-create-a-new-prisma-postgres-database] Follow these steps to create a new Prisma Postgres database: 1. Log in to [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) and open the Console. 2. In a [workspace](/console/concepts#workspace) of your choice, click the **New project** button. 3. Type a name for your project in the **Name** field, e.g. **hello-ppg**. 4. In the **Prisma Postgres** section, click the **Get started** button. 5. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. 6. Click the **Create project** button. Once your database is provisioned, obtain your direct connection string: 1. Navigate to your active Prisma Postgres instance. 2. Click the **Connection Strings** tab in the project's sidenav. 3. Click the **Create connection string** button. 4. In the popup, provide a **Name** for the connection string and click **Create**. 5. Copy the connection string starting with `postgres://`, this is your direct connection string. Save the connection string, as you'll need it in step 3. 2. Export data from your existing database [#2-export-data-from-your-existing-database] In this step, you're going to export the data from your existing database and store it in a `.bak` file on your local machine. Make sure to have the connection URL for your existing database ready, it should be [structured](/orm/reference/connection-urls) like this: ```text postgresql://USER:PASSWORD@HOST:PORT/DATABASE ``` Expand below for provider-specific instructions that help you determine the right connection string: ### Neon * Make sure to select non-pooled connection string by switching off the **Connection pooling** toggle. * The `sslmode` has to be set to `require` and appended to your Neon database URL for the command to work. * The connection URL should look similar to this: ```text postgresql://USER:PASSWORD@YOUR-NEON-HOST/DATABASE?sslmode=require ``` ### Supabase * Use a database connection URL that uses [Supavisor session mode](https://supabase.com/docs/guides/database/connecting-to-postgres#supavisor-session-mode). * The connection URL should look similar to this: ```text postgres://postgres.apbkobhfnmcqqzqeeqss:[YOUR-PASSWORD]@aws-0-ca-central-1.pooler.supabase.com:5432/postgres ``` Next, run the following command to export the data of your PostgreSQL database (replace the `__DATABASE_URL__` placeholder with your actual database connection URL): ```bash pg_dump \ -Fc \ -v \ -d __DATABASE_URL__ \ -n public \ -f db_dump.bak ``` Here's a quick overview of the CLI options that were used for this command: * `-Fc`: Uses the custom format for backups, recommended for `pg_restore` * `-v`: Runs `pg_dump` in verbose mode * `-d`: Specifies the database connection string * `-n`: Specifies the target PostgreSQL schema * `-f`: Specifies the output name for the backup file Running this command will create a backup file named `db_dump.bak` which you will use to restore the data into your Prisma Postgres database in the next step. 3. Import data into Prisma Postgres [#3-import-data-into-prisma-postgres] In this section, you'll use your [direct connection string](/postgres/database/connecting-to-your-database) to connect to your Prisma Postgres instance and import data via `pg_restore`. Your direct connection string from step 1 should look like this: ```text postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require ``` Use the backup file from **Step 2** to restore data into your Prisma Postgres database with `pg_restore` by running this command (replace `__USER__`, `__PASSWORD__` with the values from your direct connection string): ```bash pg_restore \ -h db.prisma.io \ -p 5432 \ -U __USER__ \ -d postgres \ -v \ ./db_dump.bak \ && echo "-complete-" ``` When prompted, enter the `__PASSWORD__` from your direct connection string. You can also use the full connection string format: ```bash pg_restore \ -d "postgres://USER:PASSWORD@db.prisma.io:5432/postgres?sslmode=require" \ -v \ ./db_dump.bak \ && echo "-complete-" ``` Once the command completes execution, you will have successfully imported the data from your existing PostgreSQL database into Prisma Postgres 🎉 To validate that the import worked, you can use [Prisma Studio](/guides/postgres/viewing-data#viewing-and-editing-data-in-prisma-studio). Either open it in the [Platform Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29) by clicking the **Studio** tab in the left-hand sidenav in your project or run this command to launch Prisma Studio locally: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` 4. Update your application code to query Prisma Postgres [#4-update-your-application-code-to-query-prisma-postgres] Scenario A: You are already using Prisma ORM [#scenario-a-you-are-already-using-prisma-orm] If you're already using Prisma ORM, you need to update your database connection URL to point to your new Prisma Postgres instance. Update the `DATABASE_URL` in your `.env` file to match your Prisma Postgres direct connection string from step 1: ```text title=".env" DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` Then, re-generate Prisma Client so that the updated environment variable takes effect: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` Once this is done, you can run your application and it should work as before. > [!NOTE] > For a complete guide on setting up Prisma ORM with Prisma Postgres from scratch, including driver adapter configuration and best practices, see the [Prisma ORM with Prisma Postgres quickstart](/prisma-orm/quickstart/prisma-postgres). Scenario B: You are not yet using Prisma ORM [#scenario-b-you-are-not-yet-using-prisma-orm] If you are not yet using Prisma ORM, you'll need to go through the following steps to use Prisma Postgres from your application: 1. Install the Prisma CLI and other required dependencies in your project 2. Introspect the database to generate a Prisma schema 3. Generate Prisma Client 4. Update the queries in your application to use Prisma ORM You can find the detailed step-by-step instructions for this process in this guide: [Add Prisma ORM to an existing project](/prisma-orm/add-to-existing-project/prisma-postgres). ## Related pages - [`From the CLI`](https://www.prisma.io/docs/prisma-postgres/from-the-cli): Start building a Prisma application with a Prisma Postgres database from the CLI - [`Import from MySQL`](https://www.prisma.io/docs/prisma-postgres/import-from-existing-database-mysql): Learn how to import data from an existing MySQL database into Prisma Postgres # FAQ (/docs/accelerate/more/faq) Location: Accelerate > More > FAQ When should I enable static IP for Prisma Accelerate? [#when-should-i-enable-static-ip-for-prisma-accelerate] Enable static IP for Accelerate when your security setup requires IP allowlisting or if you're implementing firewalls that only permit access from trusted IPs, ensuring controlled and secure database connections. Result of enabling static IP Accelerate with a database using IP allowlisting Learn more on [how to enable static IP for Accelerate in the Platform Console](/accelerate/static-ip). > [!NOTE] > **What is a static IP?** > > A static IP address is an IPv4 or an IPv6 address that is fixed. Unlike dynamic IP addresses, which can change unpredictably, traffic from static IP addresses can be easily identified. > > What is a static IP > ℹ️ To enable static IP support for Accelerate within your existing or new project environment, your workspace will need to be on our **Pro** or **Business** plans. Take a look at the [pricing page](https://www.prisma.io/pricing#accelerate) for more information. Why do I sometimes see unexpected cache behavior? [#why-do-i-sometimes-see-unexpected-cache-behavior] Accelerate's cache performs best when it observes a higher load from a project. Many cache operations, such as committing data to cache and refreshing stale data, happen asynchronously. When benchmarking Accelerate, we recommend doing so with loops or a load testing approach. This will mimic higher load scenarios better and reduce outliers from low frequency operations. Prisma operations are sent to Accelerate over HTTP. As a result, the first request to Accelerate must establish an HTTP handshake and may have additional latency as a result. We're exploring ways to reduce this initial request latency in the future. What is the pricing of Accelerate? [#what-is-the-pricing-of-accelerate] You can find more details on our [Accelerate pricing page](https://www.prisma.io/pricing) VS Code does not recognize the $extends method [#vs-code-does-not-recognize-the-extends-method] If you add the Prisma Client extension for Accelerate to an existing project that is currently open in VS Code, the editor might not immediately recognize the `$extends` method. This might be an issue with the TypeScript server not yet recognizing the regenerated Prisma Client. To resolve this, you need to restart TypeScript. 1. In VS Code, open the Command Palette. You can do so when you press F1 or select **View** > **Command Palette**. 2. Enter `typescript` and select and run the **TypeScript: Restart TS server** command. VS Code should now recognize the `$extends` method. What regions are Accelerate's cache nodes available in? [#what-regions-are-accelerates-cache-nodes-available-in] Accelerate runs on Cloudflare's network and cache hits are served from Cloudflare's 300+ locations. You can find the regions where Accelerate's cache nodes are available here: [https://www.cloudflare.com/network/](https://www.cloudflare.com/network/). What regions is Accelerate's connection pool available in? [#what-regions-is-accelerates-connection-pool-available-in] When no cache strategy is specified or in the event of a cache miss, the Prisma Client query is routed through Accelerate's connection pool. Currently, queries can be routed through any chosen region among the 16 available locations. Currently, the list of available regions are: * Asia Pacific, Mumbai (`ap-south-1`) * Asia Pacific, Seoul (`ap-northeast-2`) * Asia Pacific, Singapore (`ap-southeast-1`) * Asia Pacific, Sydney (`ap-southeast-2`) * Asia Pacific, Tokyo (`ap-northeast-1`) * Canada, Central (`ca-central-1`) * Europe, Frankfurt (`eu-central-1`) * Europe, Ireland (`eu-west-1`) * Europe, London (`eu-west-2`) * Europe, Paris (`eu-west-3`) * Europe, Stockholm (`eu-north-1`) * South America, Sao Paulo (`sa-east-1`) * US East, N. Virginia (`us-east-1`) * US East, Ohio (`us-east-2`) * US West, N. California (`us-west-1`) * US West, Oregon (`us-west-2`) You can also view the available regions when you're about to set up Accelerate or by visiting the **Settings** tab for Accelerate under the **Region** section in the Prisma Cloud Platform [dashboard](https://pris.ly/pdp). How does Accelerate know what region to fetch the cache from? [#how-does-accelerate-know-what-region-to-fetch-the-cache-from] Under the hood, Accelerate uses Cloudflare, which uses [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/) for network addressing and routing. An incoming request will be routed to the nearest data center or "node" in their network that has the capacity to process the request efficiently. To learn more about how this works, we recommend looking into [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/). How can I invalidate a cache on Accelerate? [#how-can-i-invalidate-a-cache-on-accelerate] You can invalidate the cache on-demand via the [`$accelerate.invalidate` API](/accelerate/reference/api-reference#accelerateinvalidate) if you're on a [paid plan](https://www.prisma.io/pricing#accelerate), or you can invalidate your entire cache, on a project level, a maximum of five times a day. This limit is set based on [your plan](https://www.prisma.io/pricing#accelerate). You can manage this via the Accelerate configuration page. What is Accelerate's consistency model? [#what-is-accelerates-consistency-model] Accelerate does not have a consistency model. It is not a distributed system where nodes need to reach a consensus (because data is only stored in the cache node(s) closest to the user). However, the data cached in Accelerate's cache nodes doesn't propagate to other nodes, so Accelerate by design doesn't need a consistency model. Accelerate implements a [read-through caching strategy](https://www.prisma.io/dataguide/managing-databases/introduction-database-caching#read-through) particularly suitable for read-heavy workloads. How is Accelerate different from other caching tools, such as Redis? [#how-is-accelerate-different-from-other-caching-tools-such-as-redis] * Accelerate is a *specialized* cache that allows you to optimize data access in code at the query level with a cache strategy. On the other hand, tools such as Redis and Memcached are *general-purpose* caches designed to be adaptable and flexible. * Accelerate is a managed service that reduces the time, risk, and engineering effort of building and maintaining a cache service. * By default, Accelerate is globally distributed, reducing the latency of your queries. Other cache tools would require additional configuration to make them available globally. When should I not use Accelerate's caching features? [#when-should-i-not-use-accelerates-caching-features] Accelerate is a global data cache and connection pool that allows you to optimize data access in code at the query level. While caching with Accelerate can greatly boost the performance of your app, it may not always the best choice for your use case. Accelerate's global cache feature may not be a good fit for your app if: * Your app is exclusively used within a specific region and both your application server and database are situated in that same region on the same network. For example, database queries will likely be much faster if your application server and database are in the same region and network. However, If your application server is in different regions or networks from your database, Accelerate will speed up your queries because the data will be cached in the closest data center to your application. * You *only* need a general-purpose cache. Accelerate is a connection pooler and a *specialized cache* that only caches your database query responses in code. A general-purpose cache, such as Redis, would allow you to cache data from multiple sources, such as external APIs, which Accelerate currently doesn't support. If general-purpose caching interests you, please share your feedback with us via our [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text). * Your application data *always* needs to be up-to-date on retrieval, making it difficult to establish a reasonable cache strategy. Even without using Accelerate's global cache, you can still greatly benefit from Accelerate by using its connection pool, especially in serverless or edge functions, where it is difficult to manage and scale database connections. You can learn more about the serverless challenge [here](/orm/prisma-client/setup-and-configuration/databases-connections#the-serverless-challenge). Can I use Accelerate with other ORMs/query builders/drivers? [#can-i-use-accelerate-with-other-ormsquery-buildersdrivers] No. We currently do not have any plans for supporting other ORMs/query builders or drivers. However, if you're interested in support for other libraries, feel free to reach out and let us know in our [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text) community in the `#help-and-questions` channel. What is the maximum allowed value for the ttl parameter when configuring cacheStrategy? [#what-is-the-maximum-allowed-value-for-the-ttl-parameter-when-configuring-cachestrategy] The [Time-to-live](/accelerate/caching) (`ttl`) parameter can be set for up to a *year*. However, it's important to note that items within the cache may be evicted if they are not frequently accessed. Based on our experimentation, we’ve seen cache items persist for around 18 hours. While items may remain in the cache for an extended period if they are actively accessed, there is no guarantee. > **Note**: Even frequently accessed items may occasionally be evicted from the cache. It's unlikely for an item to survive for up to or longer than a month, regardless of its activity level. Why doesn’t Accelerate fall back to the direct connection string during a service disruption? [#why-doesnt-accelerate-fall-back-to-the-direct-connection-string-during-a-service-disruption] In the rare event of a service disruption, falling back to a direct connection would bypass the connection pool. This could potentially deplete the database's available connections and cause other issues on the database level. If there is a service disruption, it's recommended to verify on the [status page](https://pris.ly/data-platform-status). You can reach out to one of Prisma's [support channels](/console/more/support) for assistance. > **Note:** Additionally, it's worth noting that some edge function runtime environments may not support direct connections with Prisma ORM. For further details, refer to our [Edge functions documentation](/orm/prisma-client/deployment/edge/overview). Are each of the queries within an interactive transaction counted separately for billing? [#are-each-of-the-queries-within-an-interactive-transaction-counted-separately-for-billing] Yes, [interactive transactions](/orm/prisma-client/queries/transactions#interactive-transactions) are billed based on the individual operations within the transaction. There is no charge for the start, commit, or rollback of the transaction itself. For example, in the following query, there are two billable queries: ```ts await prisma.$transaction(async (tx) => { await tx.user.deleteMany({ where: { name: "John Doe" } }); await tx.user.createMany({ data }); }); ``` However, when using the [`$transaction` API for sequential client operations](/orm/prisma-client/queries/transactions#sequential-operations), regardless of the number of queries within the array, it counts as only one billable query. For example: ```ts await prisma.$transaction([ prisma.user.deleteMany({ where: { name: "John Doe" } }), prisma.user.createMany({ data }), ]); ``` If you don't need [interactive transactions](/orm/prisma-client/queries/transactions#interactive-transactions), you can save costs and improve performance by using [sequential operations transactions](/orm/prisma-client/queries/transactions#sequential-operations). Sequential operations transactions perform better on Accelerate because they execute in one round-trip to the database, while interactive transactions require separate round-trips for start, commit, and each individual operation on the transaction. Can I increase my Accelerate query duration and response size limits? [#can-i-increase-my-accelerate-query-duration-and-response-size-limits] Yes, you can increase your Accelerate limits based on your subscription plan. Here are the configurable limits: | Limit | Free | Starter | Pro Plan | Business Plan | | ------------------------------------ | ---------------- | ---------------- | ---------------- | ---------------- | | **Query timeout** | Up to 10 seconds | Up to 10 seconds | Up to 20 seconds | Up to 60 seconds | | **Interactive transactions timeout** | Up to 15 seconds | Up to 15 seconds | Up to 30 seconds | Up to 90 seconds | | **Response size** | Up to 5 MB | Up to 5 MB | Up to 10 MB | Up to 20 MB | Check the [pricing page](https://www.prisma.io/pricing#accelerate) for more details on the available plans and their corresponding limits. > [!WARNING] > While you can increase these limits based on your subscription plan, it's *still* recommended to optimize your database operations. [Learn more in our troubleshooting guide.](/postgres/error-reference) How long does it take to invalidate a cache query result? [#how-long-does-it-take-to-invalidate-a-cache-query-result] As the cache needs to be cleared globally, it is difficult to provide a specific time frame. However, the cached data is eventually consistent and typically propagates to all PoPs within a few seconds. In very rare cases, it may take longer. Here is a [demo app](https://pris.ly/test-cache-invalidation) to test the time it takes to invalidate a cache query result. What is the difference between Invalidate and Revalidate? [#what-is-the-difference-between-invalidate-and-revalidate] **Invalidate**: The cache entry is deleted, and new data will be fetched on the next request, causing a cache miss. This removes stale data but may lead to slower responses until the cache is repopulated. **Revalidate**: The cache entry is updated proactively, ensuring the next request uses fresh data from the cache. This keeps the cache valid and maintains faster response times by avoiding cache misses. What is on-demand cache invalidation? [#what-is-on-demand-cache-invalidation] [On-demand cache invalidation](/accelerate/caching) lets applications instantly update specific cached data when it changes, instead of waiting for regular cache refresh cycles. This keeps information accurate and up-to-date for users. When should I use the cache invalidate API? [#when-should-i-use-the-cache-invalidate-api] The [cache invalidate API](/accelerate/caching) is essential when data consistency cannot wait for the cache’s standard expiration or revalidation. Key use cases include: * **Content updates**: When critical changes occur, such as edits to a published article, product updates, or profile modifications, that need to be visible immediately. * **Inventory management**: In real-time applications, like inventory or booking systems, where stock levels, availability, or reservation statuses must reflect the latest information. * **High-priority data**: For time-sensitive data, like breaking news or urgent notifications, where it’s essential for users to see the most current information right away. Using on-demand cache invalidation in these scenarios helps keep only the necessary data refreshed, preserving system performance while ensuring accurate, up-to-date information for users. How does Accelerate count queries for billing? [#how-does-accelerate-count-queries-for-billing] Accelerate counts queries at the Prisma Client invocation level. A single Prisma query may translate into multiple SQL statements under the hood, but it will only count as one query for billing purposes. This ensures straightforward, predictable billing that reflects the Prisma Client usage rather than the complexity of the underlying SQL operations. Queries are counted regardless of whether they are served from the cache or the database. Even if a query is retrieved from the cache, it still counts toward your query limit. How do I switch from GitHub login to email and password login? [#how-do-i-switch-from-github-login-to-email-and-password-login] If you previously signed up using GitHub and want to switch to email and password login, follow these steps: 1. Verify Your GitHub Email Address [#1-verify-your-github-email-address] * Check the primary email address associated with your GitHub account (e.g., from your GitHub profile or notification settings). 2. Create a New Email/Password Account [#2-create-a-new-emailpassword-account] * Go to the email/password sign-up page. * Use the **same email address** linked to your GitHub account to create the new account. * Our system will automatically connect your new email/password account to your existing data. 3. Test Your Login [#3-test-your-login] * Log out and try logging in with your email and the password you just created. > **Note**: If you encounter any issues, please contact our support team for help linking your accounts. ## Related pages - [`Feedback`](https://www.prisma.io/docs/accelerate/more/feedback): Learn where to submit feedback about Accelerate - [`Known limitations`](https://www.prisma.io/docs/accelerate/more/known-limitations): Learn about limitations of Accelerate - [`Troubleshooting`](https://www.prisma.io/docs/accelerate/more/troubleshoot): Troubleshoot common Prisma Accelerate errors and connection issues # Feedback (/docs/accelerate/more/feedback) Location: Accelerate > More > Feedback You can submit any feedback about Accelerate in our [Discord server](https://pris.ly/discord?utm_source=docs\&utm_medium=intro_text). ## Related pages - [`FAQ`](https://www.prisma.io/docs/accelerate/more/faq): Frequently asked questions about Accelerate - [`Known limitations`](https://www.prisma.io/docs/accelerate/more/known-limitations): Learn about limitations of Accelerate - [`Troubleshooting`](https://www.prisma.io/docs/accelerate/more/troubleshoot): Troubleshoot common Prisma Accelerate errors and connection issues # Known limitations (/docs/accelerate/more/known-limitations) Location: Accelerate > More > Known limitations Below are descriptions of known limitations when using Accelerate. If you encounter any additional ones, please share them with us via [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=intro_text). Cannot cache raw queries [#cannot-cache-raw-queries] At the moment, it is not possible to cache the responses of [raw queries](/orm/prisma-client/using-raw-sql/raw-queries). Not compatible with the fluent API [#not-compatible-with-the-fluent-api] Client Extensions (which are used in Accelerate) currently do not correctly forward the [fluent API](/orm/prisma-client/queries/relation-queries#fluent-api) types. We hope to get a fix into Client Extensions soon. Not compatible with extremely heavy or long-running queries [#not-compatible-with-extremely-heavy-or-long-running-queries] Accelerate is designed to work with high-performance, low-latency queries. It is not intended for use with extremely heavy or long-running queries that may cause performance issues or resource contention. While limits are configurable, we recommend optimizing your queries to ensure they fit within the recommended guidelines. For queries that cannot be optimized or pared down, we recommend one of two solutions: 1. **Use the read replica extension**: The Prisma ORM [read replica extension](https://www.npmjs.com/package/@prisma/extension-read-replicas) allows you to set up two different connections: a `primary` and a `replica`. You can set up your Accelerate connection as the `primary` and then a direct connection as the `replica`. Any queries that are resource-intensive or long-running can then be routed to the `replica`, while the `primary` (your Accelerate connection) will handle normal queries. **Please note** that this solution requires you to both set up a direct connection and requires the full generated Prisma Client (i.e. without `--no-engine`). 2. **Separate analytics queries**: Our preferred solution is to separate your analytics queries into a separate application. This separate application can then use a direct connection so that it can run heavy queries without impacting the performance or cost of your Accelerate-powered application. If you have a use case that requires running extremely heavy or long-running queries and Prisma Accelerate, please reach out to us. Not compatible with direct IPv4 addresses in MongoDB connection strings [#not-compatible-with-direct-ipv4-addresses-in-mongodb-connection-strings] Accelerate does not support direct IPv4 addresses in MongoDB connection strings. When an IPv4 address is provided, Accelerate converts it to an IPv6 format to route through its NAT gateway. This conversion may cause the connection string to be considered invalid due to the formatting of the port value. **Workaround**: To resolve this issue, create a DNS record that points to your IPv4 address and use that DNS record in your connection string instead of the direct IP. Example [#example] * **IPv4 connection string** (not supported): `mongodb://user:password@192.168.1.100:27017/db_name` * **DNS record connection string** (supported): `mongodb://user:password@my-database.example.com:27017/db_name` For additional details on Accelerate’s IPv6-first design, refer to our [blog post](https://www.prisma.io/blog/accelerate-ipv6-first). ## Related pages - [`FAQ`](https://www.prisma.io/docs/accelerate/more/faq): Frequently asked questions about Accelerate - [`Feedback`](https://www.prisma.io/docs/accelerate/more/feedback): Learn where to submit feedback about Accelerate - [`Troubleshooting`](https://www.prisma.io/docs/accelerate/more/troubleshoot): Troubleshoot common Prisma Accelerate errors and connection issues # Troubleshooting (/docs/accelerate/more/troubleshoot) Location: Accelerate > More > Troubleshooting When working with Accelerate, you may encounter errors often highlighted by specific error codes during development and operations. It is important to understand the meaning of these errors, why they occur, and how to resolve them in order to ensure the smooth operation of your applications. This guide aims to provide insights and steps to troubleshoot specific error codes encountered with Accelerate. P6009 (ResponseSizeLimitExceeded) [#p6009-responsesizelimitexceeded] This error is triggered when the response size from a database query exceeds the configured query response size limit. We've implemented this restriction to safeguard your application performance, as retrieving data over 5MB can significantly slow down your application due to multiple network layers. Typically, transmitting more than 5MB of data is common when conducting ETL (Extract, Transform, Load) operations. However, for other scenarios such as transactional queries, real-time data fetching for user interfaces, bulk data updates, or aggregating large datasets for analytics outside of ETL contexts, it should generally be avoided. These use cases, while essential, can often be optimized to work within the configured query response size limit, ensuring smoother performance and a better user experience. Possible causes for P6009 [#possible-causes-for-p6009] Transmitting images/files in response [#transmitting-imagesfiles-in-response] This error may arise if images or files stored within your table are being fetched, resulting in a large response size. Storing assets directly in the database is generally discouraged because it significantly impacts database performance and scalability. In addition to performance, it makes database backups slow and significantly increases the cost of storing routine backups. **Suggested solution:** Configure the query response size limit to be larger. If the limit is still exceeded, consider storing the image or file in a BLOB store like [Cloudflare R2](https://developers.cloudflare.com/r2/), [AWS S3](https://aws.amazon.com/pm/serv-s3/), or [Cloudinary](https://cloudinary.com/). These services allow you to store assets optimally and return a URL for access. Instead of storing the asset directly in the database, store the URL, which will substantially reduce the response size. Over-fetching of data [#over-fetching-of-data] In certain cases, a large number of records or fields are unintentionally fetched, which results in exceeding the configured query response size limit. This could happen when the [`where`](/orm/reference/prisma-client-reference#where) clause in the query is incorrect or entirely missing. **Suggested solution:** Configure the query response size limit to be larger. If the limit is still exceeded, double-check that the `where` clause is filtering data as expected. To prevent fetching too many records, consider using [pagination](/orm/prisma-client/queries/pagination). Additionally, use the [`select`](/orm/reference/prisma-client-reference#select) clause to return only the necessary fields, reducing the response size. Fetching a large volume of data [#fetching-a-large-volume-of-data] In many data processing workflows, especially those involving ETL (Extract-Transform-Load) processes or scheduled CRON jobs, there's a need to extract large amounts of data from data sources (like databases, APIs, or file systems) for analysis, reporting, or further processing. If you are running an ETL/CRON workload that fetches a huge chunk of data for analytical processing then you might run into this limit. **Suggested solution:** Configure the query response size limit to be larger. If the limit is exceeded, consider splitting your query into batches. This approach ensures that each batch fetches only a portion of the data, preventing you from exceeding the size limit for a single operation. P6004 (QueryTimeout) [#p6004-querytimeout] This error occurs when a database query fails to return a response within the configured query timeout limit. The query timeout limit includes the duration of waiting for a connection from the pool, network latency to the database, and the execution time of the query itself. We enforce this limit to prevent unintentional long-running queries that can overload system resources. > The time for Accelerate's cross-region networking is excluded from the configured query timeout limit. Possible causes for P6004 [#possible-causes-for-p6004] This error could be caused by numerous reasons. Some of the prominent ones are: High traffic and insufficient connections [#high-traffic-and-insufficient-connections] If the application is receiving very high traffic and there are not a sufficient number of connections available to the database, then the queries would need to wait for a connection to become available. This situation can lead to queries waiting longer than the configured query timeout limit for a connection, ultimately triggering a timeout error if they do not get serviced within this duration. **Suggested solution**: Review and possibly increase the `connection_limit` specified in the connection string parameter when setting up Accelerate in a platform environment. This limit should align with your database's maximum number of connections. By default, the connection limit is set to 10 unless a different `connection_limit` is specified in your database connection string. Long-running queries [#long-running-queries] Queries may be slow to respond, hitting the configured query timeout limit even when connections are available. This could happen if a very large amount of data is being fetched in a single query or if appropriate indexes are missing from the table. **Suggested solution**: Configure the query timeout limit to be larger. If the limit is exceeded, identify the slow-running queries and fetch only the necessary data. Use the `select` clause to retrieve specific fields and avoid fetching unnecessary data. Additionally, consider adding appropriate indexes to improve query efficiency. You might also isolate long-running queries into separate environments to prevent them from affecting transactional queries. Database resource contention [#database-resource-contention] A common yet challenging issue is when other services operating on the same database perform heavy analytics or data processing tasks, significantly consuming database resources. These operations can monopolize database connections and processing power, leading to a scenario where even simple queries cannot be executed in a timely manner. This "busy" or "noisy" database environment can cause queries that are typically fast to run slowly or even timeout, particularly during periods of high activity from other services. Users often rely on CPU and memory usage metrics to gauge database load, which can be misleading. While these are important indicators, they might not fully represent the database's operational state. Direct metrics like the number of reads, writes, and wait times offer a clearer view of the database's performance and should be monitored closely. A noticeable degradation in these metrics, especially in the absence of changes to the queries or data model, suggests that external pressures are affecting database performance. **Suggested solution**: If normally quick queries are intermittently slow or timing out without any modifications to them, it's probable that competing queries are exerting pressure on the same database tables. To diagnose this, adopt monitoring tools or leverage your database's inherent capabilities to observe reads, writes, and wait times. Such monitoring will unveil activity patterns or spikes that align with the observed performance dips. Moreover, it's crucial to periodically scrutinize and refine essential queries and verify that tables are properly indexed. This proactive approach minimizes the vulnerability of these queries to slowdowns caused by competing workloads. Considerations for P6009 and P6004 errors [#considerations-for-p6009-and-p6004-errors] For runtimes that support Prisma ORM natively, you could consider creating two `PrismaClient` Instances. One with the Accelerate connection string (prefixed with `prisma://`) and the other one with the direct database connection string (prefixed with `postgres://`, `mysql://` etc). The main idea behind this approach is to bypass Accelerate for certain specific queries. However, please note that the available connections would be split between both of your `PrismaClient` Instances. It's crucial to understand the implications of managing multiple instances, particularly in regards to direct database connections. Utilizing a `PrismaClient` instance with a direct database connection string means that this connection will interact directly with your database. This approach requires careful consideration because the direct connections and those managed by Accelerate share the same underlying database connection pool. This can lead to competition for resources, potentially affecting the performance and availability of your database services. Additionally, direct connections could have a significant impact on your database's performance and availability. Operations that consume a considerable amount of resources could potentially degrade the service for other users or processes that rely on the same database. If your application's runtime environment supports Prisma ORM natively and you're considering this strategy to circumvent P6009 and P6004 errors, you might create two `PrismaClient` instances: 1. An instance using the Accelerate connection string (prefixed with `prisma://`) for general operations. 2. Another instance with the direct database connection string (e.g., prefixed with `postgres://`, `mysql://`, etc.) for specific operations anticipated to exceed the configured query timeout limit or to result in responses larger than the configured query response size limit. ```ts export const prisma = new PrismaClient({ datasourceUrl: process.env.DIRECT_DB_CONNECTION, }); export const prismaAccelerate = new PrismaClient({ datasourceUrl: process.env.ACCELERATE_CONNECTION, }).$extends(withAccelerate()); ``` This setup allows you to strategically direct certain operations through the direct connection, mitigating the risk of encountering the aforementioned errors. However, this decision should be made with a comprehensive understanding of the potential consequences and an assessment of whether your database infrastructure can support this additional load without compromising overall performance and availability. > Also see [**why doesn’t Accelerate fall back to the direct connection string during a service disruption?**](/accelerate/more/faq#why-doesnt-accelerate-fall-back-to-the-direct-connection-string-during-a-service-disruption) P6008 (ConnectionError|EngineStartError) [#p6008-connectionerrorenginestarterror] This error indicates that Prisma Accelerate cannot establish a connection to your database, potentially due to several reasons. Possible causes for P6008 [#possible-causes-for-p6008] Database Not Publicly accessible [#database-not-publicly-accessible] If your database is within a VPC or access is limited to specific IP addresses, you might encounter this error if static IP is not enabled for Accelerate or if the static IPs are not permitted in your database firewall. **Suggested solution:** [Enable static IP for Accelerate](/accelerate/static-ip) and configure your database firewall to allow access from the provided static IP addresses. Unreachable Database Host/Port [#unreachable-database-hostport] If the database’s server address (hostname) and port are incorrect or unreachable then you may encounter this error. **Suggested solution:** Verify the hostname/port of the database connection string that was provided while creating the Prisma Accelerate project. Additionally, attempt to connect to the database using a Database GUI tool (e.g., [Prisma Studio](https://www.prisma.io/studio), [TablePlus](https://tableplus.com/), or [DataGrip](https://www.jetbrains.com/datagrip/)) for further investigation. Incorrect username/password/database name [#incorrect-usernamepassworddatabase-name] This error can happen when the wrong credentials are provided to Prisma Accelerate, preventing it from establishing a connection to your database. **Suggested solution:** Verify the correctness of your database's username, password, and name in the connection string provided to Prisma Accelerate. Ensure that these credentials match those required by your database. Testing the connection using a direct database GUI tool can also help in confirming if the provided credentials are correct. Database taking too long to respond [#database-taking-too-long-to-respond] If the database is taking too long to respond to the connection request, Prisma Accelerate may timeout and throw this error. This could happen if the database is not active or is waking up from sleep mode. **Suggested solution:** Verify that the database is active and reachable. If the database is in sleep mode, try to wake it up by sending a request to it using a direct database GUI tool or wake it up using the database's management console. P5011 (TooManyRequests) [#p5011-toomanyrequests] This error occurs when Prisma Accelerate detects a high volume of requests that surpasses allowable thresholds. It acts as a protective measure to safeguard both Prisma Accelerate and your underlying database from excessive load. Possible causes for P5011 [#possible-causes-for-p5011] Aggressive retry loops [#aggressive-retry-loops] If your application retries queries immediately or with minimal delay, especially after receiving certain errors, the rapid accumulation of requests can surpass the threshold. **Suggested solution:** * Implement an exponential backoff strategy. Rather than retrying immediately or with a fixed delay, gradually increase the delay period after each failed attempt. * This allows the system time to recover and reduces the likelihood of overwhelming Prisma Accelerate and your database. Sudden traffic spikes [#sudden-traffic-spikes] Unpredicted traffic surges (for example, during product launches, flash sales, or viral growth events) can cause the threshold to be met and result into `P5011`. **Suggested solution:** * Consider proactive scaling strategies for both Prisma Accelerate and your database. * Monitor traffic and resource usage. If you anticipate a surge, please contact [support](/console/more/support) for capacity planning and potential configuration adjustments. Prolonged or planned high workloads [#prolonged-or-planned-high-workloads] Certain processes, such as bulk data imports, ETL operations, or extended CRON jobs, can generate continuous high query volume over time. **Suggested solution:** * Use batching or chunking techniques to break large operations into smaller parts. * Establish throttling or scheduling to distribute the load more evenly. Other errors [#other-errors] Error with MySQL (Aiven): "We were unable to process your request. Please refresh and try again." [#error-with-mysql-aiven-we-were-unable-to-process-your-request-please-refresh-and-try-again] Issue [#issue] When using an Aiven MySQL connection string that includes the `?ssl-mode=REQUIRED` parameter, you may encounter the following error: ``` We were unable to process your request. Please refresh and try again. ``` Cause [#cause] The `ssl-mode=REQUIRED` parameter is incompatible with Accelerate, which leads to connection issues. Suggested solution [#suggested-solution] To resolve this error, remove the `?ssl-mode=REQUIRED` parameter from your MySQL connection string. Example [#example] * Original connection string: `mysql://username:password@host:port/database?ssl-mode=REQUIRED` * Updated connection string: `mysql://username:password@host:port/database` ## Related pages - [`FAQ`](https://www.prisma.io/docs/accelerate/more/faq): Frequently asked questions about Accelerate - [`Feedback`](https://www.prisma.io/docs/accelerate/more/feedback): Learn where to submit feedback about Accelerate - [`Known limitations`](https://www.prisma.io/docs/accelerate/more/known-limitations): Learn about limitations of Accelerate # API Reference (/docs/accelerate/reference/api-reference) Location: Accelerate > Reference > API Reference The Accelerate API reference documentation is based on the following schema: ```prisma model User { id Int @id @default(autoincrement()) name String? email String @unique } ``` All example are based on the `User` model. cacheStrategy [#cachestrategy] With the Accelerate extension for Prisma Client, you can use the `cacheStrategy` parameter for model queries and use the [`ttl`](/accelerate/caching) and [`swr`](/accelerate/caching) parameters to define a cache strategy for Accelerate. The Accelerate extension requires that you install Prisma Client version `4.10.0`. Options [#options] The `cacheStrategy` parameter takes an option with the following keys: | Option | Example | Type | Required | Description | | ------ | ---------- | ---------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `swr` | `60` | `Int` | No | The stale-while-revalidate time in seconds. | | `ttl` | `60` | `Int` | No | The time-to-live time in seconds. | | `tags` | `["user"]` | `String[]` | No | The `tag` serves as a variable to control the invalidation of specific queries within your application. It is an optional array of strings to [invalidate](/accelerate/reference/api-reference#accelerateinvalidate) the cache, with each tag containing only alphanumeric characters and underscores, and a maximum length of 64 characters. | | Examples [#examples] Add a caching strategy to the query, defining a 60-second stale-while-revalidate (SWR) value, a 60-second time-to-live (TTL) value, and a cache tag of `"emails_with_alice"`: ```ts highlight=7:11;normal await prisma.user.findMany({ where: { email: { contains: "alice@prisma.io", }, }, cacheStrategy: { // [!code highlight] swr: 60, // [!code highlight] ttl: 60, // [!code highlight] tags: ["emails_with_alice"], // [!code highlight] }, // [!code highlight] }); ``` Supported Prisma Client operations [#supported-prisma-client-operations] The following is a list of all read query operations that support `cacheStrategy`: * [`findUnique()`](/orm/reference/prisma-client-reference#findunique) * [`findUniqueOrThrow()`](/orm/reference/prisma-client-reference#finduniqueorthrow) * [`findFirst()`](/orm/reference/prisma-client-reference#findfirst) * [`findFirstOrThrow()`](/orm/reference/prisma-client-reference#findfirstorthrow) * [`findMany()`](/orm/reference/prisma-client-reference#findmany) * [`count()`](/orm/reference/prisma-client-reference#count) * [`aggregate()`](/orm/reference/prisma-client-reference#aggregate) * [`groupBy()`](/orm/reference/prisma-client-reference#groupby) The `cacheStrategy` parameter is not supported on any write operations, such as `create()`. withAccelerateInfo [#withaccelerateinfo] Any query that supports the `cacheStrategy` can append `withAccelerateInfo()` to wrap the response data and include additional information about the Accelerate response. To retrieve the status of the response, use: ```ts const { data, info } = await prisma.user .count({ cacheStrategy: { ttl: 60, swr: 600 }, where: { myField: "value" }, }) .withAccelerateInfo(); console.dir(info); ``` Notice the `info` property of the response object. This is where the request information is stored. Return type [#return-type] The `info` object is of type `AccelerateInfo` and follows the interface below: ```ts interface AccelerateInfo { cacheStatus: "ttl" | "swr" | "miss" | "none"; lastModified: Date; region: string; requestId: string; signature: string; } ``` | Property | Type | Description | | -------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cacheStatus` | `"ttl" \| "swr" \| "miss" \| "none" ` | The cache status of the response.
  • `ttl` indicates a cache hit within the `ttl` duration and no database query was executed
  • `swr` indicates a cache hit within the `swr` duration and the data is being refreshed by Accelerate in the background
  • `miss` indicates that both `ttl` and `swr` have expired and the database query was executed by the request
  • `none` indicates that no cache strategy was specified and the database query was executed by the request
| | `lastModified` | `Date` | The date the response was last refreshed. | | `region` | `String` | The data center region that received the request. | | `requestId` | `String` | Unique identifier of the request. Useful for troubleshooting. | | `signature` | `String` | The unique signature of the Prisma operation. | $accelerate.invalidate [#accelerateinvalidate] You can invalidate the cache using the [`$accelerate.invalidate` API](/accelerate). > [!NOTE] > To invalidate cached query results on-demand, a paid plan is required. Each plan has specific limits on the number of cache tag-based invalidations allowed per day, though there are no limits on calling the `$accelerate.invalidate` API itself. See our [pricing for more details](https://www.prisma.io/pricing#accelerate). Example [#example] To invalidate the query below: ```ts await prisma.user.findMany({ where: { email: { contains: "alice@prisma.io", }, }, cacheStrategy: { swr: 60, ttl: 60, tags: ["emails_with_alice"], // [!code highlight] }, }); ``` You need to provide the cache tag in the `$accelerate.invalidate` API: ```ts try { await prisma.$accelerate.invalidate({ // [!code highlight] tags: ["emails_with_alice"], // [!code highlight] }); // [!code highlight] } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError) { // The .code property can be accessed in a type-safe manner if (e.code === "P6003") { console.log("The cache invalidation rate limit has been reached. Please try again later."); } } throw e; } ``` > [!NOTE] > You can invalidate up to 5 tags per call. $accelerate.invalidateAll [#accelerateinvalidateall] You can invalidate the entire cache using the `$accelerate.invalidateAll` API. Example [#example-1] To invalidate the query below: ```ts await prisma.user.findMany({ where: { email: { contains: "alice@prisma.io", }, }, cacheStrategy: { swr: 60, ttl: 60, tags: ["emails_with_alice"], // [!code highlight] }, }); ``` Just call the `$accelerate.invalidateAll` API: ```ts try { await prisma.$accelerate.invalidateAll(); // [!code highlight] } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError) { if (e.code === "P6003") { console.log("The cache invalidation rate limit has been reached. Please try again later."); } } throw e; } ``` Why use $accelerate.invalidateAll? [#why-use-accelerateinvalidateall] This method offers better editor support (e.g. IntelliSense) than alternatives like `invalidate("all")`. > [!WARNING] > This clears cache for the entire environment—use with care. Providing a Custom Fetch Implementation [#providing-a-custom-fetch-implementation] Starting from Accelerate version `2.0.0`, you can provide a custom implementation of the fetch function when extending the Prisma Client with Accelerate. This allows you greater flexibility and control over how HTTP requests are handled within your application. To pass a custom fetch implementation, you can use the following pattern: ```ts const myFetch = (input: URL, init?: RequestInit): Promise => { // Your custom fetch logic here return fetch(input, init); }; const prisma = new PrismaClient().$extends(withAccelerate({ fetch: myFetch })); ``` Errors [#errors] Prisma Accelerate-related errors start with `P6xxx`. You can find the full error code reference for Prisma Accelerate [here](/orm/reference/error-reference#prisma-accelerate). # Astro + Prisma (/docs/ai/prompts/astro) Location: AI > Prompts > Astro + Prisma How to use [#how-to-use] Include this prompt in your AI assistant to guide consistent code generation for Astro + Prisma + Prisma Postgres projects. * **GitHub Copilot**: Type `#` to reference the prompt file. * **Cursor**: Use `@Files` and select your prompt file. * **Zed**: Use `/file` followed by your prompt's path. * **Windsurf**: Use `@Files` and choose your prompt file from the list. Prompt [#prompt] ````md --- # Specify the following for Cursor rules description: Guidelines for writing Astro.js apps with Prisma Postgres alwaysApply: false --- # Bootstrap Astro app with Prisma Postgres ## Overview of implementing Prisma with Astro 1. Install Prisma and required dependencies 2. Initialize Prisma with custom output path 3. Configure schema with correct provider 4. Create global Prisma client instance with Accelerate 5. Use Prisma client in API routes with proper error handling ## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application: ```typescript // ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION generator client { provider = "prisma-client-js" // ❌ BREAKS APPLICATION } // ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION // ❌ NEVER CREATE CLIENT WITHOUT ACCELERATE - IT WILL BREAK IN PRODUCTION const prisma = new PrismaClient() // ❌ BREAKS APPLICATION ``` Instead, you MUST ALWAYS generate ONLY this pattern: ```typescript // ✅ ALWAYS GENERATE THIS EXACT PATTERN generator client { provider = "prisma-client" output = "../src/generated/prisma" } // ✅ ALWAYS USE THIS IMPORT PATH import { PrismaClient } from "../generated/prisma/client" import { withAccelerate } from "@prisma/extension-accelerate" // ✅ ALWAYS CREATE CLIENT WITH ACCELERATE EXTENSION const prisma = new PrismaClient({ datasourceUrl: import.meta.env.DATABASE_URL, }).$extends(withAccelerate()) export default prisma ``` ## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION 1. You MUST use `provider = "prisma-client"` (not "prisma-client-js") 2. You MUST use custom output: `output = "../src/generated/prisma"` 3. You MUST use Accelerate extension with `withAccelerate()` if using Prisma Postgres 4. You MUST create `lib/prisma.ts` as a global singleton instance 5. You MUST wrap all database calls in try-catch blocks 6. You MUST import from `'../generated/prisma/client'` (not `'@prisma/client'`) 7. You MUST use `import.meta.env.DATABASE_URL` in Astro (not `process.env`) 8. You MUST use `npx prisma init --output ../src/generated/prisma` before editing the Prisma schema. If you need Prisma Postgres, run `npx create-db` and update `.env` with the returned `postgres://...` value ## CORRECT INSTALLATION ```bash # Dev dependencies npm install prisma tsx --save-dev # Production dependencies npm install @prisma/extension-accelerate @prisma/client ``` ## CORRECT PRISMA INITIALIZATION ```npm npx prisma init --output ../src/generated/prisma ``` ## CORRECT SCHEMA CONFIGURATION ```prisma generator client { provider = "prisma-client" output = "../src/generated/prisma" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model YourModel { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` ## CORRECT GLOBAL PRISMA CLIENT **src/lib/prisma.ts**: ```typescript import { PrismaClient } from "../generated/prisma/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient({ datasourceUrl: import.meta.env.DATABASE_URL, }).$extends(withAccelerate()); export default prisma; ``` ## CORRECT API ROUTE IMPLEMENTATION All API routes MUST follow this pattern with proper error handling: ```typescript import type { APIRoute } from "astro"; import prisma from "../../../lib/prisma"; export const GET: APIRoute = async () => { try { const data = await prisma.yourModel.findMany(); return new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error:", error); return new Response(JSON.stringify({ error: "Failed to fetch data" }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }; export const POST: APIRoute = async ({ request }) => { try { const body = await request.json(); // Validate required fields if (!body.requiredField) { return new Response(JSON.stringify({ error: "Required field missing" }), { status: 400, headers: { "Content-Type": "application/json" }, }); } const result = await prisma.yourModel.create({ data: body, }); return new Response(JSON.stringify(result), { status: 201, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error:", error); return new Response(JSON.stringify({ error: "Failed to create data" }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }; ``` ## CORRECT USAGE IN ASTRO PAGES Server-side data fetching in Astro pages: ```astro --- import prisma from '../lib/prisma' // Fetch data on the server const data = await prisma.yourModel.findMany() --- {data.map(item => (
{item.name}
))} ``` ## AI MODEL VERIFICATION STEPS Before generating any code, you MUST verify: 1. Are you using `provider = "prisma-client"` (not "prisma-client-js")? If not, STOP and FIX. 2. Are you using `output = "../src/generated/prisma"`? If not, STOP and FIX. 3. Are you importing from `'../generated/prisma/client'`? If not, STOP and FIX. 4. Are you using `withAccelerate()` extension? If not, STOP and FIX. 5. Are you wrapping database operations in try-catch? If not, STOP and FIX. 6. Are you using `import.meta.env` (not `process.env`)? If not, STOP and FIX. 7. Did you use `--generator-provider prisma-client` (NOT `postgresql`)? If not, STOP and FIX. ## CONSEQUENCES OF INCORRECT IMPLEMENTATION If you generate code using: - `prisma-client-js` provider - Default import from `@prisma/client` - PrismaClient without Accelerate extension - Missing custom output path The implementation will: 1. Break in production 2. Cause connection pool exhaustion 3. Fail to maintain proper database connections 4. Result in import errors 5. Cause performance issues ## USEFUL COMMANDS ```npm npx prisma generate # Regenerate client after schema changes ``` ```npm npx prisma migrate dev --name X # Create and apply migration ``` ```npm npx prisma studio # Open visual database editor ``` ```npm npx prisma db push # Push schema without migration ``` ## AI MODEL RESPONSE TEMPLATE When asked about Prisma + Astro implementation, you MUST: 1. ONLY use code from this guide 2. NEVER suggest deprecated approaches 3. ALWAYS use the exact patterns shown above 4. VERIFY your response against the patterns shown here 5. ALWAYS include error handling in API routes 6. ALWAYS use the global prisma instance from `lib/prisma.ts` Remember: There are NO EXCEPTIONS to these rules. ```` Running the application [#running-the-application] Get your application running locally in three quick steps: **1. Generate the Prisma Client:** ```bash npx prisma generate --no-engine ``` **2. View your database in Prisma Studio:** ```bash npm run db:studio ``` Prisma Studio opens at `localhost:5555` where you can inspect your `User` table and see the test user stored in your database. **3. Start your Next.js development server:** ```bash npm run dev ``` Visit `http://localhost:3000` to see your Next.js application live, displaying your first user fetched directly from your Prisma Postgres database! ## Related pages - [`Migrate to Prisma v7`](https://www.prisma.io/docs/ai/prompts/prisma-7): Step-by-step guide for migration your app to use the version 7 of Prisma ORM - [`Next.js + Prisma`](https://www.prisma.io/docs/ai/prompts/nextjs): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project - [`Nuxt + Prisma`](https://www.prisma.io/docs/ai/prompts/nuxt): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Nuxt project - [`Turborepo + Prisma`](https://www.prisma.io/docs/ai/prompts/turborepo): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo # Next.js + Prisma (/docs/ai/prompts/nextjs) Location: AI > Prompts > Next.js + Prisma Prerequisites [#prerequisites] Before using this prompt, you need to create a new Next.js project: ```bash npx create-next-app@latest my-app cd my-app ``` When prompted, select the following recommended options: * **TypeScript**: Yes * **ESLint**: Yes * **Tailwind CSS**: Yes (optional) * **`src/` directory**: No * **App Router**: Yes * **Turbopack**: Yes (optional) * **Import alias**: Use default (`@/*`) Once your Next.js project is created, you can use the prompt below with your AI assistant to add Prisma and Prisma Postgres. How to use [#how-to-use] Include this prompt in your AI assistant to guide consistent code generation for NextJS + Prisma + Prisma Postgres projects. * **GitHub Copilot**: Type `#` to reference the prompt file. * **Cursor**: Use `@Files` and select your prompt file. * **Zed**: Use `/file` followed by your prompt's path. * **Windsurf**: Use `@Files` and choose your prompt file from the list. Video Tutorial [#video-tutorial] Watch this step-by-step walkthrough showing this prompt in action: [Watch video](https://www.youtube.com/watch?v=Aqkc95jtHzM) Prompt [#prompt] ````md --- # Specify the following for Cursor rules description: Guidelines for writing Next.js apps with Prisma Postgres alwaysApply: false --- # Bootstrap Next.js app with Prisma Postgres (Prisma v7) > **Note**: This guide is updated for **Prisma ORM 7**. Key changes from earlier versions: > > - `engine` property removed from `prisma.config.ts` > - `url` removed from datasource in `schema.prisma` (now only in `prisma.config.ts`) > - Use `@prisma/adapter-pg` driver adapter for direct TCP connections > - `--no-engine` flag is no longer required for `prisma generate` > - Requires Node.js 20.19+ and TypeScript 5.4.0+ ## Overview of implementing Prisma with Next.js 1. Install Prisma and required dependencies (including dotenv) 2. Initialize Prisma and configure schema 3. Configure dotenv for environment variables 4. Create global Prisma client instance with Pg Adapter 5. Add npm scripts for testing and database management 6. Create test script to verify setup 7. Use Prisma client in API routes and pages with proper error handling ## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application: ```typescript // ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION generator client { provider = "prisma-client-js" // ❌ BREAKS APPLICATION } // ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION // ❌ WRONG IMPORT PATH - MISSING /client - IT WILL BREAK THE APPLICATION import { PrismaClient } from "../app/generated/prisma" // ❌ BREAKS APPLICATION // ❌ NEVER USE ACCELERATE - IT IS NOT USED IN THIS WORKFLOW import { withAccelerate } from "@prisma/extension-accelerate" // ❌ BREAKS APPLICATION // ❌ NEVER USE accelerateUrl - IT WILL BREAK THE APPLICATION const prisma = new PrismaClient({ accelerateUrl: process.env.DATABASE_URL, // ❌ BREAKS APPLICATION - use adapter }) // ❌ NEVER include url in datasource block - IT WILL BREAK THE APPLICATION datasource db { provider = "postgresql" url = env("DATABASE_URL") // ❌ BREAKS APPLICATION - moved to prisma.config.ts } // ❌ NEVER include engine property - IT WILL BREAK THE APPLICATION export default defineConfig({ engine: "classic", // ❌ BREAKS APPLICATION - removed in Prisma v7 }) // ❌ NEVER use Prisma Postgres HTTP URLs - ONLY use TCP URLs DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..." // ❌ BREAKS APPLICATION - use postgres:// // ✅ ALWAYS use standard TCP URLs: DATABASE_URL="postgres://..." // ✅ CORRECT ``` Instead, you MUST ALWAYS generate ONLY this pattern: ```typescript // ✅ ALWAYS GENERATE THIS EXACT PATTERN generator client { provider = "prisma-client" output = "../app/generated/prisma" } // ✅ CRITICAL: MUST include /client at the end of import path import { PrismaClient } from "../app/generated/prisma/client" import { PrismaPg } from "@prisma/adapter-pg" const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }) const globalForPrisma = global as unknown as { prisma: PrismaClient } const prisma = globalForPrisma.prisma || new PrismaClient({ adapter, }) if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma export default prisma ``` ## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION 1. You MUST use `provider = "prisma-client"` (not "prisma-client-js") 2. You MUST use custom output: `output = "../app/generated/prisma"` 3. You MUST use `@prisma/adapter-pg` driver adapter 4. You MUST create `lib/prisma.ts` as a global singleton instance 5. You MUST wrap all database calls in try-catch blocks 6. You MUST import from `'../app/generated/prisma/client'` (not `'@prisma/client'` or `'../app/generated/prisma'`) 7. You MUST use `adapter` property in PrismaClient constructor 8. You MUST install `dotenv` and add `import "dotenv/config"` to `prisma.config.ts` 9. You MUST add npm scripts for `db:test` and `db:studio` to package.json 10. You MUST create a test script at `scripts/test-database.ts` to verify setup 11. You MUST NOT include `url` in the datasource block of `schema.prisma` 12. You MUST NOT include `engine` property in `prisma.config.ts` 13. You MUST use `npx prisma init --output ../app/generated/prisma` to scaffold Prisma, then `npx create-db` to create a real cloud database 14. You MUST use standard TCP URLs (`postgres://...`) in .env 15. You MUST NOT use `accelerateUrl` or `withAccelerate` ## VERSION REQUIREMENTS - **Node.js**: 20.19 or higher (Node.js 18 is NOT supported) - **TypeScript**: 5.4.0 or higher (5.9.x recommended) - **Prisma**: 7.0.0 or higher ## CORRECT INSTALLATION ```bash # Dev dependencies npm install prisma tsx --save-dev # Production dependencies npm install @prisma/adapter-pg @prisma/client dotenv ``` ## CORRECT PRISMA INITIALIZATION > **FOR AI ASSISTANTS**: `npx prisma init` is not interactive. Run it yourself if your environment allows it. If you need a real Prisma Postgres database, either run `npx create-db` or ask the user to run it and update `DATABASE_URL` before you continue. ```bash # Initialize Prisma and scaffold the Prisma files npx prisma init --output ../app/generated/prisma # Then create a Prisma Postgres database npx create-db ``` This step: - Generates `prisma/schema.prisma` with the correct output path - Generates `prisma.config.ts` - Generates `.env` with a local `DATABASE_URL` - Requires `npx create-db` if you want a real Prisma Postgres database **IMPORTANT**: After `npx create-db`, replace the generated `DATABASE_URL` in `.env` with the returned `postgres://...` connection string. ```text DATABASE_URL="postgres://..." ``` ## CORRECT PRISMA CONFIG (prisma.config.ts) When using `npx prisma init`, the `prisma.config.ts` is **auto-generated** with the correct configuration: ```typescript import "dotenv/config"; // ✅ Auto-included by prisma init import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, // ✅ NO engine property - removed in Prisma v7 datasource: { url: env("DATABASE_URL"), }, }); ``` **Note**: If you need to manually create this file, ensure `import "dotenv/config"` is at the top. ## CORRECT SCHEMA CONFIGURATION (prisma/schema.prisma) Update the generated `prisma/schema.prisma` file: ```prisma generator client { provider = "prisma-client" output = "../app/generated/prisma" } datasource db { provider = "postgresql" // ✅ NO url here - now configured in prisma.config.ts } // Example User model for testing model User { id Int @id @default(autoincrement()) email String @unique name String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` ## CORRECT GLOBAL PRISMA CLIENT Create `lib/prisma.ts` file: ```typescript import { PrismaClient } from "../app/generated/prisma/client"; // ✅ CRITICAL: Include /client import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const globalForPrisma = global as unknown as { prisma: PrismaClient }; const prisma = globalForPrisma.prisma || new PrismaClient({ adapter, }); if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; export default prisma; ``` ## ADD NPM SCRIPTS TO PACKAGE.JSON Update your `package.json` to include these scripts: ```json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "eslint", "db:test": "tsx scripts/test-database.ts", "db:studio": "prisma studio" } } ``` ## CREATE TEST SCRIPT Create `scripts/test-database.ts` to verify your setup: ```typescript import "dotenv/config"; // ✅ CRITICAL: Load environment variables import prisma from "../lib/prisma"; async function testDatabase() { console.log("🔍 Testing Prisma Postgres connection...\n"); try { // Test 1: Check connection console.log("✅ Connected to database!"); // Test 2: Create a test user console.log("\n📝 Creating a test user..."); const newUser = await prisma.user.create({ data: { email: "demo@example.com", name: "Demo User", }, }); console.log("✅ Created user:", newUser); // Test 3: Fetch all users console.log("\n📋 Fetching all users..."); const allUsers = await prisma.user.findMany(); console.log(`✅ Found ${allUsers.length} user(s):`); allUsers.forEach((user) => { console.log(` - ${user.name} (${user.email})`); }); console.log("\n🎉 All tests passed! Your database is working perfectly.\n"); } catch (error) { console.error("❌ Error:", error); process.exit(1); } } testDatabase(); ``` ## CORRECT API ROUTE IMPLEMENTATION (App Router) Create `app/api/users/route.ts` with GET and POST handlers: ```typescript import { NextRequest, NextResponse } from "next/server"; import prisma from "../../../lib/prisma"; export async function GET(request: NextRequest) { try { const users = await prisma.user.findMany(); return NextResponse.json(users); } catch (error) { console.error("Error fetching users:", error); return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const body = await request.json(); const user = await prisma.user.create({ data: { email: body.email, name: body.name, }, }); return NextResponse.json(user, { status: 201 }); } catch (error) { console.error("Error creating user:", error); return NextResponse.json({ error: "Failed to create user" }, { status: 500 }); } } ``` ## CORRECT USAGE IN SERVER COMPONENTS Update `app/page.tsx` to display users from the database: ```typescript import prisma from "../lib/prisma"; export default async function Home() { let users: Array<{ id: number; email: string; name: string | null; createdAt: Date; updatedAt: Date; }> = []; let error = null; try { users = await prisma.user.findMany({ orderBy: { createdAt: "desc", }, }); } catch (e) { console.error("Error fetching users:", e); error = "Failed to load users. Make sure your DATABASE_URL is configured."; } return (

Users from Database

{error ? (

{error}

) : users.length === 0 ? (

No users yet. Create one using the API at /api/users

) : (
    {users.map((user) => (
  • {user.name || "No name"}

    {user.email}

  • ))}
)}
); } ``` ## COMPLETE SETUP WORKFLOW User should follow these steps (AI should provide these instructions): 1. **Install dependencies**: ```npm npm install prisma tsx --save-dev ``` ```npm npm install @prisma/adapter-pg @prisma/client dotenv ``` 2. **Initialize Prisma, then create Prisma Postgres:** > **AI ASSISTANT**: You can run `npx prisma init` yourself. If you should not provision cloud resources automatically, ask the user to run `npx create-db` and update `DATABASE_URL` before continuing. ```npm npx prisma init --output ../app/generated/prisma npx create-db ``` This creates `prisma/schema.prisma`, `prisma.config.ts`, and `.env`, then returns a `postgres://...` connection string for Prisma Postgres. **If you asked the user to run `npx create-db`, wait for them to share or paste the returned connection string before proceeding.** 3. **Verify `.env` was created** - Replace the generated `DATABASE_URL` with the `postgres://...` connection string returned by `npx create-db`. ```text DATABASE_URL="postgres://..." ``` **Do NOT invent this URL. Use the one returned by `npx create-db`.** 4. **Update `prisma/schema.prisma`** - Add the User model (generator and datasource are already configured): ```prisma model User { id Int @id @default(autoincrement()) email String @unique name String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` 5. **Create `lib/prisma.ts`** with correct import path including `/client` and using `@prisma/adapter-pg`. 6. **Add npm scripts** to `package.json` for `db:test` and `db:studio` 7. **Create `scripts/test-database.ts`** test script 8. **Push schema to database**: ```npm npx prisma db push ``` 9. **Generate Prisma Client**: ```npm npx prisma generate ``` 10. **Test the setup**: ```bash npm run db:test ``` 11. **Start development server**: ```bash npm run dev ``` ## AI MODEL VERIFICATION STEPS Before generating any code, you MUST verify: 1. Are you using `provider = "prisma-client"` (not "prisma-client-js")? If not, STOP and FIX. 2. Are you using `output = "../app/generated/prisma"`? If not, STOP and FIX. 3. Are you importing from `'../app/generated/prisma/client'` (with `/client`)? If not, STOP and FIX. 4. Did you add `import "dotenv/config"` to `prisma.config.ts`? If not, STOP and FIX. 5. Did you add `import "dotenv/config"` to `scripts/test-database.ts`? If not, STOP and FIX. 6. Are you using `@prisma/adapter-pg`? If not, STOP and FIX. 7. Are you using `adapter` property in PrismaClient constructor? If not, STOP and FIX. 8. Are you wrapping database operations in try-catch? If not, STOP and FIX. 9. Did you create the test script at `scripts/test-database.ts`? If not, STOP and FIX. 10. Did you add `db:test` and `db:studio` scripts to package.json? If not, STOP and FIX. 11. Did you remove `url` from the datasource block in `schema.prisma`? If not, STOP and FIX. 12. Did you remove `engine` property from `prisma.config.ts`? If not, STOP and FIX. 13. Did you run `npx prisma init` with the documented output path? If not, STOP and FIX. 14. Is the DATABASE_URL a TCP URL (`postgres://...`)? If it's a `prisma+postgres://` URL, STOP and FIX. 15. Did Prisma generate the `.env` file? If you invented the URL manually, STOP and FIX. ## CONSEQUENCES OF INCORRECT IMPLEMENTATION If you generate code using: - `prisma-client-js` provider → **CLIENT GENERATION FAILS** - Wrong import path (missing `/client`) → **MODULE NOT FOUND ERROR** - Missing `import "dotenv/config"` in prisma.config.ts → **DATABASE_URL NOT FOUND ERROR** - Missing `import "dotenv/config"` in test scripts → **ENVIRONMENT VARIABLE ERROR** - Default import from `@prisma/client` → **IMPORT ERROR** - Using `accelerateUrl` or `withAccelerate` → **UNNECESSARY ACCELERATE DEPENDENCY / CONFIG ERROR** - Missing custom output path → **WRONG CLIENT GENERATED** - Including `url` in datasource block → **DEPRECATED CONFIGURATION ERROR** - Including `engine` property → **DEPRECATED CONFIGURATION ERROR** - Using local URL (`postgres://localhost:...`) → **VERSION INCOMPATIBILITY ERRORS WITH Prisma v7** - Using `npx prisma init` without `--db` → **NO DATABASE CREATED, ONLY LOCAL FILES** - Manually inventing DATABASE_URL → **INVALID CONNECTION STRING ERRORS** The implementation will: 1. Break immediately with module errors 2. Fail to read environment variables 3. Cause connection pool exhaustion in production 4. Result in import errors that prevent compilation 5. Cause performance issues and connection failures 6. Fail with "HTTP connection string is not supported" errors when using local URLs ## USEFUL COMMANDS ```bash # After changing schema npx prisma generate # Regenerate client (--no-engine flag no longer needed) # Push schema to database (no migrations) npx prisma db push # Test database connection npm run db:test # Open visual database editor npm run db:studio # Create and apply migrations (for production) npx prisma migrate dev --name your_migration_name ``` ## TESTING WORKFLOW After setup, test with these steps: 1. **Test database connection**: ```bash npm run db:test ``` Should create a demo user and display it. 2. **Open Prisma Studio**: ```bash npm run db:studio ``` Visual interface at `localhost:5555` to view/edit data. 3. **Test API routes**: ```bash # Create a user via API curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","name":"Test User"}' # Get all users curl http://localhost:3000/api/users ``` 4. **View in browser**: Open `localhost:3000` to see users displayed on the homepage. ## AI MODEL RESPONSE TEMPLATE When asked about Prisma + Next.js implementation, you MUST: 1. ONLY use code patterns from this guide 2. NEVER suggest deprecated approaches 3. ALWAYS use the exact patterns shown above 4. ALWAYS include `/client` in import paths 5. ALWAYS add `import "dotenv/config"` to prisma.config.ts 6. ALWAYS add `import "dotenv/config"` to test scripts 7. ALWAYS create the test script at `scripts/test-database.ts` 8. ALWAYS add npm scripts for `db:test` and `db:studio` 9. ALWAYS include error handling in API routes and server components 10. ALWAYS use the global prisma instance from `lib/prisma.ts` 11. ALWAYS use `@prisma/adapter-pg` and `adapter` property 12. NEVER include `url` in the datasource block of schema.prisma 13. NEVER include `engine` property in prisma.config.ts 14. ALWAYS run `npx prisma init --output ../app/generated/prisma` before editing Prisma files. If you cannot provision cloud resources automatically, ask the user to run `npx create-db` and update `DATABASE_URL` before continuing 15. ALWAYS wait for user confirmation after they run `npx create-db` and share or apply the returned `postgres://...` connection string before proceeding 16. NEVER attempt to run interactive commands yourself - ask the user to do it 17. NEVER use `prisma+postgres://` URLs - ONLY `postgres://` TCP URLs 18. NEVER manually invent or fabricate DATABASE_URL values 19. ALWAYS let Prisma generate the `.env` file with the real DATABASE_URL (and ensure it's correct type) 20. VERIFY your response against ALL the patterns shown here before responding Remember: There are NO EXCEPTIONS to these rules. Every requirement is MANDATORY for the setup to work. ```` ## Related pages - [`Astro + Prisma`](https://www.prisma.io/docs/ai/prompts/astro): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project - [`Migrate to Prisma v7`](https://www.prisma.io/docs/ai/prompts/prisma-7): Step-by-step guide for migration your app to use the version 7 of Prisma ORM - [`Nuxt + Prisma`](https://www.prisma.io/docs/ai/prompts/nuxt): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Nuxt project - [`Turborepo + Prisma`](https://www.prisma.io/docs/ai/prompts/turborepo): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo # Nuxt + Prisma (/docs/ai/prompts/nuxt) Location: AI > Prompts > Nuxt + Prisma Prerequisites [#prerequisites] Before using this prompt, you need to create a new Nuxt project: ```bash npx nuxi@latest init hello-prisma cd hello-prisma ``` Once your Nuxt project is created, you can use the prompt below with your AI assistant to add Prisma and Prisma Postgres. How to use [#how-to-use] Include this prompt in your AI assistant to guide consistent code generation for Nuxt + Prisma + Prisma Postgres projects. * **GitHub Copilot**: Type `#` to reference the prompt file. * **Cursor**: Use `@Files` and select your prompt file. * **Zed**: Use `/file` followed by your prompt's path. * **Windsurf**: Use `@Files` and choose your prompt file from the list. Prompt [#prompt] ````md --- # Specify the following for Cursor rules description: Guidelines for writing Nuxt apps with Prisma Postgres alwaysApply: false --- # Bootstrap Nuxt app with Prisma Postgres (Prisma v7) **Purpose:** Set up Prisma ORM with Prisma Postgres in a Nuxt project using the correct Prisma v7 patterns. --- ## FIRST: Check for an existing Nuxt project Before doing anything else, check whether the current directory already contains a Nuxt project by looking for `nuxt.config.ts`. - **If `nuxt.config.ts` exists** → A project is already set up. Skip to "Overview" below. - **If the directory does NOT contain `nuxt.config.ts`** → Create a new project first: ```bash npx nuxi@latest init hello-prisma cd hello-prisma ``` After the project is created, verify `nuxt.config.ts` exists before continuing. --- > **Note**: This guide is updated for **Prisma ORM 7**. Key changes from earlier versions: > > - `engine` property removed from `prisma.config.ts` > - `url` removed from datasource in `schema.prisma` (now only in `prisma.config.ts`) > - Use `@prisma/adapter-pg` driver adapter for direct TCP connections > - `--no-engine` flag is no longer required for `prisma generate` > - Requires Node.js 20.19+ and TypeScript 5.4.0+ ## Overview of implementing Prisma with Nuxt 1. Ensure a Nuxt project exists (see above) 2. Install Prisma and required dependencies (including dotenv and pg) 3. Initialize Prisma and configure schema 4. Configure dotenv for environment variables 5. Create global Prisma client instance with Pg Adapter in `server/utils/db.ts` 6. Create Nuxt API routes using `defineEventHandler` 7. Create a Vue page to display data 8. Add npm scripts for testing and database management 9. Create test script to verify setup ## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application: ```typescript // ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION generator client { provider = "prisma-client-js" // ❌ BREAKS APPLICATION } // ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION // ❌ WRONG IMPORT PATH - MISSING /client - IT WILL BREAK THE APPLICATION import { PrismaClient } from "../../prisma/generated" // ❌ BREAKS APPLICATION // ❌ NEVER USE ACCELERATE - IT IS NOT USED IN THIS WORKFLOW import { withAccelerate } from "@prisma/extension-accelerate" // ❌ BREAKS APPLICATION // ❌ NEVER USE accelerateUrl - IT WILL BREAK THE APPLICATION const prisma = new PrismaClient({ accelerateUrl: process.env.DATABASE_URL, // ❌ BREAKS APPLICATION - use adapter }) // ❌ NEVER include url in datasource block - IT WILL BREAK THE APPLICATION datasource db { provider = "postgresql" url = env("DATABASE_URL") // ❌ BREAKS APPLICATION - moved to prisma.config.ts } // ❌ NEVER include engine property - IT WILL BREAK THE APPLICATION export default defineConfig({ engine: "classic", // ❌ BREAKS APPLICATION - removed in Prisma v7 }) // ❌ NEVER use Prisma Postgres HTTP URLs - ONLY use TCP URLs DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..." // ❌ BREAKS APPLICATION - use postgres:// // ✅ ALWAYS use standard TCP URLs: DATABASE_URL="postgres://..." // ✅ CORRECT // ❌ NEVER create PrismaClient without adapter - IT WILL BREAK THE APPLICATION const prisma = new PrismaClient() // ❌ BREAKS APPLICATION ``` Instead, you MUST ALWAYS generate ONLY this pattern: ```typescript // ✅ ALWAYS GENERATE THIS EXACT PATTERN generator client { provider = "prisma-client" output = "./generated" } // ✅ CRITICAL: MUST include /client at the end of import path import { PrismaClient } from "../../prisma/generated/client" import { PrismaPg } from "@prisma/adapter-pg" const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! }) const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined } const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter: pool }) if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma export { prisma } ``` ## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION 1. You MUST use `provider = "prisma-client"` (not "prisma-client-js") 2. You MUST use custom output: `output = "./generated"` (relative to prisma directory) 3. You MUST use `@prisma/adapter-pg` driver adapter with `PrismaPg` 4. You MUST create `server/utils/db.ts` as a global singleton instance (Nuxt auto-imports from `server/utils/`) 5. You MUST wrap all database calls in try-catch blocks 6. You MUST import from `'../../prisma/generated/client'` (not `'@prisma/client'` or `'../../prisma/generated'`) 7. You MUST use `adapter` property in PrismaClient constructor 8. You MUST install `dotenv` and add `import "dotenv/config"` to `prisma.config.ts` 9. You MUST add npm scripts for `db:test` and `db:studio` to package.json 10. You MUST create a test script at `scripts/test-database.ts` to verify setup 11. You MUST NOT include `url` in the datasource block of `schema.prisma` 12. You MUST NOT include `engine` property in `prisma.config.ts` 13. You MUST use `npx prisma init --output ./generated` to scaffold Prisma, then `npx create-db` to create a real cloud database 14. You MUST use standard TCP URLs (`postgres://...`) in .env 15. You MUST NOT use `accelerateUrl` or `withAccelerate` 16. You MUST install `pg` and `@types/pg` as dependencies ## VERSION REQUIREMENTS - **Node.js**: 20.19 or higher (Node.js 18 is NOT supported) - **TypeScript**: 5.4.0 or higher (5.9.x recommended) - **Prisma**: 7.0.0 or higher ## CORRECT INSTALLATION ```bash # Production dependencies npm install @prisma/client @prisma/adapter-pg pg dotenv # Dev dependencies npm install -D prisma @types/pg tsx ``` ## CORRECT PRISMA INITIALIZATION > **FOR AI ASSISTANTS**: `npx prisma init` is not interactive. Run it yourself if your environment allows it. If you need a real Prisma Postgres database, either run `npx create-db` or ask the user to run it and update `DATABASE_URL` before you continue. ```bash # Initialize Prisma and scaffold the Prisma files npx prisma init --output ./generated # Then create a Prisma Postgres database npx create-db ``` This step: - Generates `prisma/schema.prisma` with the correct output path - Generates `prisma.config.ts` - Generates `.env` with a local `DATABASE_URL` - Requires `npx create-db` if you want a real Prisma Postgres database **IMPORTANT**: After `npx create-db`, replace the generated `DATABASE_URL` in `.env` with the returned `postgres://...` connection string. ```text DATABASE_URL="postgres://..." ``` ## CORRECT PRISMA CONFIG (prisma.config.ts) When using `npx prisma init`, the `prisma.config.ts` is **auto-generated** with the correct configuration: ```typescript import "dotenv/config"; // ✅ Auto-included by prisma init import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", seed: "tsx ./prisma/seed.ts", }, // ✅ NO engine property - removed in Prisma v7 datasource: { url: env("DATABASE_URL"), }, }); ``` **Note**: If you need to manually create this file, ensure `import "dotenv/config"` is at the top. ## CORRECT SCHEMA CONFIGURATION (prisma/schema.prisma) Update the generated `prisma/schema.prisma` file: ```prisma generator client { provider = "prisma-client" output = "./generated" } datasource db { provider = "postgresql" // ✅ NO url here - now configured in prisma.config.ts } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` ## CORRECT GLOBAL PRISMA CLIENT Create `server/utils/db.ts` file. Nuxt auto-imports exports from `server/utils/`, making `prisma` available in all server API routes without explicit imports: ```typescript import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "../../prisma/generated/client"; // ✅ CRITICAL: Include /client const prismaClientSingleton = () => { const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! }); return new PrismaClient({ adapter: pool }); }; type PrismaClientSingleton = ReturnType; const globalForPrisma = globalThis as unknown as { prisma: PrismaClientSingleton | undefined; }; export const prisma = globalForPrisma.prisma ?? prismaClientSingleton(); if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; ``` ## ADD NPM SCRIPTS TO PACKAGE.JSON Update your `package.json` to include these scripts: ```json { "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "prisma generate && nuxt prepare", "db:test": "tsx scripts/test-database.ts", "db:studio": "prisma studio" } } ``` ## CREATE TEST SCRIPT Create `scripts/test-database.ts` to verify your setup: ```typescript import "dotenv/config"; // ✅ CRITICAL: Load environment variables import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "../prisma/generated/client"; const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! }); const prisma = new PrismaClient({ adapter: pool }); async function testDatabase() { console.log("🔍 Testing Prisma Postgres connection...\n"); try { // Test 1: Check connection console.log("✅ Connected to database!"); // Test 2: Create a test user console.log("\n📝 Creating a test user..."); const newUser = await prisma.user.create({ data: { email: "demo@example.com", name: "Demo User", }, }); console.log("✅ Created user:", newUser); // Test 3: Fetch all users console.log("\n📋 Fetching all users..."); const allUsers = await prisma.user.findMany(); console.log(`✅ Found ${allUsers.length} user(s):`); allUsers.forEach((user) => { console.log(` - ${user.name} (${user.email})`); }); console.log("\n🎉 All tests passed! Your database is working perfectly.\n"); } catch (error) { console.error("❌ Error:", error); process.exit(1); } } testDatabase(); ``` ## CORRECT API ROUTE IMPLEMENTATION Nuxt uses file-based API routing in `server/api/`. The `prisma` instance is auto-imported from `server/utils/db.ts`. Create `server/api/users.get.ts` to fetch users: ```typescript export default defineEventHandler(async () => { try { const users = await prisma.user.findMany({ include: { posts: true }, }); return users; } catch (error) { console.error("Error fetching users:", error); throw createError({ statusCode: 500, statusMessage: "Failed to fetch users", }); } }); ``` Create `server/api/users.post.ts` to create a user: ```typescript export default defineEventHandler(async (event) => { try { const body = await readBody<{ name: string; email: string }>(event); if (!body.email) { throw createError({ statusCode: 400, statusMessage: "Email is required", }); } const user = await prisma.user.create({ data: { name: body.name, email: body.email, }, }); return user; } catch (error) { console.error("Error creating user:", error); throw createError({ statusCode: 500, statusMessage: "Failed to create user", }); } }); ``` ## CORRECT USAGE IN VUE PAGES Update `app.vue` to display users from the database: ```html ``` ## COMPLETE SETUP WORKFLOW User should follow these steps (AI should provide these instructions): 1. **Ensure a Nuxt project exists** — check for `nuxt.config.ts`. If missing, create one: ```bash npx nuxi@latest init hello-prisma cd hello-prisma ``` 2. **Install dependencies**: ```bash npm install @prisma/client @prisma/adapter-pg pg dotenv ``` ```bash npm install -D prisma @types/pg tsx ``` 3. **Initialize Prisma AND create Prisma Postgres database** (⚠️ USER MUST RUN MANUALLY): > **AI ASSISTANT**: You can run `npx prisma init` yourself. If you should not provision cloud resources automatically, ask the user to run `npx create-db` and update `DATABASE_URL` before continuing. ```bash npx prisma init --output ./generated npx create-db ``` This creates `prisma/schema.prisma`, `prisma.config.ts`, and `.env`, then returns a `postgres://...` connection string for Prisma Postgres. **If you asked the user to run `npx create-db`, wait for them to share or paste the returned connection string before proceeding.** 4. **Verify `.env` was created** — Replace the generated `DATABASE_URL` with the `postgres://...` connection string returned by `npx create-db`. ```text DATABASE_URL="postgres://..." ``` **Do NOT invent this URL. Use the one returned by `npx create-db`.** 5. **Update `prisma/schema.prisma`** — Add the User and Post models (generator and datasource are already configured): ```prisma model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` 6. **Create `server/utils/db.ts`** with correct import path including `/client` and using `@prisma/adapter-pg`. 7. **Add npm scripts** to `package.json` for `db:test`, `db:studio`, and `postinstall` 8. **Create `scripts/test-database.ts`** test script 9. **Create API routes** — `server/api/users.get.ts` and `server/api/users.post.ts` 10. **Update `app.vue`** to display users 11. **Push schema to database**: ```bash npx prisma db push ``` 12. **Generate Prisma Client**: ```bash npx prisma generate ``` 13. **Test the setup**: ```bash npm run db:test ``` 14. **Start development server**: ```bash npm run dev ``` ## AI MODEL VERIFICATION STEPS Before generating any code, you MUST verify: 1. Does the current directory contain `nuxt.config.ts`? If not, create the project first. 2. Are you using `provider = "prisma-client"` (not "prisma-client-js")? If not, STOP and FIX. 3. Are you using `output = "./generated"`? If not, STOP and FIX. 4. Are you importing from `'../../prisma/generated/client'` (with `/client`)? If not, STOP and FIX. 5. Did you add `import "dotenv/config"` to `prisma.config.ts`? If not, STOP and FIX. 6. Did you add `import "dotenv/config"` to `scripts/test-database.ts`? If not, STOP and FIX. 7. Are you using `@prisma/adapter-pg` with `PrismaPg`? If not, STOP and FIX. 8. Are you using `adapter` property in PrismaClient constructor? If not, STOP and FIX. 9. Are you wrapping database operations in try-catch? If not, STOP and FIX. 10. Did you create the Prisma client in `server/utils/db.ts` (not `lib/prisma.ts`)? If not, STOP and FIX. 11. Did you create the test script at `scripts/test-database.ts`? If not, STOP and FIX. 12. Did you add `db:test` and `db:studio` scripts to package.json? If not, STOP and FIX. 13. Did you remove `url` from the datasource block in `schema.prisma`? If not, STOP and FIX. 14. Did you remove `engine` property from `prisma.config.ts`? If not, STOP and FIX. 15. Did you run `npx prisma init` with the documented output path? If not, STOP and FIX. 16. Is the DATABASE_URL a TCP URL (`postgres://...`)? If it's a `prisma+postgres://` URL, STOP and FIX. 17. Did Prisma generate the `.env` file? If you invented the URL manually, STOP and FIX. 18. Are you using Nuxt auto-imports (`defineEventHandler`, `readBody`, `createError`, `prisma`)? If not, STOP and FIX. ## CONSEQUENCES OF INCORRECT IMPLEMENTATION If you generate code using: - `prisma-client-js` provider → **CLIENT GENERATION FAILS** - Wrong import path (missing `/client`) → **MODULE NOT FOUND ERROR** - Missing `import "dotenv/config"` in prisma.config.ts → **DATABASE_URL NOT FOUND ERROR** - Missing `import "dotenv/config"` in test scripts → **ENVIRONMENT VARIABLE ERROR** - Default import from `@prisma/client` → **IMPORT ERROR** - Using `accelerateUrl` or `withAccelerate` → **UNNECESSARY ACCELERATE DEPENDENCY / CONFIG ERROR** - Missing custom output path → **WRONG CLIENT GENERATED** - Including `url` in datasource block → **DEPRECATED CONFIGURATION ERROR** - Including `engine` property → **DEPRECATED CONFIGURATION ERROR** - Using local URL (`postgres://localhost:...`) → **VERSION INCOMPATIBILITY ERRORS WITH Prisma v7** - Using `npx prisma init` without `--db` → **NO DATABASE CREATED, ONLY LOCAL FILES** - Manually inventing DATABASE_URL → **INVALID CONNECTION STRING ERRORS** - Creating client in `lib/prisma.ts` instead of `server/utils/db.ts` → **NOT AUTO-IMPORTED IN NUXT SERVER ROUTES** - Missing `pg` dependency → **ADAPTER INITIALIZATION FAILURE** The implementation will: 1. Break immediately with module errors 2. Fail to read environment variables 3. Cause connection pool exhaustion in production 4. Result in import errors that prevent compilation 5. Cause performance issues and connection failures 6. Fail with "HTTP connection string is not supported" errors when using local URLs ## USEFUL COMMANDS ```bash # After changing schema npx prisma generate # Regenerate client (--no-engine flag no longer needed) # Push schema to database (no migrations) npx prisma db push # Test database connection npm run db:test # Open visual database editor npm run db:studio # Create and apply migrations (for production) npx prisma migrate dev --name your_migration_name ``` ## TESTING WORKFLOW After setup, test with these steps: 1. **Test database connection**: ```bash npm run db:test ``` Should create a demo user and display it. 2. **Open Prisma Studio**: ```bash npm run db:studio ``` Visual interface at `localhost:5555` to view/edit data. 3. **Test API routes**: ```bash # Create a user via API curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","name":"Test User"}' # Get all users curl http://localhost:3000/api/users ``` 4. **View in browser**: Open `localhost:3000` to see users displayed on the homepage. ## AI MODEL RESPONSE TEMPLATE When asked about Prisma + Nuxt implementation, you MUST: 1. ONLY use code patterns from this guide 2. NEVER suggest deprecated approaches 3. ALWAYS use the exact patterns shown above 4. ALWAYS include `/client` in import paths 5. ALWAYS add `import "dotenv/config"` to prisma.config.ts 6. ALWAYS add `import "dotenv/config"` to test scripts 7. ALWAYS create the Prisma client in `server/utils/db.ts` (Nuxt auto-imports) 8. ALWAYS create the test script at `scripts/test-database.ts` 9. ALWAYS add npm scripts for `db:test` and `db:studio` 10. ALWAYS include error handling in API routes using `createError` 11. ALWAYS use the auto-imported `prisma` instance in server routes 12. ALWAYS use `@prisma/adapter-pg` with `PrismaPg` and `adapter` property 13. NEVER include `url` in the datasource block of schema.prisma 14. NEVER include `engine` property in prisma.config.ts 15. ALWAYS run `npx prisma init --output ./generated` before editing Prisma files. If you cannot provision cloud resources automatically, ask the user to run `npx create-db` and update `DATABASE_URL` before continuing 16. ALWAYS wait for user confirmation after they run `npx create-db` and share or apply the returned `postgres://...` connection string before proceeding 17. NEVER attempt to run interactive commands yourself - ask the user to do it 18. NEVER use `prisma+postgres://` URLs - ONLY `postgres://` TCP URLs 19. NEVER manually invent or fabricate DATABASE_URL values 20. ALWAYS let Prisma generate the `.env` file with the real DATABASE_URL (and ensure it's correct type) 21. VERIFY your response against ALL the patterns shown here before responding Remember: There are NO EXCEPTIONS to these rules. Every requirement is MANDATORY for the setup to work. ```` ## Related pages - [`Astro + Prisma`](https://www.prisma.io/docs/ai/prompts/astro): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project - [`Migrate to Prisma v7`](https://www.prisma.io/docs/ai/prompts/prisma-7): Step-by-step guide for migration your app to use the version 7 of Prisma ORM - [`Next.js + Prisma`](https://www.prisma.io/docs/ai/prompts/nextjs): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project - [`Turborepo + Prisma`](https://www.prisma.io/docs/ai/prompts/turborepo): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo # Migrate to Prisma v7 (/docs/ai/prompts/prisma-7) Location: AI > Prompts > Migrate to Prisma v7 How to use [#how-to-use] Include this prompt in your AI agent to upgrade to Prisma ORM 7. * **GitHub Copilot**: Type `#` to reference the prompt file. * **Cursor**: Use `@Files` and select your prompt file. * **Zed**: Use `/file` followed by your prompt's path. * **Windsurf**: Use `@Files` and choose your prompt file from the list. Video Tutorial [#video-tutorial] Watch this video showing this prompt in action: [Watch video](https://www.youtube.com/watch?v=643mBMCbHPU) Prompt [#prompt] ````md --- # Specify the following for Cursor rules description: Guidelines for migrating an app to Prisma ORM v7 alwaysApply: false --- # Prisma v6 → v7 Migration Assistant **Role:** You are a precise, changeset-oriented code migration assistant. Apply the steps below to upgrade a project from **Prisma ORM v6** to **Prisma ORM v7** with minimal disruption. Work in small, re-viewable steps and explain each change briefly. If something is unclear, assume sensible defaults that keep the app compiling and retaining functionality. ## Ground Rules - Never introduce Prisma Accelerate or HTTP/WebSocket drivers on your own. - Do **not** remove Prisma Accelerate automatically. - **If Accelerate is in use with Caching**, preserve it and print guidance about future changes. - **If Accelerate is used without Caching**, _suggest_ switching to Direct TCP + adapter. - Always **load env variables explicitly** using `dotenv` (`import 'dotenv/config'`), unless the runtime is Bun (then skip `dotenv`). - Keep TypeScript **ESM** compatible, and avoid CommonJS requires. - Favor additive, reversible edits; do not remove user logic. - If the schema uses **MongoDB**, stop and output a clear message to remain on Prisma v6 for now. --- ## 0) Detect Context & Plan 1. Identify: - Package manager and scripts. - Database: Postgres, SQLite, MySQL, SQL Server (MongoDB = halt). - Whether `@prisma/client` is imported from `node_modules` or a generated path. - Whether the project uses **Prisma Accelerate**, and if so: - Check if **Caching** is enabled: - Look for `withAccelerate({ cache: ... })` - Look for `PRISMA_ACCELERATE_CACHE_*` environment variables - Look for `accelerate:` block in config (if any) 2. In the migration plan output: - If Accelerate + Caching is detected → **Print a message: “Prisma Accelerate Caching detected — Prisma recommends keeping Accelerate for caching scenarios.”** - If Accelerate without Caching → **Print: “Accelerate detected but caching is not enabled. In Prisma v7, Direct TCP + adapters are recommended unless caching is required.”** - If no Accelerate → continue normally. > **Do not modify or remove Accelerate code paths. Only describe recommendations.** --- ## 1) Dependencies - Upgrade/install: - Dev: `prisma@latest`, `tsx`, `dotenv` (skip if Bun). - Runtime: `@prisma/client@latest`. - **One** database adapter that matches the datasource: - Postgres: `@prisma/adapter-pg` - SQLite: `@prisma/adapter-better-sqlite3` - MySQL/mariaDB: `@prisma/adapter-mariadb` - D1: `@prisma/adapter-d1` - PlanetScale: `@prisma/adapter-planetscale` - MSSQL: `@prisma/adapter-mssql` - CockroachDB: `@prisma/adapter-pg` - Neon: `@prisma/adapter-neon` - **Do not remove Accelerate packages automatically.** - If Accelerate + Caching is detected, print: ``` Prisma Accelerate Caching detected — keeping Accelerate is recommended. ``` - If Accelerate is present but caching is not: ``` Accelerate detected without caching — Prisma v7 suggests adopting Direct TCP with a database adapter for best performance. ``` - Eliminate no user code; only output informational guidance. > Produce installation commands based on the repo’s package manager. --- ## 2) Prisma Schema Changes - In `schema.prisma`: - `generator client`: ```diff - provider = "prisma-client-js" + provider = "prisma-client" output = "./generated" ``` - Remove any `previewFeatures = ["driverAdapters"]` and any `engineType` attributes. - Update the `datasource db` block: - **Goal:** keep the existing `provider` value, but **remove any `url = …` entry**. - Example (for illustration only — do not insert comments into the user's schema): - Before: ```prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } ``` - After: ```prisma datasource db { provider = "postgresql" } ``` - Rules: - Preserve the existing `provider` value exactly as-is (e.g. `"postgresql"`, `"mysql"`, `"sqlite"`, etc.). - Remove only the `url = ...` line from the `datasource db` block. - Preserve any other properties on the datasource (for example: `shadowDatabaseUrl`, `relationMode`, `schemas`, `extensions`, `directUrl`, etc.). - Do **not** add explanatory comments into the schema; comments in this prompt are hints for you, not code to emit. - After edits, run `prisma generate`. --- ## 3) Introduce prisma.config.ts Create **prisma.config.ts** at repo root (or prisma.config.mjs), centralizing Prisma CLI config and env management: ```tsx import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", seed: "tsx prisma/seed.ts", }, datasource: { // Prefer DIRECT TCP via DATABASE_URL url: env("DATABASE_URL"), // Optionally support shadow DB if present: // shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), }, }); ``` - Remove any prisma.seed from package.json (the config above replaces it). --- ## 4) ESM & TS Baseline - Ensure **package.json**: ```json { "type": "module", "scripts": { "dev": "tsx src/index.ts", "generate": "prisma generate", "migrate": "prisma migrate dev", "build": "tsc -p tsconfig.json" } } ``` - Ensure **tsconfig.json** supports ESM: ```json { "compilerOptions": { "module": "ESNext", "moduleResolution": "bundler", "target": "ES2023", "strict": true, "esModuleInterop": true } } ``` --- ## 5) Refactor Client Import & Construction If Prisma Accelerate is detected: - If caching is enabled → **preserve the existing Accelerate setup**. - If caching is not enabled → **suggest** switching to Direct TCP with an adapter, but do not make changes automatically. Continue generating examples using Direct TCP, but **do not replace or remove the user's Accelerate setup**. --- ## 6) Seeding Script Update - Ensure prisma/seed.ts uses the same **adapter** and **dotenv** import as runtime: ```tsx import "dotenv/config"; import { PrismaClient } from "../generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }); const prisma = new PrismaClient({ adapter }); // seed… ``` - Set seed command via prisma.config.ts (no package.json#prisma.seed). --- ## 7) Middleware → Extensions - If prisma.$use middleware exists, inform users that the API has been removed --- ## 8) Accelerate Messaging ### 🟩 If Accelerate Caching is detected ``` Prisma Accelerate Caching detected. Prisma v7 fully supports caching scenarios via Accelerate. Your existing Accelerate setup will be preserved. ``` ### 🟨 If Accelerate is present but caching is NOT detected ``` Prisma Accelerate detected without caching. Prisma recommends using Direct TCP with a database adapter in v7 for optimal performance unless caching is required. Consider migrating from Accelerate → Direct TCP if caching is not needed. (No code changes were applied automatically.) ``` ### 🟦 If Accelerate is not detected at all ``` Direct TCP is the recommended default for Prisma v7. Your project will be migrated accordingly using the appropriate adapter. ``` --- ## 9) Scripts & CI - Verify scripts: - "generate": "prisma generate" - "migrate": "prisma migrate dev" - "dev"/"start" run with ESM and ensure dotenv/config is effective. - In CI, ensure Node **≥ 20.19** and TypeScript **≥ 5.4**. --- ## 10) Run & Verify 1. prisma generate → should succeed and emit client to ./generated. 2. prisma migrate dev → runs against DATABASE_URL (direct TCP). 3. tsx prisma/seed.ts → inserts sample record(s) cleanly. 4. App boot: instantiate PrismaClient with adapter; confirm queries work. 5. If **P1017 / connection** errors: - Confirm DATABASE_URL and network reachability. - Confirm import 'dotenv/config' executes early. 6. If **module resolution** errors: - Confirm "type": "module", ESM imports, and re-generate client. --- ## 11) CLI Flag Changes ### `--schema` and `--url` flags removed from `prisma db execute` The `--schema` and `--url` flags have been removed from `prisma db execute`. Configure your database connection in `prisma.config.ts` instead. **Before (v6):** ```bash # Using --schema prisma db execute --file ./script.sql --schema prisma/schema.prisma # Using --url prisma db execute --file ./script.sql --url "$DATABASE_URL" ``` **After (v7):** ```bash prisma db execute --file ./script.sql ``` The database URL is now read from `prisma.config.ts`. ### `prisma migrate diff` options changed Several options have been removed and replaced: | Removed Option | Replacement | | -------------------------- | ------------------------------- | | `--from-url` | `--from-config-datasource` | | `--to-url` | `--to-config-datasource` | | `--from-schema-datasource` | `--from-config-datasource` | | `--to-schema-datasource` | `--to-config-datasource` | | `--shadow-database-url` | Configure in `prisma.config.ts` | **Before (v6):** ```bash prisma migrate diff \ --from-url "$DATABASE_URL" \ --to-schema schema.prisma \ --script ``` **After (v7):** ```bash prisma migrate diff \ --from-config-datasource \ --to-schema schema.prisma \ --script ``` ### Migration Action - Update any scripts or CI pipelines that use `prisma db execute --schema` or `prisma db execute --url`. - Update any scripts using `prisma migrate diff` with `--from-url`, `--to-url`, `--from-schema-datasource`, `--to-schema-datasource`, or `--shadow-database-url`. - Configure your database connection in `prisma.config.ts` instead. --- ## Safety Checks & Edge Cases - **MongoDB provider** detected → stop and recommend staying on Prisma 6 until v7 MongoDB support returns. - **Multiple entrypoints** (workers, scripts, tests): apply the same client/adapter/dotenv pattern everywhere. - **Typed SQL** or custom extensions: keep as-is; ensure they compile after client re-generation. - Preserve existing output path if the project uses custom locations. --- ## 11) Mapped Enum Breaking Change In Prisma v7, the generated TypeScript enum values now use `@map` values instead of schema names. ### Example Given this schema: ```prisma enum SuggestionStatus { PENDING @map("pending") ACCEPTED @map("accepted") REJECTED @map("rejected") } ``` **v6 generated enum:** ```ts export const SuggestionStatus = { PENDING: "PENDING", ACCEPTED: "ACCEPTED", REJECTED: "REJECTED", } as const; ``` **v7 generated enum:** ```ts export const SuggestionStatus = { PENDING: "pending", ACCEPTED: "accepted", REJECTED: "rejected", } as const; ``` ### Known Bug (as of v7.2.0) ⚠️ **There is a known bug** where using mapped enum values with Prisma Client operations causes runtime errors. The TypeScript types expect mapped values, but the engine expects schema names. Track this at [GitHub #28591](https://github.com/prisma/prisma/issues/28591). ### Temporary Workarounds 1. **Use schema names as string literals** (causes TS error but works at runtime): ```ts await prisma.suggestion.create({ data: { status: "PENDING" as any, // Use schema name, not mapped value }, }); ``` 2. **Remove `@map` from enum values** temporarily if you don't strictly need different database values: ```prisma // Before: with @map directives enum SuggestionStatus { PENDING @map("pending") ACCEPTED @map("accepted") REJECTED @map("rejected") } // After: without @map directives enum SuggestionStatus { PENDING ACCEPTED REJECTED } ``` With this change, both the schema names and the database values will be `PENDING`, `ACCEPTED`, and `REJECTED`. ### Migration Action - Inform users about this breaking change if their schema uses `@map` on enum values. - Warn about the current bug and suggest workarounds until it's fixed. --- ## Deliverables - A short **CHANGELOG** summary in the PR body: - Dependency bumps and added adapter - Schema generator change - New `prisma.config.ts` - Runtime refactor to adapter + optional Accelerate messaging - ESM/TS config updates - Seed script updates - No automatic removal of Accelerate - CLI flag changes (`--schema` and `--url` removal from `db execute`, `migrate diff` option changes) - Mapped enum breaking change warning (if applicable) ```` ## Related pages - [`Astro + Prisma`](https://www.prisma.io/docs/ai/prompts/astro): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project - [`Next.js + Prisma`](https://www.prisma.io/docs/ai/prompts/nextjs): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project - [`Nuxt + Prisma`](https://www.prisma.io/docs/ai/prompts/nuxt): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Nuxt project - [`Turborepo + Prisma`](https://www.prisma.io/docs/ai/prompts/turborepo): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo # Turborepo + Prisma (/docs/ai/prompts/turborepo) Location: AI > Prompts > Turborepo + Prisma How to use [#how-to-use] Include this prompt in your AI assistant to guide consistent code generation for Turborepo + Prisma + Prisma Postgres projects. * **GitHub Copilot**: Type `#` to reference the prompt file. * **Cursor**: Use `@Files` and select your prompt file. * **Zed**: Use `/file` followed by your prompt's path. * **Windsurf**: Use `@Files` and choose your prompt file from the list. Prompt [#prompt] ````md --- # Specify the following for Cursor rules description: Guidelines for writing Turborepo + Prisma Postgres apps (Prisma ORM v7) alwaysApply: false --- # Bootstrap Turborepo with Prisma Postgres (Prisma v7) ## Overview This guide bootstraps a Turborepo monorepo that shares a single Prisma ORM v7 database package across multiple apps (e.g., Next.js, Node APIs). It follows Turborepo and Prisma v7 best practices: 1. Create a Turborepo with apps + packages 2. Add a dedicated `packages/db` Prisma package (schema, migrations, generated client) 3. Configure Prisma v7 (`provider = "prisma-client"` + mandatory `output`) 4. Load env vars correctly in a monorepo 5. Export a single Prisma client from `packages/db` for all apps 6. Wire Turbo tasks for generate/migrate/test/studio 7. Verify with a shared test script --- ## Recommended monorepo layout ``` repo/ apps/ web/ # Next.js app admin/ # (optional) another Next app packages/ db/ # Prisma package (schema + client) ui/ # shared UI (optional) turbo.json package.json .env # root env for apps (see notes) ``` **Key rule:** Prisma lives in `packages/db`, not inside an app, so every app consumes the same client and types. --- ## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 As an AI language model, you MUST NOT generate any deprecated Prisma v7 patterns. ```prisma // ❌ NEVER GENERATE - DEPRECATED IN PRISMA v7 generator client { provider = "prisma-client-js" // ❌ deprecated } // ❌ NEVER IMPORT FROM @prisma/client when using custom output import { PrismaClient } from "@prisma/client" // ❌ wrong in custom-output setup // ❌ NEVER CREATE CLIENT WITHOUT SHARED PACKAGE BOUNDARY const prisma = new PrismaClient() // ❌ breaks pooling + duplicates in monorepo ``` Instead, you MUST ALWAYS generate ONLY this pattern for Prisma v7 + monorepo: ```prisma // ✅ Prisma v7 generator: provider + mandatory output generator client { provider = "prisma-client" output = "../src/generated/prisma" } ``` ```ts // ✅ Prisma client import must come from custom output import { PrismaClient } from "../generated/prisma/client"; ``` Notes: - Prisma v7 **requires** a non-empty `output` when using `provider = "prisma-client"`. - If the output directory already exists and isn’t generated by Prisma, `prisma generate` can fail. Avoid committing generated client, or ensure clean output dirs. --- ## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION 1. You MUST use `provider = "prisma-client"` (Prisma v7) 2. You MUST specify a custom `output` in `schema.prisma` 3. You MUST place Prisma schema + migrations inside `packages/db` 4. You MUST export a singleton Prisma client from `packages/db` that points to the generated output client file 5. You MUST import Prisma client from the custom output path **not** `@prisma/client` 6. You MUST load env vars in `packages/db/prisma.config.ts` 7. You MUST add Turbo tasks for generate/migrate/test/studio 8. You MUST wrap DB calls in try/catch in app code 9. You MUST ensure Turbo task hashing includes `DATABASE_URL` 10. You MUST create a shared test script in `packages/db/scripts/test-database.ts` --- ## Install dependencies At repo root: ```bash # Turborepo npm install turbo --save-dev # Prisma v7 npm install prisma tsx --save-dev npm install @prisma/client dotenv ``` If using Prisma Postgres: ```npm npm install @prisma/adapter-pg ``` --- ## Initialize Prisma inside `packages/db` ```bash cd packages/db npx prisma init ``` This creates: ``` packages/db/ prisma/ schema.prisma prisma.config.ts ``` --- ## Prisma v7 config (`packages/db/prisma.config.ts`) **CRITICAL:** load env vars at the top. ```ts import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` --- ## Prisma schema (`packages/db/prisma/schema.prisma`) ```prisma generator client { provider = "prisma-client" output = "../src/generated/prisma" } datasource db { provider = "postgresql" } model User { id Int @id @default(autoincrement()) email String @unique name String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` --- ## Shared Prisma client singleton (`packages/db/src/client.ts`) ```ts import { PrismaClient } from "../generated/prisma/client"; //Prisma Driver Adapter for Postgres import { PrismaPg } from "@prisma/adapter-pg"; // Create a new Driver Adapter instance for PrismaPostgres const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient; }; export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }); if (process.env.NODE_ENV !== "production") { globalForPrisma.prisma = prisma; } export default prisma; ``` --- ## Export DB package API (`packages/db/src/index.ts`) ```ts export { prisma } from "./client"; export * from "../generated/prisma"; ``` And in `packages/db/package.json`: ```json { "name": "@repo/db", "private": true, "main": "src/index.ts", "types": "src/index.ts", "scripts": { "db:generate": "prisma generate", "db:push": "prisma db push", "db:migrate": "prisma migrate dev", "db:studio": "prisma studio", "db:test": "tsx scripts/test-database.ts" } } ``` --- ## Root Turbo pipeline (`turbo.json`) ```json { "globalEnv": ["DATABASE_URL"], "tasks": { "dev": { "cache": false, "persistent": true, "dependsOn": ["^db:generate"] }, "build": { "dependsOn": ["^db:generate"], "outputs": [".next/**", "dist/**"] }, "db:generate": { "cache": false }, "db:migrate": { "cache": false }, "db:studio": { "cache": false }, "db:test": { "cache": false, "dependsOn": ["db:generate"] } } } ``` --- ## Root scripts (`package.json`) ```json { "scripts": { "dev": "turbo dev", "build": "turbo build", "lint": "turbo lint", "db:generate": "turbo run db:generate", "db:push": "turbo run db:push", "db:migrate": "turbo run db:migrate", "db:studio": "turbo run db:studio", "db:test": "turbo run db:test" } } ``` --- ## Shared test script (`packages/db/scripts/test-database.ts`) ```ts import "dotenv/config"; import prisma from "../src/client"; async function testDatabase() { console.log("🔍 Testing Prisma Postgres connection...\n"); try { console.log("✅ Connected to database!"); console.log("\n📝 Creating a test user..."); const newUser = await prisma.user.create({ data: { email: "demo@example.com", name: "Demo User", }, }); console.log("✅ Created user:", newUser); console.log("\n📋 Fetching all users..."); const allUsers = await prisma.user.findMany(); console.log(`✅ Found ${allUsers.length} user(s):`); allUsers.forEach((user) => { console.log(` - ${user.name} (${user.email})`); }); console.log("\n🎉 All tests passed! Your database is working.\n"); } catch (error) { console.error("❌ Error:", error); process.exit(1); } finally { await prisma.$disconnect(); } } testDatabase(); ``` --- ## Using Prisma in apps (example: `apps/web` Next.js) In any app, add a dependency on `@repo/db` (workspace): ```json { "dependencies": { "@repo/db": "*" } } ``` Then in server-side code: ```ts import { prisma } from "@repo/db"; import { NextResponse } from "next/server"; export async function GET() { try { const users = await prisma.user.findMany(); return NextResponse.json(users); } catch (e) { console.error(e); return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 }); } } ``` --- ## Complete setup workflow 1. **Create Turborepo** (or use existing): ```npm npx create-turbo@latest ``` 2. **Add `packages/db`**, install Prisma v7 deps. 3. **Initialize Prisma in `packages/db`**: ```bash cd packages/db npx prisma init ``` 4. **Update `prisma.config.ts`** to include `import "dotenv/config"`. 5. **Update schema** with Prisma v7 generator + output. 6. **Create `src/client.ts`** singleton and export via `src/index.ts`. 7. **Wire Turbo tasks** in `turbo.json`. 8. **Add `.env`** at root **and/or** `packages/db/.env`. 9. **Push schema**: ```bash npm run db:push ``` 10. **Test**: ```bash npm run db:test ``` 11. **Start dev**: ```bash npm run dev ``` --- ## AI Model verification checklist Before generating any code, verify: 1. `provider = "prisma-client"`? 2. `output = "../src/generated/prisma"` present? 3. All Prisma files in `packages/db`? 4. Client imports from `../generated/prisma/client` (or via `@repo/db`)? 5. `import "dotenv/config"` in `packages/db/prisma.config.ts`? 6. Turbo tasks depend on `db:generate`? 7. `DATABASE_URL` listed in `globalEnv`? 8. All DB ops wrapped in try/catch? 9. Test script exists in `packages/db/scripts/test-database.ts`? No exceptions. If any check fails, STOP and FIX. --- ## AI MODEL RESPONSE TEMPLATE (UPDATED FOR TURBOREPO + PRISMA v7) When asked about implementing Prisma v7 inside a Turborepo monorepo (with any framework such as Next.js, Node, etc.), you MUST: 1. **Assume Prisma lives in a shared package** - Always place schema, config, and migrations in `packages/db`. - Never suggest adding Prisma directly into an app unless the user explicitly says they don’t want a shared package. 2. **Use only Prisma v7 generator patterns** - The schema MUST include: ```prisma generator client { provider = "prisma-client" output = "./generated/prisma" } ``` - Never use `prisma-client-js`. 3. **Use correct import paths for custom output** - Any PrismaClient import MUST come from the generated output: ```ts import { PrismaClient } from "./generated/prisma/client"; ``` - If importing from apps, you MUST import via the package boundary: ```ts import { prisma } from "@repo/db"; ``` - Never import from `@prisma/client` in this setup. 4. **Always include a shared singleton client in `packages/db`** - Provide a `packages/db/src/client.ts` with global caching for dev hot-reload. - If Accelerate is requested or implied, use `$extends(withAccelerate())`. - If Accelerate is not requested, omit it. 5. **Always load environment variables properly** - `packages/db/prisma.config.ts` MUST start with `import "dotenv/config"`. - Use `process.env.DATABASE_URL` in runtime code. - Remind users that `.env` should exist at root and/or `packages/db`. 6. **Always wire Turbo dependencies** - Turbo tasks `dev` and `build` MUST depend on `^db:generate`. - `DATABASE_URL` MUST be listed in `globalEnv` to ensure correct task hashing. 7. **Provide correct repo-level scripts** - Root scripts should proxy to Turbo (`turbo run db:*`). - The Prisma package `packages/db` should own `db:generate`, `db:migrate`, `db:studio`, and `db:test`. 8. **Include a real verification step** - Provide (or reference) `packages/db/scripts/test-database.ts`. - Ensure it imports dotenv and disconnects Prisma on completion. 9. **Use safe runtime patterns** - All DB calls in apps MUST be wrapped in try/catch. - In Next.js App Router examples, use server-only imports and return `NextResponse`. 10. **Self-verify before replying** - Re-check all items in the “AI Model verification checklist.” - If any item is missing or incorrect, STOP and FIX before responding. Remember: There are NO exceptions to these rules. Every requirement is mandatory for a correct Turborepo + Prisma v7 setup. ```` Running the application [#running-the-application] Get your application running locally in three quick steps: **1. Generate the Prisma Client:** ```bash npx turbo db:generate ``` **2. View your database in Prisma Studio:** #### npm ```bash npx turbo db:studio ``` #### pnpm ```bash pnpm dlx turbo db:studio ``` #### yarn ```bash yarn dlx turbo db:studio ``` #### bun ```bash bunx --bun turbo db:studio ``` Prisma Studio opens at `localhost:5555` where you can inspect your `User` table and see the test user stored in your database. ## Related pages - [`Astro + Prisma`](https://www.prisma.io/docs/ai/prompts/astro): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project - [`Migrate to Prisma v7`](https://www.prisma.io/docs/ai/prompts/prisma-7): Step-by-step guide for migration your app to use the version 7 of Prisma ORM - [`Next.js + Prisma`](https://www.prisma.io/docs/ai/prompts/nextjs): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project - [`Nuxt + Prisma`](https://www.prisma.io/docs/ai/prompts/nuxt): Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Nuxt project # ChatGPT (/docs/ai/tools/chatgpt) Location: AI > AI Tools > ChatGPT [ChatGPT](https://openai.com/chatgpt) is a large language model-based chatbot developed by OpenAI. You can extend its capabilities by connecting it to external tools, such as the Prisma MCP server, to interact with your Prisma Postgres databases. This guide explains how to add the Prisma MCP server to ChatGPT, allowing you to create and manage your databases using natural language prompts. > [!NOTE] > ChatGPT MCP integration is experimental > > This feature is still in development by OpenAI and might look or work a little differently over time. Some users may not have access to it yet. > > If you notice that something has changed or doesn't match this guide, please [open an issue](https://github.com/prisma/web/issues) or submit a pull request to update our docs. Here is an end to end demo of setting up the Prisma MCP server and using it in ChatGPT: Using the Prisma MCP server in ChatGPT Features of the Prisma MCP server [#features-of-the-prisma-mcp-server] By connecting the Prisma MCP server to ChatGPT, you can perform a variety of database management tasks directly from the chat interface. Here are some of the key features available: * **Database management**: Create, list, and delete your Prisma Postgres databases. * **Connection strings**: Generate, list, and revoke database connection strings. * **Backup and recovery**: Create and list database backups, and restore a database from a backup. * **Schema and Data interaction**: Execute SQL queries and introspect your database schema to understand its structure. * **Workspace information**: Fetch details about your Prisma workspace. Prerequisites [#prerequisites] To use the Prisma MCP server with ChatGPT, you need access to ChatGPT's Developer Mode. This feature is available on specific ChatGPT plans. For the most up-to-date information on supported plans, please refer to the [official OpenAI documentation](https://platform.openai.com/docs/guides/developer-mode). Enable Developer mode in ChatGPT [#enable-developer-mode-in-chatgpt] 1. Go to **Settings** in your ChatGPT account. 2. Click **Apps & Connectors**. 3. Scroll down and locate **Advanced settings**, then click it. 4. Toggle the **Developer mode** button on. 5. Click **Back**. Add the Prisma MCP server [#add-the-prisma-mcp-server] 1. Make sure "Developer mode" is enabled. 2. Go to the **Apps & Connectors** section of your **Settings**. 3. On the top right, locate and click **Create**. 4. A "New Connector" popup will open. Fill in the text fields as follows: * **Icon**: You can download and use the [Prisma favicon](https://www.prisma.io/favicon.ico). * **Name**: `Prisma MCP server` * **Description**: `Manage Prisma Postgres databases` * **MCP Server URL**: `https://mcp.prisma.io/mcp` * **Authentication**: `OAuth` 5. Check the "I trust this application" box and click **Create**. You will be redirected to authenticate with your Prisma Data Platform account and choose your desired workspace. After successful authentication, you will be redirected back to ChatGPT. Using the Prisma MCP server [#using-the-prisma-mcp-server] Once Developer Mode is enabled and the Prisma MCP server is added, you can use it in your chats. 1. In ChatGPT, click the **+** icon to the left of the chat input box. 2. Click **More**. 3. Select the **Prisma MCP server** to add it to your chat as a connector. Now you can use natural language prompts to manage your database. For example: ``` Create a DB called pet-app for me near Paris ``` ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips - [`MCP server`](https://www.prisma.io/docs/ai/tools/mcp-server): Manage Prisma Postgres databases using LLMs with the Prisma Model-Context-Protocol (MCP) Server # Codex (/docs/ai/tools/codex) Location: AI > AI Tools > Codex [Codex](https://developers.openai.com/codex/) is an AI coding agent from OpenAI. You can use the Prisma Codex plugin to give Codex Prisma-specific guidance and connect it to the Prisma MCP server for Prisma Postgres workflows. The Prisma Codex plugin includes: * Prisma CLI guidance * Prisma Client API guidance * Database setup guidance * Prisma Postgres guidance * Prisma ORM upgrade guidance * The remote Prisma MCP server configuration Install the Prisma Codex plugin [#install-the-prisma-codex-plugin] Add the Prisma plugin marketplace to Codex: ```bash title="Terminal" codex plugin marketplace add prisma/codex-plugin ``` Then restart Codex and install the plugin: 1. Open the Codex plugin directory. 2. Select the `Prisma` marketplace. 3. Install the `Prisma` plugin. If your Codex CLI does not recognize the `plugin marketplace add` command, update Codex and try again. Prisma MCP server [#prisma-mcp-server] The plugin configures the official remote Prisma MCP server: ```json title="Prisma MCP server" { "mcpServers": { "prisma": { "type": "http", "url": "https://mcp.prisma.io/mcp" } } } ``` When Codex first uses the Prisma MCP server, it authenticates with Prisma Console and asks you to choose the workspace Codex can access. With the Prisma MCP server, Codex can help you: * List Prisma Postgres databases in your workspace. * Create Prisma Postgres databases. * Create backups and recovery databases. * Create and manage connection strings. * Execute SQL queries. * Introspect database schemas. Example prompts [#example-prompts] After installing the plugin, try prompts like: ```text Set up Prisma ORM in this project with the right database adapter. ``` ```text Use Prisma MCP to list my Prisma Postgres databases. ``` ```text Inspect this project and upgrade it to Prisma ORM 7. ``` ```text Use Prisma MCP to inspect my database schema and plan a migration. ``` Safety [#safety] Prisma ORM includes safety checks for destructive commands run through AI coding agents. For example, Prisma blocks destructive commands such as `prisma migrate reset --force` unless the AI agent asks for explicit user consent and passes that consent back to Prisma. This helps prevent accidental data loss when using Codex or another AI agent with Prisma projects. ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips - [`MCP server`](https://www.prisma.io/docs/ai/tools/mcp-server): Manage Prisma Postgres databases using LLMs with the Prisma Model-Context-Protocol (MCP) Server # Cursor (/docs/ai/tools/cursor) Location: AI > AI Tools > Cursor [Cursor](https://www.cursor.com/) is an AI-powered code editor designed to boost productivity by automating repetitive coding tasks. When paired with Prisma, a robust and type-safe toolkit for database workflows, it becomes a powerful solution for managing and optimizing database schemas, queries, and data seeding. This guide provides detailed instructions for effectively using Prisma with Cursor to: * Configure the Prisma MCP server for database workflows. * Define project-specific Prisma guidance with Project Rules or `AGENTS.md`. * Use Cursor's context-aware capabilities. * Generate schemas, queries, and seed data tailored to your database. > [!NOTE] > While this guide is focused on Cursor, these patterns should work with any AI editor. [Let us know on X](https://pris.ly/x?utm_source=docs\&utm_medium=inline_text) if you'd like us to create guides for your preferred tool! Prisma Plugin [#prisma-plugin] The [Prisma plugin for Cursor](https://cursor.com/marketplace/prisma) provides integration with the Prisma MCP server, various skills for working with Prisma ORM and Prisma Postgres, and automation for database development. [Install the Prisma plugin for Cursor](https://cursor.com/marketplace/prisma) Prisma MCP server [#prisma-mcp-server] Prisma provides its own [Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) server that lets you manage Prisma Postgres databases, inspect schemas, and execute SQL queries. Learn more about how you can add it to Cursor [here](/ai/tools/mcp-server#cursor). You can also add the Prisma MCP server to Cursor using the [one-click installation](https://docs.cursor.com/context/model-context-protocol#one-click-installation) by clicking on the following link: [Install MCP Server](https://pris.ly/cursor-prisma-mcp-web) This will prompt you to open the Cursor app in your browser. Once opened, you'll be guided to install the Prisma MCP server directly into your Cursor configuration. Define project-specific rules [#define-project-specific-rules] [Cursor Rules](https://docs.cursor.com/context/rules) provide persistent instructions to Cursor's Agent and Inline Edit. For Prisma projects, prefer one of these current options: * **Project Rules**: Create a version-controlled `.cursor/rules/prisma.mdc` file for structured rules. * **`AGENTS.md`**: Create an `AGENTS.md` file in the project root for simple, readable agent instructions. The legacy `.cursorrules` file is still supported by Cursor, but Cursor recommends Project Rules for new projects. Below is a concise Project Rule you can add to `.cursor/rules/prisma.mdc`: ```markdown title=".cursor/rules/prisma.mdc" --- description: Prisma ORM and Prisma Postgres guidance globs: **/*.{ts,tsx,js,jsx,prisma,json} alwaysApply: false --- - Prefer current Prisma documentation from https://www.prisma.io/docs and the Prisma LLM feed at https://pris.ly/llms.txt. - For Prisma ORM v7 projects, use the `prisma-client` generator with an explicit `output`. - Keep database connection URLs in `prisma.config.ts`; do not add `url = env("DATABASE_URL")` to the Prisma schema unless the project is intentionally using older Prisma ORM conventions. - Use `prisma.config.ts` with `datasource.url = env("DATABASE_URL")` for Prisma CLI commands. - Instantiate Prisma Client with the correct driver adapter for the database, for example `@prisma/adapter-pg` for PostgreSQL. - When creating or managing Prisma Postgres databases, prefer the Prisma MCP server tools instead of guessing CLI/API steps. - Before changing Prisma setup, inspect `package.json`, `prisma.config.*`, `schema.prisma`, existing generated client imports, and the installed Prisma version. - Preserve existing Prisma Accelerate usage unless explicitly asked to migrate it. ## Prisma application best practices - Validate inputs at API boundaries before calling Prisma Client. - Use `select` or scoped `include` to avoid over-fetching data. - Use transactions for multi-step writes that must succeed or fail together. - Handle known Prisma errors intentionally, especially constraint and validation errors. - Prefer integration tests against the same database provider used in production when testing Prisma behavior. - Mock Prisma Client only for isolated unit tests where database behavior is not under test. - Review generated migrations before applying them to shared or production environments. - Avoid exposing database-specific errors directly to end users. - Keep Prisma-related database access separate from unrelated business logic when it improves maintainability. ``` For a simpler repo-wide setup, you can paste the same guidance into `AGENTS.md`. Using Cursor's context-aware capabilities [#using-cursors-context-aware-capabilities] Cursor's [context-aware](https://docs.cursor.com/context/) capabilities let you add specific websites, files, folders or documentation to enhance its understanding of your project. By adding your `schema.prisma` file as context, you enable Cursor to generate more accurate queries, tests, and seed data based on your database schema. Add Prisma docs llm.txt file as @Docs context [#add-prisma-docs-llmtxt-file-as-docs-context] To improve Cursor's understanding of Prisma-related suggestions in your project, include the [`/llms.txt`](https://llmstxt.org/) markdown file as context. This file offers a concise overview, useful guidance, and links to detailed Prisma documentation—all optimized for LLM processing. Simply navigate to the [url](https://pris.ly/llms.txt) and add it as a `@Docs` resource in your Cursor configuration. Adding additional Prisma documentation [#adding-additional-prisma-documentation] Cursor may already have Prisma documentation available in its built-in docs context, but external documentation indexes can lag behind the latest Prisma release. Add the Prisma LLM feed explicitly when you need Cursor to follow the current recommended setup. To stay updated with the latest changes or incorporate additional context, add these resources as `@Docs` context: * [Prisma Changelog](https://www.prisma.io/changelog) for updates and new features. * [Prisma Blog](https://www.prisma.io/blog) for practical guides and best practices. To learn how to add and manage documentation context, visit the [Cursor documentation](https://docs.cursor.com/context/@-symbols/@-docs#docs). Using schema as context [#using-schema-as-context] Add your `schema.prisma` file (or the entire codebase) as context using the [`@Files`](https://docs.cursor.com/context/@-symbols/@-files) syntax before requesting queries, tests, or seed scripts. This allows Cursor to generate precise, schema-driven outputs such as queries, tests, and seed data. For example, in [Cursor Chat](https://docs.cursor.com/chat/overview), you can include your schema by typing `@Files` followed by adding your `schema.prisma` file. Generating Prisma Schema [#generating-prisma-schema] Cursor can generate Prisma schemas from high-level descriptions, enabling you to quickly establish a solid foundation for your database schema. By providing a clear and detailed prompt, Cursor creates Prisma schemas tailored to your requirements. Whether you need a general foundational schema or a highly specific one for detailed use cases, Cursor can deliver with precision. Here's an example prompt and its corresponding result: > [!NOTE] > If you run the prompts below, you may receive a different outputs because LLMs produce non-deterministic responses. #### Prompt to generate Prisma schema ```text "Create a Prisma schema for a SaaS app using PostgreSQL as a provider with `User`, `Organization`, and `Subscription` models, ensuring all models include `createdAt` and `updatedAt` DateTime fields with defaults, a soft-delete `deletedAt` field, and proper relationships between entities." ``` #### Result ```prisma title="schema.prisma" generator client { provider = "prisma-client" output = "./generated" } datasource db { provider = "postgresql" } model User { id Int @id @default(autoincrement()) email String @unique name String password String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int role UserRole @default(MEMBER) } model Organization { id Int @id @default(autoincrement()) name String slug String @unique subscription Subscription? users User[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } model Subscription { id Int @id @default(autoincrement()) organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int @unique plan SubscriptionPlan status SubscriptionStatus @default(ACTIVE) startDate DateTime endDate DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } enum UserRole { ADMIN MEMBER } enum SubscriptionPlan { FREE BASIC PREMIUM ENTERPRISE } enum SubscriptionStatus { ACTIVE CANCELED EXPIRED PAST_DUE } ``` Generating Prisma queries [#generating-prisma-queries] Cursor can help you create queries tailored to your Prisma schema, whether for basic data retrieval or complex, optimized operations. To get the best results, focus on writing clear, specific prompts that define your requirements, such as the fields to include, conditions to apply, and relationships to traverse. This ensures Cursor generates accurate, performant, and type-safe queries. Here's an example prompt and its resulting query: #### Prompt to generate a database query ```text "Generate a query to retrieve all User records associated with an Organization that has an `active` Subscription, while excluding any records where the deletedAt field is set." ``` #### Result ```typescript const activeUsers = await prisma.user.findMany({ where: { deletedAt: null, organization: { deletedAt: null, subscription: { deletedAt: null, status: "ACTIVE", }, }, }, include: { organization: { include: { subscription: true, }, }, }, orderBy: { createdAt: "desc", }, skip: 0, take: 10, }); ``` Creating seed files with Cursor [#creating-seed-files-with-cursor] Writing seed scripts can be a tedious process, but Cursor simplifies it by quickly generating structured and organized seed code. By providing clear instructions, you can guide Cursor to create scripts that populate your database with realistic data, including handling relationships and complex structures defined in your schema. Here's an example prompt and its resulting seed script: #### Prompt to seed the database ```text "Generate code to populate the Prisma schema with realistic data for the User, Organization, and Subscription models, ensuring all necessary fields are included." ``` #### Result ```ts title="seed.ts" import { PrismaClient, UserRole, SubscriptionPlan, SubscriptionStatus, } from "../prisma/generated/client"; const prisma = new PrismaClient(); async function main() { // Clear existing data await prisma.user.deleteMany(); await prisma.subscription.deleteMany(); await prisma.organization.deleteMany(); const organizations = [ { name: "Tech Innovators", slug: "tech-innovators", subscription: { plan: SubscriptionPlan.ENTERPRISE, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-01"), }, users: [ { name: "Emma Thompson", email: "emma@techinnovators.com", role: UserRole.ADMIN, password: "password123", }, { name: "Michael Chen", email: "michael@techinnovators.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Digital Solutions", slug: "digital-solutions", subscription: { plan: SubscriptionPlan.PREMIUM, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-15"), }, users: [ { name: "Sarah Wilson", email: "sarah@digitalsolutions.com", role: UserRole.ADMIN, password: "password123", }, { name: "James Miller", email: "james@digitalsolutions.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Cloud Systems", slug: "cloud-systems", subscription: { plan: SubscriptionPlan.BASIC, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-02-01"), }, users: [ { name: "David Garcia", email: "david@cloudsystems.com", role: UserRole.ADMIN, password: "password123", }, { name: "Lisa Wang", email: "lisa@cloudsystems.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Data Analytics Co", slug: "data-analytics", subscription: { plan: SubscriptionPlan.PREMIUM, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-10"), }, users: [ { name: "Alex Johnson", email: "alex@dataanalytics.com", role: UserRole.ADMIN, password: "password123", }, { name: "Rachel Kim", email: "rachel@dataanalytics.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Smart Solutions", slug: "smart-solutions", subscription: { plan: SubscriptionPlan.FREE, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-02-15"), }, users: [ { name: "Daniel Brown", email: "daniel@smartsolutions.com", role: UserRole.ADMIN, password: "password123", }, { name: "Maria Rodriguez", email: "maria@smartsolutions.com", role: UserRole.MEMBER, password: "password123", }, ], }, ]; for (const org of organizations) { const createdOrg = await prisma.organization.create({ data: { name: org.name, slug: org.slug, subscription: { create: { plan: org.subscription.plan, status: org.subscription.status, startDate: org.subscription.startDate, }, }, }, }); for (const user of org.users) { await prisma.user.create({ data: { name: user.name, email: user.email, password: user.password, role: user.role, organizationId: createdOrg.id, }, }); } } console.log("Seed data created successfully"); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Using the Prisma VS Code extension to manage your database [#using-the-prisma-vs-code-extension-to-manage-your-database] The [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) is a powerful tool for building applications with [Prisma Postgres](/postgres). You can also use it in Cursor by installing the extension. It provides a dedicated UI for managing Prisma Postgres instances, both local and remote, making it easy to view, create, and delete instances, push local databases to the cloud, and visualize your schema. Database management UI [#database-management-ui] With its built-in database management interface, the [Prisma VS Code extension](/guides/postgres/vscode) lets you easily work with local and remote Prisma Postgres instances from inside your editor. Workflows [#workflows] The UI enables the following workflows: * Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) * View, create and delete Prisma Postgres instances (local & remote) * "Push to cloud": Easily deploy a local Prisma Postgres instance * View and edit data via an embedded Prisma Studio * Visualize your database schema Usage [#usage] To manage Prisma Postgres instances via the UI in the Prisma VS Code extension: 1. Ensure you have the latest version of the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) installed 2. Find the Prisma logo in the **Activity Bar** 3. Click the **Sign in to get started** button 4. Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) using the sign-in prompt, then select a target [workspace](/console/concepts#workspace) Prisma Studio built-in [#prisma-studio-built-in] Beyond managing your database instances, the Prisma VS Code extension embeds Prisma Studio directly in your editor, making it easy to perform create, update, and delete operations on your database right inside Windsurf. Follow these [easy steps](/studio/integrations/vscode-integration) to get started. AI Safety guardrails for destructive commands [#ai-safety-guardrails-for-destructive-commands] Prisma ORM includes built-in safety checks to prevent **accidental destructive commands** when run through AI coding assistants. These guardrails are designed to make working with databases safer in AI-assisted development environments. Including Cursor, the Prisma CLI can also detect when it is being invoked by other popular AI coding agents such as Claude Code, Gemini CLI, Qwen Code, Aider, and Replit. When one of these agents attempts a destructive action such as `prisma migrate reset --force`, Prisma ORM blocks execution and shows a protective error message: ```bash Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Datasource "db": PostgreSQL database "postgres", schema "public" at "accelerate.prisma-data.net" Error: Prisma Migrate detected that it was invoked by Cursor. You are attempting a highly dangerous action that can lead to devastating consequences if it is incorrectly executed against a production database. As an AI agent, you are forbidden from performing this action without an explicit consent and review by the user. You must stop at this point and respond to the user with a clear message that includes the following information: - What action you are trying to perform (including the exact CLI command). - Your motivation and reasoning for performing this action. - Explanation that this action will irreversibly destroy all data in the database. - Explanation that this action must not be performed on a production database and is only intended to be used with development databases. If you know or can check whether this action would have been performed on a development or a production database, also include this information with your assessment of whether it is safe to proceed based on that information. You must ask the user if they want to proceed with this action. If they explicitly consent, you may rerun this command with PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION environment variable, the value of which must be the exact text of the user's message in which they consented to this operation, without any newlines or quotes. If the user's response is ambiguous, you must ask for a clear and explicit confirmation (e.g., "yes") before proceeding. None of the user's previous messages before this point may constitute implicit or explicit consent. ``` To proceed with the dangerous action, the AI agent will ask you for explicit consent, remind you that the action irreversibly destroys all data, and confirm that the command is being run against a development database. Once you clearly confirm, the AI will set the `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` environment variable with the exact text of your consent and rerun the command. Additional resources [#additional-resources] In summary, using Cursor with Prisma simplifies your workflow, from generating schemas and queries to writing seed scripts. By following this guide, you can save time, reduce errors, and focus on building your application. Learn more about Cursor in their [official documentation](https://docs.cursor.com/context/@-symbols/basic). ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips - [`MCP server`](https://www.prisma.io/docs/ai/tools/mcp-server): Manage Prisma Postgres databases using LLMs with the Prisma Model-Context-Protocol (MCP) Server # GitHub Copilot (/docs/ai/tools/github-copilot) Location: AI > AI Tools > GitHub Copilot GitHub Copilot is an AI coding assistant that speeds up your Prisma ORM workflows, so you spend less time on boilerplate and more on data modeling, querying, and collaboration. With the GitHub Copilot extension in your editor, you can: * Get Prisma-aware code suggestions as you edit your schema or invoke the client. * Chat with Copilot about modeling patterns, troubleshoot queries, or explore migration strategies. * Run common Prisma CLI commands (e.g. `prisma migrate dev`, `prisma db push`) via Copilot's command-palette interface. * Scaffold Prisma schema models and generate Prisma Client code and run migrations directly from the Copilot chat interface. GitHub Copilot allows you to query the official docs via the [**Prisma for GitHub Copilot** extension](https://github.com/apps/prisma-for-github-copilot) and also perform automated [actions in VS Code agent mode](/guides/postgres/vscode#agent-mode), such as scaffolding a Prisma schema, running seed scripts, and creating a production-ready Prisma Postgres database. Query Prisma docs with the Prisma for GitHub Copilot extension [#query-prisma-docs-with-the-prisma-for-github-copilot-extension] The [Prisma for GitHub Copilot extension](https://github.com/apps/prisma-for-github-copilot) lets you fetch Prisma documentation directly in GitHub Copilot Chat. You can look up schema syntax, client methods, migration commands, and more from your editor. How to enable the extension [#how-to-enable-the-extension] 1. Install the **Prisma for Copilot** from the GitHub Marketplace. 2. Ensure [GitHub Copilot Chat is installed](https://docs.github.com/en/copilot/using-github-copilot/copilot-chat/asking-github-copilot-questions-in-your-ide) and active in your code editor. 3. Open a file in your workspace and launch Copilot Chat. 4. In chat, prefix your question with the `@prisma-for-copilot` keyword: ``` @prisma-for-copilot How do I define a one-to-many relation? ``` 1. Install the [Prisma for GitHub Copilot](https://github.com/apps/prisma-for-github-copilot) extension. 2. Open your IDE. 3. Install the [GitHub Copilot Chat extension](https://docs.github.com/en/copilot/managing-copilot/configure-personal-settings/installing-the-github-copilot-extension-in-your-environment). 4. Open Copilot Chat and switch to [**Ask** mode](https://code.visualstudio.com/docs/copilot/chat/chat-ask-mode). 5. Ask: "`@prisma-for-github-copilot` How do I define a one-to-many relation?" (If the `@prisma-for-github-copilot` namespace doesn't show up after a few seconds, reload the chat.) 6. When prompted, authorize the Prisma app in your browser, then return to the chat. 7. After returning to the chat, resend the question. 8. Copilot returns the answer pulled straight from the Prisma docs. Use GitHub Copilot's agent features [#use-github-copilots-agent-features] GitHub Copilot Chat offers an **Agent** mode in VS Code that can run Prisma commands. You can use the agent chat to: * Run and inspect migrations. * Generate Prisma Client code. * Create a new Prisma Postgres database and update your `.env` file. You can type `Create a database named test-db and add its connection string to the .env file.` in the Copilot chat, and it will automatically create a new database named `test-db` and add the connection string to your `.env` file. To learn more about this, visit our [VS Code agent mode documentation](/guides/postgres/vscode#agent-mode). Customize GitHub Copilot with copilot-instructions.md [#customize-github-copilot-with-copilot-instructionsmd] You can tailor Copilot Chat's behavior in your repository by [adding a `.github/copilot-instructions.md` file](https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot). This file injects your guidelines into every Copilot Chat session.
Example `.github/copilot-instructions.md` for Prisma ````text # GitHub Copilot Instructions for Prisma Workspace ## General Guidelines 1. **Language**: English only. 2. **Types**: Declare explicit types; avoid `any`. 3. **Comments**: Use JSDoc for public methods and classes. 4. **Exports**: One export per file. 5. **Naming**: * **Classes/interfaces** → `PascalCase` * **Variables/functions** → `camelCase` * **Files/directories** → `kebab-case` * **Constants** → `UPPERCASE` * **Boolean flags** → verb-based (e.g., `isLoading`) --- ## Prisma-Specific Guidelines ### 1. Data Modeling * **Domain-driven model names**: keep them singular (e.g. `User`, `OrderItem`). * **Field naming**: use `camelCase` for fields (e.g. `createdAt`, `deletedAt`). * **IDs & keys**: ```prisma model Post { id Int @id @default(autoincrement()) uuid String @unique @default(uuid()) } /``` * **Composite keys & uniques**: ```prisma @@id([userId, role]) @@unique([email, tenantId]) /``` * **Enums & constrained values**: leverage `enum` for fixed domains. * **Soft deletes & audit**: ```prisma model Base { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } /``` ### 2. Indexing & Constraints * **Single-column indexes** for frequent lookups: ```prisma @@index([email]) /``` * **Compound indexes** for multi-field filters/sorts: ```prisma @@index([status, createdAt]) /``` * **Full-text search** (Postgres-only): ```prisma @@index([title, content], type: Brin) // or Gin for JSONB /``` ### 3. Migrations * **Descriptive names**: `npx prisma migrate dev --name add-order-totals` * **Idempotent steps**: avoid imperative SQL in migrations. * **Shadow database**: enable in CI to catch drift. * **Never edit** migration SQL after it’s applied to any environment. ### 4. Client Instantiation & Connection Management * **Singleton pattern** ```ts // prisma.ts import { PrismaClient } from '../prisma/generated/client'; export const prisma = global.prisma || new PrismaClient(); if (process.env.NODE_ENV !== 'production') global.prisma = prisma; /``` ### 5. Transactions & Batch Operations * **Multi-step atomicity**: ```ts const result = await prisma.$transaction([ prisma.user.create({ data: { /*…*/ } }), prisma.order.create({ data: { /*…*/ } }), ]); /``` * **Interactive transactions** for long-running flows. * **Bulk writes**: chunk large inserts/updates to avoid timeouts. ### 6. Precise Queries & Performance * **Select only needed fields**: ```ts await prisma.user.findUnique({ where: { id }, select: { id: true, email: true }, }); /``` * **Avoid N+1**: use `include` or batch `findMany` with `where: { id: { in: [...] } }` or use database joins in prisma. * Use **Cursor-based pagination** ### 7. Raw Queries & Client Extensions * **Raw SQL** when necessary, safely: ```ts const users = await prisma.$queryRaw`SELECT * FROM "User" WHERE email = ${email}`; /``` * **Sanitize inputs** with `Prisma.sql` for complex interpolations. * **Client extensions**: use preview feature `clientExtensions` to add common helper methods. ### 8. Error Handling * **Catch specific errors**: ```ts try { // … } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError) { // P2002: Unique constraint } } /``` * **Wrap in service-level errors** to add context before bubbling up. ### 9. Testing * **In-memory DB** (SQLite) or **Testcontainers** for integration tests. * **Mock Prisma Client** for pure unit tests via `jest.mock()` or similar. ### 10. Logging, Monitoring & Metrics * **Enable query logging** in dev: ```ts new PrismaClient({ log: ['query', 'warn', 'error'] }); /``` * **APM integration** (Datadog, Sentry) – capture latency, errors. ### 11. Security & Best Practices * **Never expose** raw Prisma client in HTTP controllers—wrap in a service layer. * **Validate inputs** (e.g. with Zod) before any DB operation. * **Least privilege** DB users: use separate roles for migrations vs. runtime. * **Rotate credentials** and load from secure vault (AWS Secrets Manager, etc.). ### 12. Environment & Configuration * **Centralize `DATABASE_URL`** and connection settings in `.env`. * **Pin preview features** in `schema.prisma`: ```prisma generator client { previewFeatures = ["clientExtensions", "interactiveTransactions"] } /``` * **Version pinning**: match CLI and client versions in `package.json`. ````
Place this file at the root of your repository under `.github/`. Copilot Chat automatically applies these rules to every conversation in your project. ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`MCP server`](https://www.prisma.io/docs/ai/tools/mcp-server): Manage Prisma Postgres databases using LLMs with the Prisma Model-Context-Protocol (MCP) Server # MCP server (/docs/ai/tools/mcp-server) Location: AI > AI Tools > MCP server Overview [#overview] The [Model-Context-Protocol](https://modelcontextprotocol.io/introduction) (MCP) gives LLMs a way to call APIs and access external systems in a well-defined manner. Prisma provides an MCP server that lets AI tools manage Prisma Postgres databases through the standard HTTP transport. The server authenticates with Prisma Console on first use so your AI tool can access the workspace you choose. Tools [#tools] [Tools](https://modelcontextprotocol.io/docs/concepts/tools) represent the *capabilities* of an MCP server. Here's the list of tools exposed by the Prisma MCP server: * `CreateBackupTool`: Create a new managed Prisma Postgres Backup. * `CreateConnectionStringTool`: Create a new Connection String for a Prisma Postgres database with the given id. * `CreateRecoveryTool`: Restore a Prisma Postgres Database to a new database with the given Backup id. * `DeleteConnectionStringTool`: Delete a Connection String with the given connection string id. * `DeleteDatabaseTool`: Delete a Prisma Postgres database with the given id. * `ListBackupsTool`: Fetch a list of available Prisma Postgres Backups for the given database id and environment id. * `ListConnectionStringsTool`: Fetch a list of available Prisma Postgres Database Connection Strings for the given database id and environment id. * `ListDatabasesTool`: Fetch a list of available Prisma Postgres Databases for user's workspace. * `ExecuteSqlQueryTool`: Execute a SQL query on a Prisma Postgres database with the given id. * `IntrospectSchemaTool`: Introspect the schema of a Prisma Postgres database with the given id. Once you're connected to the Prisma MCP server, you can also always prompt your AI agent to "List the Prisma tools" to get a full overview of the latest supported tools. Usage [#usage] The Prisma MCP server follows the standard JSON-based configuration for MCP servers. Here's what it looks like: ```json title="MCP configuration" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` Sample prompts [#sample-prompts] * "Show me a list of all the databases in my account." * "Create a new database in the US region for me." * "Seed my database with real-looking data but create a backup beforehand." * "Show me all available backups of my database." * "Show me all customers and run an analysis over their orders." Integrating in AI tools [#integrating-in-ai-tools] AI tools have different ways of integrating MCP servers. In most cases, there are dedicated configuration files where you add the JSON configuration from above. Below, we're covering the config formats of the most popular AI tools. VS Code [#vs-code] Install the Prisma MCP server in VS Code with a single click using the link below: VS CODE INSTALL PRISMA MCP SERVER This will prompt you to open VS Code. Once opened, you'll be guided to install the Prisma MCP server directly into your VS Code configuration. If your browser blocks the link, [you can set it up manually](https://code.visualstudio.com/docs/copilot/chat/mcp-servers#_add-an-mcp-server-to-your-workspace) by creating a `.vscode/mcp.json` file in your workspace and adding: ```json title=".vscode/mcp.json" { "servers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` Explore additional Prisma features and workflows for VS Code in [our docs](/guides/postgres/vscode). Codex [#codex] The Prisma Codex plugin includes the remote Prisma MCP server and curated Prisma skills for Prisma ORM, Prisma Client, database setup, Prisma Postgres, and Prisma ORM upgrades. Add the Prisma plugin marketplace to Codex: ```bash title="Codex" codex plugin marketplace add prisma/codex-plugin ``` Restart Codex, open the plugin directory, select the Prisma marketplace, and install the `Prisma` plugin. The plugin configures the remote Prisma MCP server at `https://mcp.prisma.io/mcp`; on first use, Codex will authenticate with Prisma Console so it can access the workspace you choose. Learn more in the [Codex integration guide](/ai/tools/codex). Cursor [#cursor] To learn more about Cursor's MCP integration, check out the [Cursor MCP docs](https://docs.cursor.com/context/model-context-protocol#configuration-locations). Add via one-click installation [#add-via-one-click-installation] You can add the Prisma MCP server to Cursor using the [one-click installation](https://docs.cursor.com/context/model-context-protocol#one-click-installation) by clicking on the following link: Install MCP Server This will prompt you to open the Cursor app in your browser. Once opened, you'll be guided to install the Prisma MCP server directly into your Cursor configuration. Add via Cursor Settings UI [#add-via-cursor-settings-ui] When opening the **Cursor Settings**, you can add the Prisma MCP Server as follows: 1. Select **MCP** in the settings sidenav 2. Click **+ Add new global MCP server** 3. Add the `Prisma` snippet to the `mcpServers` JSON object: ```json title="Cursor MCP configuration" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` Global configuration [#global-configuration] Adding it via the **Cursor Settings** settings will modify the global `~/.cursor/mcp.json` config file. In this case, the Prisma MCP server will be available in *all* your Cursor projects: ```json title="~/.cursor/mcp.json" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } // other MCP servers } } ``` Project configuration [#project-configuration] If you want the Prisma MCP server to be available only in specific Cursor projects, add it to the Cursor config of the respective project inside the `.cursor` directory in the project's root: ```json title=".cursor/mcp.json" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } // other MCP servers } } ``` Windsurf [#windsurf] To learn more about Windsurf's MCP integration, check out the [Windsurf MCP docs](https://docs.windsurf.com/windsurf/cascade/mcp). Add via Windsurf MCP Plugin Store (Recommended) [#add-via-windsurf-mcp-plugin-store-recommended] Use the Prisma MCP plugin from the [Windsurf MCP Plugin Store](https://docs.windsurf.com/windsurf/cascade/mcp#adding-a-new-mcp-plugin). Follow [the steps here](/ai/tools/windsurf#add-prisma-mcp-server-via-windsurf-plugins) to add the Prisma MCP plugin in Windsurf. This is the simplest and recommended way to add the Prisma MCP server to Windsurf. Add via Windsurf Settings UI [#add-via-windsurf-settings-ui] When opening the **Windsurf Settings** (via **Windsurf - Settings** > **Advanced Settings or Command Palette** > **Open Windsurf Settings Page**), you can add the Prisma MCP Server as follows: 1. Select **Cascade** in the settings sidenav 2. Click **Add Server** 3. Add the `Prisma` snippet to the `mcpServers` JSON object: ```json title="Windsurf MCP configuration" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` Global configuration [#global-configuration-1] Adding it via the **Windsurf Settings** will modify the global `~/.codeium/windsurf/mcp_config.json` config file. Alternatively, you can also manually add it to that file: ```json title="~/.codeium/windsurf/mcp_config.json" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } // other MCP servers } } ``` Warp [#warp] You can add the Prisma MCP to Warp as a globally available tool. First, [visit your MCP settings](https://docs.warp.dev/knowledge-and-collaboration/mcp#how-to-access-mcp-server-settings) and click **+ Add**. From here, you can configure the Prisma MCP server as JSON: ```json title="Warp MCP configuration" { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } ``` Hit **Save** and ensure the MCP server is running from your MCP settings panel. Then, open a new terminal window and ask Warp to manage your Prisma database. It should reach for the Prisma MCP server automatically. To learn more about Warp's MCP integration, visit the [Warp MCP docs](https://docs.warp.dev/knowledge-and-collaboration/mcp). Claude Code [#claude-code] Claude Code is a terminal-based AI tool where you can add MCP servers using the `claude mcp add` command: ```bash title="Claude Code" claude mcp add --transport http prisma https://mcp.prisma.io/mcp ``` Learn more in the [Claude Code MCP docs](https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/tutorials#configure-mcp-servers). Claude Desktop only [#claude-desktop-only] Follow the instructions in the [Claude Desktop MCP docs](https://modelcontextprotocol.io/quickstart/user#2-add-the-filesystem-mcp-server) to create the required configuration file: * macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` * Windows: `%APPDATA%\Claude\claude_desktop_config.json` Then add the JSON snippet to that configuration file: ```json title="Claude Desktop configuration" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } // other MCP servers } } ``` Claude Desktop & Web [#claude-desktop--web] Alternatively, you can add the Prisma MCP server as an [integration](https://www.anthropic.com/news/integrations): 1. In a new chat, find the **Connect apps** field in the main Claude UI below the input prompt field 2. Click **+ Add integration** 3. Enter the following: * **Integration name**: `Prisma Postgres` * **Integration URL**: `https://mcp.prisma.io/mcp` 1. Click **Add** ChatGPT [#chatgpt] You can add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases using natural language. Learn more about setting it up in our [ChatGPT integration guide](/ai/tools/chatgpt). Gemini CLI [#gemini-cli] Gemini CLI can add the Prisma MCP server using HTTP transport: ```bash title="Gemini CLI" gemini mcp add --transport http Prisma https://mcp.prisma.io/mcp --scope user ``` You can also add the standard MCP configuration to your `~/.gemini/settings.json` file: ```json title="~/.gemini/settings.json" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` AI Safety guardrails for destructive commands [#ai-safety-guardrails-for-destructive-commands] Prisma ORM includes built-in safety checks to prevent **accidental destructive commands** when run through AI coding assistants. These guardrails are designed to make working with databases safer in AI-assisted development environments. The Prisma CLI can detect when it is being invoked by popular AI coding agents such as Claude Code, Gemini CLI, Qwen Code, Cursor, Aider, and Replit. When one of these agents attempts a destructive action such as `prisma migrate reset --force`, Prisma ORM blocks execution and shows a protective error message: ```bash title="Destructive command guardrail" Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Datasource "db": PostgreSQL database "postgres", schema "public" at "accelerate.prisma-data.net" Error: Prisma Migrate detected that it was invoked by Cursor. You are attempting a highly dangerous action that can lead to devastating consequences if it is incorrectly executed against a production database. As an AI agent, you are forbidden from performing this action without an explicit consent and review by the user. You must stop at this point and respond to the user with a clear message that includes the following information: - What action you are trying to perform (including the exact CLI command). - Your motivation and reasoning for performing this action. - Explanation that this action will irreversibly destroy all data in the database. - Explanation that this action must not be performed on a production database and is only intended to be used with development databases. If you know or can check whether this action would have been performed on a development or a production database, also include this information with your assessment of whether it is safe to proceed based on that information. You must ask the user if they want to proceed with this action. If they explicitly consent, you may rerun this command with PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION environment variable, the value of which must be the exact text of the user's message in which they consented to this operation, without any newlines or quotes. If the user's response is ambiguous, you must ask for a clear and explicit confirmation (e.g., "yes") before proceeding. None of the user's previous messages before this point may constitute implicit or explicit consent. ``` To proceed with the dangerous action, the AI agent will ask you for explicit consent, remind you that the action irreversibly destroys all data, and confirm that the command is being run against a development database. Once you clearly confirm, the AI will set the `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` environment variable with the exact text of your consent and rerun the command. ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips # Agent Skills (/docs/ai/tools/skills) Location: AI > AI Tools > Agent Skills AI coding agents often struggle with Prisma 7 -they generate outdated v6 patterns, hallucinate APIs, and miss breaking changes like ESM-only support and required driver adapters. **Prisma Skills** fix this by giving your agent accurate, version-specific knowledge it can reference automatically. Skills are packaged instructions that follow the open [Agent Skills](https://agentskills.io/) format. Once installed, your agent uses them whenever it detects a relevant task -no prompting required. Install [#install] Add all Prisma skills to your project: #### npm ```bash npx skills add prisma/skills ``` #### pnpm ```bash pnpm dlx skills add prisma/skills ``` #### yarn ```bash yarn dlx skills add prisma/skills ``` #### bun ```bash bunx --bun skills add prisma/skills ``` Or install only the ones you need: #### npm ```bash npx skills add prisma/skills --skill prisma-client-api ``` #### pnpm ```bash pnpm dlx skills add prisma/skills --skill prisma-client-api ``` #### yarn ```bash yarn dlx skills add prisma/skills --skill prisma-client-api ``` #### bun ```bash bunx --bun skills add prisma/skills --skill prisma-client-api ``` > [!NOTE] > Skills are compatible with any agent that supports the [Agent Skills](https://agentskills.io/) format, including Claude Code, Cursor, and others. Available skills [#available-skills] prisma-cli [#prisma-cli] Complete reference for all Prisma CLI commands in v7. Covers `init`, `generate`, `dev`, `migrate dev`, `migrate deploy`, `db push`, `db pull`, `db seed`, `studio`, and more. Use this when your agent needs to run Prisma commands, set up projects, or manage migrations. prisma-client-api [#prisma-client-api] Comprehensive Prisma Client API reference for v7. Covers CRUD operations (`findMany`, `create`, `update`, `delete`), query options (`select`, `include`, `omit`, `orderBy`), filter operators, transactions (`$transaction`), raw queries (`$queryRaw`, `$executeRaw`), and client methods (`$connect`, `$disconnect`, `$extends`). prisma-upgrade-v7 [#prisma-upgrade-v7] Step-by-step migration guide from Prisma v6 to v7. Covers ESM module configuration, required driver adapters, the new `prisma.config.ts` file, manual environment variable loading, and removed features (middleware, metrics, deprecated CLI flags). Essential for upgrading existing projects. prisma-database-setup [#prisma-database-setup] Guides for configuring Prisma with different database providers. Covers PostgreSQL, Prisma Postgres, MySQL/MariaDB, SQLite, MongoDB, SQL Server, and CockroachDB. Use this when setting up a new project or switching databases. prisma-postgres [#prisma-postgres] Prisma Postgres workflows across Console, CLI, Management API, and SDK. Covers `npx create-db`, Console operations, programmatic provisioning via the Management API, and the `@prisma/management-api-sdk`. Use this when creating or managing Prisma Postgres databases. Useful commands [#useful-commands] List available skills before installing: #### npm ```bash npx skills add prisma/skills --list ``` #### pnpm ```bash pnpm dlx skills add prisma/skills --list ``` #### yarn ```bash yarn dlx skills add prisma/skills --list ``` #### bun ```bash bunx --bun skills add prisma/skills --list ``` List skills currently installed in your project: #### npm ```bash npx skills list ``` #### pnpm ```bash pnpm dlx skills list ``` #### yarn ```bash yarn dlx skills list ``` #### bun ```bash bunx --bun skills list ``` Example prompts [#example-prompts] Once skills are installed, your agent will use them automatically. Try prompts like: * *"Set up Prisma with PostgreSQL in this project"* * *"Upgrade this project from Prisma 6 to 7"* * *"Write a query to find all users with their posts"* * *"Run migrations for production"* * *"Create a new Prisma Postgres database"* Learn more [#learn-more] * [Prisma Skills on skills.sh](https://skills.sh/prisma/skills) - browse available skills and install instructions * [GitHub repository](https://github.com/prisma/skills) - source code, contribution guidelines, and skill structure * [Agent Skills format](https://agentskills.io/) - the open standard behind skills ## Related pages - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips - [`MCP server`](https://www.prisma.io/docs/ai/tools/mcp-server): Manage Prisma Postgres databases using LLMs with the Prisma Model-Context-Protocol (MCP) Server # Tabnine (/docs/ai/tools/tabnine) Location: AI > AI Tools > Tabnine [Tabnine](https://www.tabnine.com/) is a an AI software development platform that comes as an [extension](https://www.tabnine.com/install/) for your IDE (e.g. VS Code, WebStorm, IntelliJ, ...). Overview [#overview] It helps developers write code faster by: * Providing context-aware [code completion](https://docs.tabnine.com/main/getting-started/getting-the-most-from-tabnines-code-completion) suggestions in the editor for small, repetitive coding tasks * Offering an integrated [chat](https://docs.tabnine.com/main/getting-started/getting-the-most-from-tabnine-chat) for higher-level tasks and detailed instructions Why use Prisma ORM with Tabnine? [#why-use-prisma-orm-with-tabnine] AI editors like Tabnine are powerful tools that can drastically improve developer productivity. It works especially well with the following workflows: * Data modeling and database schema design * Constructing and optimizing database queries * Generating CRUD functionality and other boilerplate code * Generating plain SQL queries that can be used with [TypedSQL](/orm/prisma-client/using-raw-sql/typedsql) * Generating code for unit and integrations tests * Guiding through major refactorings * Generating seeding scripts Leveraging the Prisma schema [#leveraging-the-prisma-schema] Because Prisma has its own [schema](/orm/prisma-schema/overview), Tabnine can understand the basic shape of your data and help you write code for the other parts of your stack. We therefore recommend that you start out by defining your Prisma schema and then use Tabnine to build the application layer around it (including API calls, DTOs, business logic, 3rd party integrations, ...). Data modeling and database schema design [#data-modeling-and-database-schema-design] How Tabnine helps [#how-tabnine-helps] Designing a database schema from scratch involves a lot of boilerplate and can be time-consuming. Tabnine can accelerate this process by: * Generating boilerplate for models, indexes, constraints, and relations. * Keeping the schema consistent by sticking to naming and other conventions. * Auto-completing model and field definitions based on common database patterns. * Suggesting relationships and field types based on naming conventions. Example: Defining a Prisma schema [#example-defining-a-prisma-schema] Prompt [#prompt] *Define a Prisma schema for a SaaS application with User, Organization, and Subscription models. Ensure relationships are properly set up.* Generated code [#generated-code] ```prisma generator client { provider = "prisma-client" output = "./generated" } datasource db { provider = "postgresql" } model User { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique name String organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int } model Organization { id Int @id @default(autoincrement()) name String slug String @unique subscription Subscription? users User[] } model Subscription { id Int @id @default(autoincrement()) organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int @unique plan String status Status } enum Status { Active Paused Expired } ``` Constructing and optimizing database queries [#constructing-and-optimizing-database-queries] How Tabnine helps [#how-tabnine-helps-1] Prisma ORM provides a convenient high-level API for writing database queries intuitively. However, queries involving filters, pagination and advanced patterns can still become complex to construct. Tabnine can help by: * Auto-completing Prisma queries based on the schema. * Suggesting `where` clauses for filters and `skip` / `take` options for pagination logic. * Helping with efficiency and performance optimizations. Example: fetching data with relationships [#example-fetching-data-with-relationships] Prompt [#prompt-1] *Generate a Prisma query to fetch all active users from an organization with an active subscription. Include data about the users' organizations in the query result.* Generated code [#generated-code-1] ```ts const activeUsers = await prisma.user.findMany({ where: { organization: { subscription: { status: "ACTIVE", }, }, }, include: { organization: true, }, }); ``` Generating CRUD functionality and other boilerplate code [#generating-crud-functionality-and-other-boilerplate-code] How Tabnine helps [#how-tabnine-helps-2] Most applications require basic CRUD operations or other boilerplate code that's usually derived from the structure of the database schema. For example, an API layer may expose a set of HTTP endpoints that allow to create, read, update or delete records of a certain model. Similarly, a frontend will data fetching and state management logic to interact with these API endpoints and update the UI accordingly. Instead of writing this code manually, Tabnine can speed up this process by: * Generating Prisma `create`, `read`, `update`, and `delete` operations for the backend and UI components for the frontend. * Auto-completing function names and argument types. * Write boilerplate code while following best practices for using DTOs, error handling, consistent API design, ... Example: Generating CRUD functionality with Next.js [#example-generating-crud-functionality-with-nextjs] Prompt [#prompt-2] *Generate CRUD functionality for a Next.js app based on the User model from the schema above.* Generated code [#generated-code-2] API endpoints [#api-endpoints] ```ts filename=app/api/users/routes.ts import { NextResponse } from "next/server"; import prisma from "../../../lib/prisma"; export async function GET() { const users = await prisma.user.findMany({ include: { organization: true }, }); return NextResponse.json(users); } export async function POST(request: Request) { const body = await request.json(); const user = await prisma.user.create({ data: { email: body.email, name: body.name, organization: { connect: { id: body.organizationId }, }, }, include: { organization: true }, }); return NextResponse.json(user); } export async function PUT(request: Request) { const body = await request.json(); const user = await prisma.user.update({ where: { id: body.id }, data: { email: body.email, name: body.name, organizationId: body.organizationId, }, include: { organization: true }, }); return NextResponse.json(user); } export async function DELETE(request: Request) { const { searchParams } = new URL(request.url); const id = searchParams.get("id"); const user = await prisma.user.delete({ where: { id: Number(id) }, }); return NextResponse.json(user); } ``` React components [#react-components] ```ts filename=app/components/User.tsx import React, { useState, useEffect } from 'react'; interface User { id: number; email: string; name: string; organizationId: number; } const User: React.FC = () => { const [users, setUsers] = useState([]); const [newUser, setNewUser] = useState({ email: '', name: '', organizationId: 0 }); useEffect(() => { fetchUsers(); }, []); const fetchUsers = async () => { const response = await fetch('/api/users'); const data = await response.json(); setUsers(data); }; const createUser = async () => { await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newUser), }); fetchUsers(); setNewUser({ email: '', name: '', organizationId: 0 }); }; const deleteUser = async (id: number) => { await fetch(`/api/users?id=${id}`, { method: 'DELETE' }); fetchUsers(); }; return (

Users

    {users.map((user) => (
  • {user.name} ({user.email}) - Org ID: {user.organizationId}
  • ))}

Create New User

setNewUser({ ...newUser, name: e.target.value })} /> setNewUser({ ...newUser, email: e.target.value })} /> setNewUser({ ...newUser, organizationId: Number(e.target.value) })} />
); }; export default User; ``` Generating plain SQL queries for use with TypedSQL [#generating-plain-sql-queries-for-use-with-typedsql] How Tabnine helps [#how-tabnine-helps-3] While Prisma provides a high-level API for querying, sometimes a developer may need to drop down to raw SQL for more low-level control of a query. In these cases, they can use [TypedSQL](/orm/prisma-client/using-raw-sql/typedsql) which provides full type safety for raq SQL queries in Prisma ORM. One common use case are aggregation queries, such as calculating percentages of different subscription statuses in the schema example above. Tabnine can assist by: * Generating SQL queries based on your Prisma schema. * Structuring complex aggregations without manual trial and error. * Integrating the queries in your application code. Example: Calculating the percentages of active, expired, and paused subscriptions [#example-calculating-the-percentages-of-active-expired-and-paused-subscriptions] Prompt [#prompt-3] *Generate a SQL query that returns the percentage of subscriptions that are Active, Paused, and Expired.* Generated SQL query [#generated-sql-query] ```sql title="prisma/sql/subscriptionsReport.sql" SELECT status, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM "Subscription") AS percentage FROM "Subscription" GROUP BY status; ``` Application code [#application-code] ```ts import { PrismaClient } from "../prisma/generated/client"; import { subscriptionsReport } from "../prisma/generated/client/sql"; const prisma = new PrismaClient(); const usersWithPostCounts = await prisma.$queryRawTyped(subscriptionsReport()); console.log(usersWithPostCounts); ``` Generating code for unit and integration tests [#generating-code-for-unit-and-integration-tests] How Tabnine helps [#how-tabnine-helps-4] Writing tests ensures that Prisma-based applications function correctly and behave according to requirements and expectations. However, writing tests is a time-consuming activity that often follows predictable and repetitive patterns. Tabnine can drastically speed up writing tests by: * Generating test boilerplate for both unit and integration tests. * Suggesting mocks and fixtures for Prisma database interactions. * Helping structure test cases to follow best practices. * Providing integration test scaffolding for testing Prisma with a real or in-memory database. Example: Writing a unit test for a Prisma service [#example-writing-a-unit-test-for-a-prisma-service] Prompt [#prompt-4] *Generate a Jest unit test for a Prisma service function that fetches all active users.* Generated code [#generated-code-3] ```ts filename=__tests__/userService.test.ts import { prismaMock } from "../prisma/singleton"; import { getActiveUsers } from "../services/userService"; test("should return only active users", async () => { prismaMock.user.findMany.mockResolvedValue([ { id: 1, name: "Alice", email: "alice@example.com" }, { id: 2, name: "Bob", email: "bob@example.com" }, ]); const users = await getActiveUsers(); expect(users).toHaveLength(2); expect(users[0].email).toBe("alice@example.com"); }); ``` Guiding through major refactorings [#guiding-through-major-refactorings] How Tabnine helps [#how-tabnine-helps-5] Thanks to Prisma ORM's type safe queries, refactoring are more safe and predictable than with other ORMs: After making schema changes, the generated Prisma Client code will be updated and the TypeScript compiler will highlight all places that need a change. However, there may still be more difficult situations during a refactoring, e.g. when business logic or complex queries need to be adjusted. Tabnine can assist during refactorings by: * Identifying patterns in your code and suggesting refactorings while maintaining consistency. * Helping update database queries after schema changes and reducing manual effort. * Providing function rewrites to simplify and optimize logic. * Suggesting breaking changes that need to be handled across your codebase. Example: Refactoring a Prisma query after a schema change [#example-refactoring-a-prisma-query-after-a-schema-change] Prompt [#prompt-5] *Refactor this Prisma query to support soft deletion using a `deletedAt` timestamp field in the User model.* Initial code [#initial-code] ```ts const users = await prisma.user.findMany(); ``` Refactored code [#refactored-code] ```ts const users = await prisma.user.findMany({ where: { deletedAt: null }, }); ``` Generating seeding scripts [#generating-seeding-scripts] How Tabnine helps [#how-tabnine-helps-6] Seeding a database with realistic test data can be cumbersome. Realistic seed data is helpful during development because it gives the developer a better impression of the application when it's used in the real-world. Tabnine can help with database seeding by: * Generating scripts with structured seed data based on the schema and with specific requirements. * Creating real-looking placeholder data that can be used to test the app. * Generate specific data to cover edge cases. Example: Creating a seed script [#example-creating-a-seed-script] Prompt [#prompt-6] *Generate a Prisma seed script for populating User, Organization, and Subscription models.* Generated code [#generated-code-4] ```ts import { PrismaClient } from "../prisma/generated/client"; const prisma = new PrismaClient(); async function main() { await prisma.organization.create({ data: { name: "Prisma Corp", slug: "prisma-corp", subscription: { create: { plan: "PRO", status: "ACTIVE", }, }, users: { create: [ { name: "Alice Doe", email: "alice@prisma.io" }, { name: "Bob Smith", email: "bob@prisma.io" }, ], }, }, }); console.log("Seed data created successfully"); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Using the Prisma VS Code extension to manage your database [#using-the-prisma-vs-code-extension-to-manage-your-database] The [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) is a powerful tool for building applications with [Prisma Postgres](/postgres). If you are using Tabnine in an editor that allows you to install the Prisma VS Code extension and you are using Prisma Postgres, you should use it. The extension provides a dedicated UI for managing Prisma Postgres instances, both local and remote, making it easy to view, create, and delete instances, push local databases to the cloud, and visualize your schema. Database management UI [#database-management-ui] With its built-in database management interface, the [Prisma VS Code extension](/guides/postgres/vscode) lets you easily work with local and remote Prisma Postgres instances from inside your editor. Workflows [#workflows] The UI enables the following workflows: * Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) * View, create and delete Prisma Postgres instances (local & remote) * "Push to cloud": Easily deploy a local Prisma Postgres instance * View and edit data via an embedded Prisma Studio * Visualize your database schema Usage [#usage] To manage Prisma Postgres instances via the UI in the Prisma VS Code extension: 1. Ensure you have the latest version of the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) installed 2. Find the Prisma logo in the **Activity Bar** 3. Click the **Sign in to get started** button 4. Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) using the sign-in prompt, then select a target [workspace](/console/concepts#workspace) Prisma Studio built-in [#prisma-studio-built-in] Beyond managing your database instances, the Prisma VS Code extension embeds Prisma Studio directly in your editor, making it easy to perform create, update, and delete operations on your database right inside Windsurf. Follow these [easy steps](/studio/integrations/vscode-integration) to get started. ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips # Windsurf (/docs/ai/tools/windsurf) Location: AI > AI Tools > Windsurf [Windsurf Editor](https://windsurf.com/editor/) is an AI-powered code editor designed to boost productivity by automating repetitive coding tasks. When paired with Prisma, a robust and type-safe toolkit for database workflows, it becomes a powerful solution for managing and optimizing database schemas, queries, and data seeding. This guide provides detailed instructions for effectively using Prisma with Windsurf to: * Define project-specific best practices with `.windsurfrules`. * Use Windsurf's context-aware capabilities. * Generate schemas, queries, and seed data tailored to your database. > [!NOTE] > While this guide is focused on Windsurf, these patterns should work with any AI editor. [Let us know on X](https://pris.ly/x?utm_source=docs\&utm_medium=inline_text) if you'd like us to create guides for your preferred tool! Prisma MCP server [#prisma-mcp-server] Prisma provides its own [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server that lets you manage Prisma Postgres databases, inspect schemas, and execute SQL queries. Add Prisma MCP server via Windsurf Plugins [#add-prisma-mcp-server-via-windsurf-plugins] You can add the Prisma MCP server via [Windsurf MCP Plugin Store](https://docs.windsurf.com/windsurf/cascade/mcp#adding-a-new-mcp-plugin). New MCP plugins can be added from the **Plugin Store**, which you can access by clicking on the **Plugins** icon in the top right menu in the **Cascade** panel, or from the **Windsurf Settings** > **Cascade** > **Plugins** section. Just search for **Prisma** in the **Plugin Store** and install the `Prisma` plugin. > [!NOTE] > You can also add the Prisma MCP server manually. Learn more about how you can add the MCP server manually to Windsurf [here](/ai/tools/mcp-server#windsurf). Defining project-specific rules with .windsurfrules [#defining-project-specific-rules-with-windsurfrules] The [`.windsurfrules` file](https://docs.windsurf.com/windsurf/cascade/memories) in Windsurf allows you to enforce best practices and development standards tailored to your Prisma project. By defining clear and consistent rules, you can ensure that Windsurf generates clean, maintainable, and project-specific code with minimal manual adjustments. To implement these rules, create a `.windsurfrules` file in the root of your project. Below is an example configuration:
Example .windsurfrules file ```text title=".windsurfrules" You are a senior TypeScript/JavaScript programmer with expertise in Prisma, clean code principles, and modern backend development. Generate code, corrections, and refactorings that comply with the following guidelines: TypeScript General Guidelines Basic Principles - Use English for all code and documentation. - Always declare explicit types for variables and functions. - Avoid using "any". - Create precise, descriptive types. - Use JSDoc to document public classes and methods. - Maintain a single export per file. - Write self-documenting, intention-revealing code. Nomenclature - Use PascalCase for classes and interfaces. - Use camelCase for variables, functions, methods. - Use kebab-case for file and directory names. - Use UPPERCASE for environment variables and constants. - Start function names with a verb. - Use verb-based names for boolean variables: - isLoading, hasError, canDelete - Use complete words, avoiding unnecessary abbreviations. - Exceptions: standard abbreviations like API, URL - Accepted short forms: - i, j for loop indices - err for errors - ctx for contexts Functions - Write concise, single-purpose functions. - Aim for less than 20 lines of code. - Name functions descriptively with a verb. - Minimize function complexity: - Use early returns. - Extract complex logic to utility functions. - Leverage functional programming techniques: - Prefer map, filter, reduce. - Use arrow functions for simple operations. - Use named functions for complex logic. - Use object parameters for multiple arguments. - Maintain a single level of abstraction. Data Handling - Encapsulate data in composite types. - Prefer immutability. - Use readonly for unchanging data. - Use as const for literal values. - Validate data at the boundaries. Error Handling - Use specific, descriptive error types. - Provide context in error messages. - Use global error handling where appropriate. - Log errors with sufficient context. Prisma-Specific Guidelines Schema Design - Use meaningful, domain-driven model names. - Leverage Prisma schema features: - Use @id for primary keys. - Use @unique for natural unique identifiers. - Utilize @relation for explicit relationship definitions. - Keep schemas normalized and DRY. - Use meaningful field names and types. - Implement soft delete with deletedAt timestamp. - Use Prisma's native type decorators. Prisma Client Usage - Always use type-safe Prisma client operations. - Prefer transactions for complex, multi-step operations. - Handle optional relations explicitly. - Use Prisma's filtering and pagination capabilities. Database Migrations - Create migrations for schema changes. - Use descriptive migration names. - Review migrations before applying. - Never modify existing migrations. - Keep migrations idempotent. Error Handling with Prisma - Catch and handle Prisma-specific errors: - PrismaClientKnownRequestError - PrismaClientUnknownRequestError - PrismaClientValidationError - Provide user-friendly error messages. - Log detailed error information for debugging. Testing Prisma Code - Use in-memory database for unit tests. - Mock Prisma client for isolated testing. - Test different scenarios: - Successful operations - Error cases - Edge conditions - Use factory methods for test data generation. - Implement integration tests with actual database. Performance Considerations - Use select and include judiciously. - Avoid N+1 query problems. - Use findMany with take and skip for pagination. - Leverage Prisma's distinct for unique results. - Profile and optimize database queries. Security Best Practices - Never expose raw Prisma client in APIs. - Use input validation before database operations. - Implement row-level security. - Sanitize and validate all user inputs. - Use Prisma's built-in protections against SQL injection. Coding Style - Keep Prisma-related code in dedicated repositories/modules. - Separate data access logic from business logic. - Create repository patterns for complex queries. - Use dependency injection for Prisma services. Code Quality - Follow SOLID principles. - Prefer composition over inheritance. - Write clean, readable, and maintainable code. - Continuously refactor and improve code structure. Development Workflow - Use version control (Git). - Implement comprehensive test coverage. - Use continuous integration. - Perform regular code reviews. - Keep dependencies up to date. ```
This file ensures consistent and maintainable code generation, reducing manual intervention while improving project quality. Using Windsurf's context-aware capabilities [#using-windsurfs-context-aware-capabilities] Windsurf's [context-awareness](https://docs.windsurf.com/context-awareness/overview) features let you leverage both your project files and external resources to enhance the AI's understanding of your project. By including your Prisma schema and relevant documentation in the context, you enable Windsurf to generate more accurate queries, tests, and seed data based on your database schema. Including Additional Prisma Resources [#including-additional-prisma-resources] Windsurf comes with built-in knowledge of common libraries, but you can further enhance its awareness by explicitly referencing external Prisma resources. This is especially useful for staying up-to-date or providing authoritative context for code generation and best practices. For example, you might reference: * [Prisma Changelog](https://www.prisma.io/changelog) * [Prisma Blog](https://www.prisma.io/blog) * [Prisma Documentation](/) Reference the resource in your requests: [#reference-the-resource-in-your-requests] When asking for code, explanations, or reviews, include the link to the relevant Prisma resource and specify that it should be used as a reference. ```bash Generate a migration script using best practices from prisma.io/docs. ``` Request persistent awareness: [#request-persistent-awareness] Ask Windsurf to always consider a specific resource for all Prisma-related work in your project. ```bash Always use the Prisma Changelog at prisma.io/changelog for Prisma updates in this project. ``` Ask for regular updates: [#ask-for-regular-updates] If you want Windsurf to check for updates or new features, explicitly request it. ```bash Before suggesting Prisma code, check the latest changes from prisma.io/changelog. ``` By referencing external resources directly in your requests or project guidelines, you ensure Windsurf leverages the most current and relevant Prisma information. Using schema as context [#using-schema-as-context] Out of the box, Windsurf automatically considers the current file, other open files, and indexed portions of your codebase as context. To ensure Cascade fully leverages your Prisma schema, keep your `schema.prisma` file open or pinned in the editor. Generating Prisma schema [#generating-prisma-schema] Windsurf can generate Prisma schemas from high-level descriptions, enabling you to quickly establish a solid foundation for your database schema. By providing a clear and detailed prompt, Windsurf creates Prisma schemas tailored to your requirements. Whether you need a general foundational schema or a highly specific one for detailed use cases, Windsurf can deliver with precision. Here's an example prompt and its corresponding result: > [!NOTE] > LLMs may produce different results each time, even with the same prompt. #### Prompt to generate Prisma schema ```text copy "Create a Prisma schema for a SaaS app using PostgreSQL as a provider with `User`, `Organization`, and `Subscription` models, ensuring all models include `createdAt` and `updatedAt` DateTime fields with defaults, a soft-delete `deletedAt` field, and proper relationships between entities." ``` #### Result ```prisma title="schema.prisma" showLineNumbers generator client { provider = "prisma-client" output = "./generated" } datasource db { provider = "postgresql" } model User { id Int @id @default(autoincrement()) email String @unique name String password String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int role UserRole @default(MEMBER) } model Organization { id Int @id @default(autoincrement()) name String slug String @unique subscription Subscription? users User[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } model Subscription { id Int @id @default(autoincrement()) organization Organization @relation(fields: [organizationId], references: [id]) organizationId Int @unique plan SubscriptionPlan status SubscriptionStatus @default(ACTIVE) startDate DateTime endDate DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } enum UserRole { ADMIN MEMBER } enum SubscriptionPlan { FREE BASIC PREMIUM ENTERPRISE } enum SubscriptionStatus { ACTIVE CANCELED EXPIRED PAST_DUE } ``` Generating Prisma queries [#generating-prisma-queries] Windsurf can help you create queries tailored to your Prisma schema, whether for basic data retrieval or complex, optimized operations. To get the best results, focus on writing clear, specific prompts that define your requirements, such as the fields to include, conditions to apply, and relationships to traverse. This ensures Windsurf generates accurate, performant, and type-safe queries. Here's an example prompt and its resulting query: #### Prompt to generate a database query ```text copy "Generate a query to retrieve all User records associated with an Organization that has an `active` Subscription, while excluding any records where the `deletedAt` field is set." ``` #### Result ```ts showLineNumbers const activeUsers = await prisma.user.findMany({ where: { deletedAt: null, organization: { deletedAt: null, subscription: { deletedAt: null, status: "ACTIVE", }, }, }, include: { organization: { include: { subscription: true, }, }, }, orderBy: { createdAt: "desc", }, skip: 0, take: 10, }); ``` Creating seed files with Windsurf [#creating-seed-files-with-windsurf] Writing seed scripts can be a tedious process, but Windsurf simplifies it by quickly generating structured and organized seed code. By providing clear instructions, you can guide Windsurf to create scripts that populate your database with realistic data, including handling relationships and complex structures defined in your schema. Here's an example prompt and its resulting seed script: #### Prompt to seed the database ```text copy "Generate code to populate the Prisma schema with realistic data for the User, Organization, and Subscription models, ensuring all necessary fields are included." ``` #### Result ```ts title="seed.ts" import { PrismaClient, UserRole, SubscriptionPlan, SubscriptionStatus, } from "../prisma/generated/client"; const prisma = new PrismaClient(); async function main() { // Clear existing data await prisma.user.deleteMany(); await prisma.subscription.deleteMany(); await prisma.organization.deleteMany(); const organizations = [ { name: "Tech Innovators", slug: "tech-innovators", subscription: { plan: SubscriptionPlan.ENTERPRISE, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-01"), }, users: [ { name: "Emma Thompson", email: "emma@techinnovators.com", role: UserRole.ADMIN, password: "password123", }, { name: "Michael Chen", email: "michael@techinnovators.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Digital Solutions", slug: "digital-solutions", subscription: { plan: SubscriptionPlan.PREMIUM, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-15"), }, users: [ { name: "Sarah Wilson", email: "sarah@digitalsolutions.com", role: UserRole.ADMIN, password: "password123", }, { name: "James Miller", email: "james@digitalsolutions.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Cloud Systems", slug: "cloud-systems", subscription: { plan: SubscriptionPlan.BASIC, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-02-01"), }, users: [ { name: "David Garcia", email: "david@cloudsystems.com", role: UserRole.ADMIN, password: "password123", }, { name: "Lisa Wang", email: "lisa@cloudsystems.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Data Analytics Co", slug: "data-analytics", subscription: { plan: SubscriptionPlan.PREMIUM, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-01-10"), }, users: [ { name: "Alex Johnson", email: "alex@dataanalytics.com", role: UserRole.ADMIN, password: "password123", }, { name: "Rachel Kim", email: "rachel@dataanalytics.com", role: UserRole.MEMBER, password: "password123", }, ], }, { name: "Smart Solutions", slug: "smart-solutions", subscription: { plan: SubscriptionPlan.FREE, status: SubscriptionStatus.ACTIVE, startDate: new Date("2024-02-15"), }, users: [ { name: "Daniel Brown", email: "daniel@smartsolutions.com", role: UserRole.ADMIN, password: "password123", }, { name: "Maria Rodriguez", email: "maria@smartsolutions.com", role: UserRole.MEMBER, password: "password123", }, ], }, ]; for (const org of organizations) { const createdOrg = await prisma.organization.create({ data: { name: org.name, slug: org.slug, subscription: { create: { plan: org.subscription.plan, status: org.subscription.status, startDate: org.subscription.startDate, }, }, }, }); for (const user of org.users) { await prisma.user.create({ data: { name: user.name, email: user.email, password: user.password, role: user.role, organizationId: createdOrg.id, }, }); } } console.log("Seed data created successfully"); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Using the Prisma VS Code extension to manage your database [#using-the-prisma-vs-code-extension-to-manage-your-database] The [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) is a powerful tool for building applications with [Prisma Postgres](/postgres). You can also use it in Windsurf by installing the extension. It provides a dedicated UI for managing Prisma Postgres instances, both local and remote, making it easy to view, create, and delete instances, push local databases to the cloud, and visualize your schema. Database management UI [#database-management-ui] With its built-in database management interface, [the Prisma VS Code extension](/guides/postgres/vscode) lets you easily work with local and remote Prisma Postgres instances from inside your editor. Workflows [#workflows] The UI enables the following workflows: * Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) * View, create and delete Prisma Postgres instances (local & remote) * "Push to cloud": Easily deploy a local Prisma Postgres instance * View and edit data via an embedded Prisma Studio * Visualize your database schema Usage [#usage] To manage Prisma Postgres instances via the UI in the Prisma VS Code extension: 1. Ensure you have the latest version of the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) installed 2. Find the Prisma logo in the **Activity Bar** 3. Click the **Sign in to get started** button 4. Authenticate with the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=ai) using the sign-in prompt, then select a target [workspace](/console/concepts#workspace) Prisma Studio built-in [#prisma-studio-built-in] Beyond managing your database instances, the Prisma VS Code extension embeds Prisma Studio directly in your editor, making it easy to perform create, update, and delete operations on your database right inside Windsurf. Follow these [easy steps](/studio/integrations/vscode-integration) to get started. Additional resources [#additional-resources] Using Windsurf with Prisma can speed up development while ensuring clean and maintainable database code. To keep learning: * [Windsurf Documentation](https://docs.windsurf.com/windsurf/getting-started) * [Prisma Documentation](/) ## Related pages - [`Agent Skills`](https://www.prisma.io/docs/ai/tools/skills): Give your AI coding agent up-to-date Prisma knowledge with installable skills - [`ChatGPT`](https://www.prisma.io/docs/ai/tools/chatgpt): Learn how to add the Prisma MCP server to ChatGPT to manage your Prisma Postgres databases - [`Codex`](https://www.prisma.io/docs/ai/tools/codex): Learn how to install the Prisma Codex plugin and use Prisma MCP from Codex - [`Cursor`](https://www.prisma.io/docs/ai/tools/cursor): Learn tips and best practices for using Prisma ORM with the Cursor AI code editor - [`GitHub Copilot`](https://www.prisma.io/docs/ai/tools/github-copilot): Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips # Linktree Clone SaaS (/docs/ai/tutorials/linktree-clone) Location: AI > Tutorials > Linktree Clone SaaS Introduction [#introduction] In this comprehensive vibe coding tutorial, you'll build a complete **Linktree clone SaaS** application from scratch using AI assistance. This guide teaches you how to leverage AI tools to rapidly develop a full-stack application with: * **[Next.js](https://nextjs.org/)** — React framework for production * **[Prisma ORM](https://www.prisma.io/orm)** — Type-safe database access * **[Prisma Postgres](https://www.prisma.io/postgres)** — Serverless PostgreSQL database * **[Clerk](https://clerk.com/)** — Authentication and user management By the end of this tutorial, you'll have a working SaaS application where users can sign up, create their profile, and manage their personal link page — all built with AI-assisted development. > [!NOTE] > What is Vibe Coding? > > Vibe coding is a development approach where you collaborate with AI assistants to build applications. You describe what you want to build, and the AI helps generate the code while you guide the direction and make architectural decisions. Video tutorial [#video-tutorial] Watch this step-by-step walkthrough of the entire build process: [Watch video](https://www.youtube.com/watch?v=R3GJ1eo943k) Prerequisites [#prerequisites] Before starting this tutorial, make sure you have: * [Node.js 20+](https://nodejs.org) installed * A [Clerk account](https://clerk.com) (free tier works) * An AI coding assistant ([Cursor](https://cursor.com), [Windsurf](https://windsurf.com), [GitHub Copilot](https://github.com/features/copilot), etc.) * Basic familiarity with React and TypeScript > [!NOTE] > Recommended AI Models > > For best results, we recommend using the latest AI models such as (minimum) Claude Sonnet 4, Gemini 2.5 Pro, or GPT-4o. These models provide better code generation accuracy and understand complex architectural patterns. 1. Set Up Your Project [#1-set-up-your-project] Let's start by creating a new Next.js application: #### npm ```bash npx create-next-app@latest app-name ``` #### pnpm ```bash pnpm dlx create-next-app@latest app-name ``` #### yarn ```bash yarn dlx create-next-app@latest app-name ``` #### bun ```bash bunx --bun create-next-app@latest app-name ``` Once the setup is complete, you'll need to add **Prisma** and **Prisma Postgres** to your project. We've prepared a detailed prompt that handles the complete setup for you. 👉 **Find the setup prompt here:** [Next.js + Prisma Prompt](/ai/prompts/nextjs) **How to use it:** 1. Create a new file called `prompt.md` at the root of your project 2. Copy and paste the prompt content into this file 3. Ask your AI assistant to follow the instructions in this file The AI will set up Prisma ORM, create your database connection, and configure everything automatically. Quick Check [#quick-check] Let's verify everything is working correctly: 1. Start your development server: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` 2. Open Prisma Studio to view your seed data: #### npm ```bash npm run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### bun ```bash bun run db:studio ``` If both commands run without errors and you can see sample data in Prisma Studio, you're ready to continue! > [!NOTE] > Good Practice: Commit Early and Often > > Throughout this tutorial, we'll commit our changes regularly. This makes it easy to track progress and roll back if something goes wrong. > > Start by linking your project to GitHub: > > ```bash > git init > git add . > git commit -m "Initial setup: Next.js app with Prisma" > ``` 2. Set Up Authentication with Clerk [#2-set-up-authentication-with-clerk] Now let's add user authentication using [Clerk](https://clerk.com/), which provides a complete authentication solution out of the box. **Steps to follow:** 1. Go to [Clerk](https://clerk.com/) and create an account (if you don't have one) 2. Create a new application in your Clerk dashboard 3. Follow Clerk's official quickstart guide to integrate it with your Next.js app: 👉 **Clerk Next.js Quickstart:** [clerk.com/docs/nextjs/getting-started/quickstart](https://clerk.com/docs/nextjs/getting-started/quickstart) The guide will walk you through installing the SDK, adding environment variables, and wrapping your app with the `ClerkProvider`. Once complete, commit your changes: ```bash git add . git commit -m "Add Clerk authentication setup" ``` 3. Update Your Database Schema [#3-update-your-database-schema] Since we're building a Linktree clone, we need to update the database schema to support our specific data model. This includes: * A `User` model with a unique `username` (for public profile URLs like `/username`) * A `Link` model to store each user's links Replace the contents of your `prisma/schema.prisma` file with the following: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../app/generated/prisma" } datasource db { provider = "postgresql" } // Example User model for testing model User { id Int @id @default(autoincrement()) email String @unique username String @unique // Important for the public profile URL clerkId String @unique // Links to Clerk Auth name String? links Link[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Link { id Int @id @default(autoincrement()) title String url String userId Int user User @relation(fields: [userId], references: [id]) createdAt DateTime @default(now()) } ``` Since we're changing the schema structure, we need to reset the database. The existing seed data was just for testing purposes, so it's safe to drop and recreate: #### npm ```bash npx prisma db push --force-reset ``` #### pnpm ```bash pnpm dlx prisma db push --force-reset ``` #### yarn ```bash yarn dlx prisma db push --force-reset ``` #### bun ```bash bunx --bun prisma db push --force-reset ``` This command: * **Drops** the existing database tables * **Creates** new tables based on your updated schema > [!WARNING] > Use with Caution > > The `--force-reset` flag deletes all existing data. This is fine during prototyping, but never use it on a production database! Once your schema is stable, switch to `prisma migrate dev` for proper migration tracking. Quick Check [#quick-check-1] Open Prisma Studio to verify the new schema is applied: #### npm ```bash npm run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### bun ```bash bun run db:studio ``` You should see the updated `User` and `Link` tables (they'll be empty, which is expected). **Commit your changes:** ```bash git add . git commit -m "Update schema for Linktree clone" ``` 4. Connect Clerk Users to Your Database [#4-connect-clerk-users-to-your-database] Here's the challenge: when a user signs in with Clerk, they exist in Clerk's system but **not** in your database. We need to bridge this gap. Our approach: create a "Claim Username" flow where users pick their unique username (e.g., `yourapp.com/johndoe`) after signing in for the first time. > [!NOTE] > Use ASK Mode First > > When working with AI assistants, we recommend using **ASK mode** by default to review suggested changes before applying them. Only switch to AGENT mode once you're comfortable with the proposed code. The Prompt [#the-prompt] Copy and paste the following prompt into your AI assistant: ```markdown Connect Clerk authentication to your Prisma database with a "Claim Username" flow. **Goal:** When a user signs in via Clerk, they don't automatically exist in YOUR database. Create a flow where: 1. Logged out → Show landing page with "Sign In" button 2. Logged in but no DB profile → Show "Claim Username" form 3. Has DB profile → Show dashboard **User Model (already in schema):** model User { id Int @id @default(autoincrement()) email String @unique username String @unique clerkId String @unique name String? links Link[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } **Files to create/update:** 1. `app/actions.ts` - Server Action with `claimUsername(formData)` 2. `app/page.tsx` - Three-state UI (logged out / claim username / dashboard) 3. `app/api/users/route.ts` - Update POST to accept `clerkId`, `email`, `username`, `name` **Requirements:** - Use `'use server'` directive in `app/actions.ts` - Use `currentUser()` from `@clerk/nextjs/server` to get auth user - Store `clerkId`, `email`, `username`, and `name` in User model - Use `redirect("/")` after successful profile creation - Handle username uniqueness (Prisma will throw if duplicate) **Pattern:** 1. Server Action receives FormData, validates username (min 3 chars, alphanumeric + underscore) 2. Creates User in Prisma with Clerk's `user.id` as `clerkId` 3. Page.tsx checks: `currentUser()` → then `prisma.user.findUnique({ where: { clerkId } })` 4. Render different UI based on auth state and DB state **Keep it simple:** - No middleware file needed - No webhook sync (user creates profile manually) - Basic validation (username length >= 3) - Errors just throw (no fancy error UI for MVP) ``` After the AI generates the code, you may see TypeScript errors. This is because the Prisma Client needs to be regenerated to reflect the schema changes: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` Quick Check [#quick-check-2] Test the complete flow: 1. Stop your dev server and restart it 2. Open your app in the browser 3. Sign up as a new user through Clerk 4. You should see the "Claim Username" form 5. Enter a username and submit 6. Verify the user appears in Prisma Studio (`npm run db:studio`) If everything works, commit your changes! 5. Upgrade the UI Design [#5-upgrade-the-ui-design] Let's give our app a more polished, friendly look inspired by platforms like Buy Me a Coffee. 👉 [Visit Buy Me a Coffee for design inspiration](https://buymeacoffee.com/) Copy and paste this prompt to your AI assistant: ```markdown Design a minimal, friendly UI inspired by Buy Me a Coffee. **Theme:** - Force light mode only (no dark mode switching) - Clean white background (#FFFFFF) - Black text (#000000) for headings - Gray (#6B7280) for secondary text - Bright yellow (#FFDD00) for CTA buttons - Light gray (#F7F7F7) for cards/sections - Subtle borders (#E5E5E5) **Typography & Spacing:** - Large, bold headlines (text-5xl or bigger) - Generous whitespace and padding - Rounded corners everywhere (rounded-full for buttons, rounded-xl for cards) **Buttons:** - Primary: Yellow background, black text, rounded-full, font-semibold - Secondary: White background, border, rounded-full **Overall feel:** - Friendly, approachable, not corporate - Minimal — only essential elements - Mobile-first with good touch targets (py-4, px-8 on buttons) - One unified canvas — background applies to the entire page (body), with white cards floating on top. No separate section backgrounds. Use Tailwind CSS. Keep it simple. ``` Quick Check [#quick-check-3] After the AI applies the changes: 1. Refresh your app and browse through all pages 2. Verify the design has updated but **no functionality has changed** 3. Test the sign-in flow and username claim process Once verified, commit the changes: ```bash git add . git commit -m "Update UI design" ``` 6. Build Link Management (Add & Delete) [#6-build-link-management-add--delete] Now let's add the core functionality: managing links! Users should be able to add new links and delete existing ones from their dashboard. Copy and paste this prompt: ```markdown Build a simple dashboard for managing links using Next.js App Router and Server Actions. **Requirements:** - Server Component page that fetches user data from database - "Add Link" form with Title and URL inputs - List of existing links with Delete button - Use Server Actions (no API routes) for create/delete operations - Use `revalidatePath("/")` after mutations to refresh the page **Pattern:** 1. Create server actions in `actions.ts` with `'use server'` directive 2. Pass actions directly to form `action` prop 3. Keep page.tsx as a Server Component (no 'use client') 4. Use hidden inputs for IDs (e.g., ``) **Keep it simple:** - No loading states - No client components - No confirmation dialogs - Just forms + server actions + revalidation This is the MVP pattern for CRUD with Next.js App Router. ``` Quick Check [#quick-check-4] Test the link management: 1. Add a new link with a title and URL 2. Verify it appears in your dashboard 3. Delete the link 4. Verify it's removed Both operations should work instantly without page navigation. 7. Create Public Profile Pages [#7-create-public-profile-pages] This is the heart of a Linktree clone: public profile pages that anyone can visit at `/username`. Copy and paste this prompt: ```markdown Build a public profile page at /[username] using Next.js App Router dynamic routes. **Requirements:** - Create `app/[username]/page.tsx` as a Server Component - Fetch user + links from database by username (from URL params) - Return 404 if user not found (use `notFound()` from next/navigation) - Display: avatar (first letter), username, name, and list of links - Links open in new tab with `target="_blank"` - Add a small "Create your own" link at the bottom **Pattern:** 1. Get params: `const { username } = await params` 2. Query database with `findUnique({ where: { username } })` 3. If no user: call `notFound()` 4. Render profile with links as clickable buttons **Keep it simple:** - No auth required (it's a public page) - Pure Server Component (no 'use client') - Basic styling with hover effects This is the core "Linktree" feature — anyone can visit /username to see the links. ``` Quick Check [#quick-check-5] Test your public profile: 1. Navigate to `localhost:3000/your-username` (replace with your actual username) 2. Verify your profile and links display correctly 3. Click a link and confirm it opens in a new tab 8. Add a "Copy Link" Button [#8-add-a-copy-link-button] Make it easy for users to share their profile URL with a one-click copy button. Copy and paste this prompt: ```markdown **Requirements:** - Create a Client Component (`'use client'`) for the button - Use `navigator.clipboard.writeText(url)` to copy - Show "Copied!" feedback for 2 seconds after clicking - Use `useState` to toggle the button text **Pattern:** 1. Create `app/components/copy-button.tsx` with 'use client' 2. Accept `url` as a prop 3. On click: copy to clipboard, set `copied` to true 4. Use `setTimeout` to reset after 2 seconds 5. Import and use in your Server Component page **Keep it simple:** - One small client component - No toast libraries - Just inline text feedback ("Copy link" → "Copied!") ``` Quick Check [#quick-check-6] 1. Find the "Copy link" button on your dashboard 2. Click it and verify it shows "Copied!" 3. Paste somewhere to confirm the URL was copied correctly 9. Create a Custom 404 Page [#9-create-a-custom-404-page] When someone visits a non-existent username, they should see a friendly error page instead of a generic 404. Copy and paste this prompt: ```markdown Create a custom 404 page for Next.js App Router. **Requirements:** - Create `app/not-found.tsx` (Server Component) - Display: 404 heading, friendly message, "Go home" button - Match your app's design (colors, fonts, spacing) **Pattern:** - Next.js automatically uses `not-found.tsx` when `notFound()` is called - Or when a route doesn't exist - No configuration needed — just create the file **Keep it simple:** - Static page, no data fetching - One heading, one message, one link - Same styling as rest of the app ``` Quick Check [#quick-check-7] Test the 404 page by visiting a random URL like `/this-user-does-not-exist`. You should see your custom 404 page with a link back to the homepage. 10. Add a Custom Background [#10-add-a-custom-background] Let's make the app more visually distinctive with a custom background pattern. **First**, either: * Download a background SVG pattern you like, or * Create your own using tools like [SVG Backgrounds](https://www.svgbackgrounds.com/) or [Hero Patterns](https://heropatterns.com/) **Then**, save it as `background.svg` in your `public/` folder. Copy and paste this prompt: ````markdown Add a custom SVG background to my app. **Requirements:** - The svg file is in the `public/` folder (e.g., `public/background.svg`) - Apply it as a fixed, full-cover background on the body **Pattern:** In `globals.css`, update the body: ```css body { background: var(--background) url("/background.svg") center/cover no-repeat fixed; min-height: 100vh; } ``` **Key properties:** - `center/cover` — centers and scales to fill - `no-repeat` — prevents tiling - `fixed` — background stays in place when scrolling Files in `public/` are served at the root URL, so `/background.svg` works. ```` Quick Check [#quick-check-8] 1. Refresh your app 2. Verify the background appears on **all pages** (homepage, dashboard, profile pages, 404) 3. If the background doesn't appear everywhere, ask your AI to fix it Commit your changes once it's working correctly. 11. Add Glassmorphism Card Containers [#11-add-glassmorphism-card-containers] Create visual depth by adding semi-transparent card containers that "float" over the background. Copy and paste this prompt: ````markdown Add a reusable card container class to create visual separation from the background. **Requirements:** - Create a `.card` class in `globals.css` - Apply glassmorphism: semi-transparent white + blur - Use on all main content areas (landing, forms, dashboard, profile pages) **Pattern:** In `globals.css`, add: ```css .card { background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(10px); border-radius: 1.5rem; padding: 2rem; box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06); } ``` **Usage:** Wrap content sections with `
...
` For public profile pages (/[username]): Wrap the entire profile (avatar, name, username, and links list) in a single .card container This creates a Linktree-style floating card effect Footer/attribution links stay outside the card Hero section: Add a soft radial glow behind the content (large blurred white circle, blur-3xl, 50% opacity) No visible container edges — just organic, fading brightness Content floats freely over the glow **Result:** - Content "lifts" off the background - Subtle blur creates depth - Consistent UI across all pages ```` 12. Display Clerk Profile Images [#12-display-clerk-profile-images] If users sign in with Google or another OAuth provider, Clerk stores their profile photo. Let's display it on public profiles! Copy and paste this prompt: ````markdown On the public profile page (`/[username]`), display the user's Clerk profile image (Google photo, etc.) instead of the initial letter avatar. **Pattern:** ```typescript // Fetch Clerk user to get profile image const client = await clerkClient(); const clerkUser = await client.users.getUser(user.clerkId); ``` **Display:** - Use a plain `` tag (not Next.js Image component) - If `clerkUser.imageUrl` exists, show the image - Otherwise fallback to the yellow initial avatar **Keep it simple:** - No try/catch — let errors bubble up - No next.config changes needed - No database schema changes needed ```` Quick Check [#quick-check-9] Visit your public profile page and verify your profile image (from Google, GitHub, etc.) is displayed instead of the initial letter avatar. 13. Add Icons with Lucide [#13-add-icons-with-lucide] Small icons can significantly improve UI clarity. Let's add some using Lucide React. Copy and paste this prompt: ```markdown Add Lucide React icons to improve the UI. First install: npm install lucide-react Add icons to these elements: - View button: ExternalLink icon - Delete button: Trash2 icon (replace text with icon) - Empty links state: Link icon Import icons from 'lucide-react' and use with size prop (e.g., size={18}). Keep buttons minimal — only add icons where they improve clarity. ``` Quick Check [#quick-check-10] Browse through your app and verify the icons appear on: * The view/external link buttons * The delete buttons * The empty state when no links exist 14. Deploy to Vercel [#14-deploy-to-vercel] Time to ship! Let's deploy your app to Vercel. > [!WARNING] > Important Steps > > Follow these steps carefully to avoid deployment errors. Step 1: Configure Prisma for Production [#step-1-configure-prisma-for-production] Add a `postinstall` script to ensure Prisma Client is generated during deployment. Add this to your `package.json` scripts section: ```json title="package.json" { "scripts": { "postinstall": "prisma generate" } } ``` 📖 **Reference:** [Deploy to Vercel - Build Configuration](/orm/prisma-client/deployment/serverless/deploy-to-vercel#build-configuration) Step 2: Clean Up Development Files [#step-2-clean-up-development-files] Delete the `scripts/` folder if it exists. This folder was auto-generated during initial setup for seed data, you don't need it in production. Step 3: Deploy to Vercel [#step-3-deploy-to-vercel] 1. Push your code to GitHub (if you haven't already) 2. Go to [vercel.com](https://vercel.com) and import your repository 3. **Important:** Add all your environment variables in Vercel's dashboard: * `DATABASE_URL` * `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` * `CLERK_SECRET_KEY` Step 4: Update the App URL [#step-4-update-the-app-url] After your first deployment: 1. Copy your production URL from Vercel (e.g., `https://your-app.vercel.app`) 2. Add a new environment variable in Vercel: ```text NEXT_PUBLIC_APP_URL=https://your-app.vercel.app ``` 3. Redeploy to apply the change > [!WARNING] > Don't Forget This Step > > If you skip setting `NEXT_PUBLIC_APP_URL`, features like the "Copy Link" button will copy `localhost` URLs instead of your production URL. Final Check [#final-check] Test your deployed app thoroughly: * [ ] Sign up flow works * [ ] Username claiming works * [ ] Adding/deleting links works * [ ] Public profile pages load correctly * [ ] Copy link copies the correct production URL * [ ] 404 page displays for non-existent usernames **Congratulations! Your Linktree clone is live! 🎉** Resources [#resources] * [Prisma Documentation](/orm) * [Next.js Documentation](https://nextjs.org/docs) * [Clerk Documentation](https://clerk.com/docs) * [Tailwind CSS Documentation](https://tailwindcss.com/docs) ## Related pages - [`Build a Tweet SaaS with Next.js, Prisma Postgres, and Ollama`](https://www.prisma.io/docs/ai/tutorials/typefully-clone): A complete vibe coding tutorial: build a tweet polishing app from scratch using Next.js, Prisma ORM, Prisma Postgres, UploadThing, and a local LLM with Ollama. # Build a Tweet SaaS with Next.js, Prisma Postgres, and Ollama (/docs/ai/tutorials/typefully-clone) Location: AI > Tutorials > Build a Tweet SaaS with Next.js, Prisma Postgres, and Ollama Introduction [#introduction] In this comprehensive vibe coding tutorial, you'll build **TweetSmith**, a tweet polishing application that transforms your rough draft tweets into engaging, well-formatted content using AI. The twist? Everything runs locally on your machine with no API keys required for the AI. You'll learn how to leverage AI tools to rapidly develop a full-stack application with: * **[Next.js](https://nextjs.org/)** — React framework for production * **[Prisma ORM](https://www.prisma.io/orm)** — Type-safe database access * **[Prisma Postgres](https://www.prisma.io/postgres)** — Serverless PostgreSQL database * **[Ollama](https://ollama.com/)** — Run LLMs locally on your machine * **[UploadThing](https://uploadthing.com/)** — Easy file uploads for tweet images * **[Lucide React](https://lucide.dev/)** — Beautiful icon library By the end of this tutorial, you'll have a working application where users can paste draft tweets, transform them with AI, save their favorites, and even attach images, all built with AI-assisted development. > [!NOTE] > What is Vibe Coding? > > Vibe coding is a development approach where you collaborate with AI assistants to build applications. You describe what you want to build, and the AI helps generate the code while you guide the direction and make architectural decisions. Video tutorial [#video-tutorial] Watch this step-by-step walkthrough of the entire build process: [Watch video](https://www.youtube.com/watch?v=QIuR2_pKFXA) Prerequisites [#prerequisites] Before starting this tutorial, make sure you have: * [Node.js 20+](https://nodejs.org) installed * [Ollama](https://ollama.com/) installed on your machine * An AI coding assistant ([Cursor](https://cursor.com), [Windsurf](https://windsurf.com), [GitHub Copilot](https://github.com/features/copilot), etc.) * Basic familiarity with React and TypeScript > [!NOTE] > Recommended AI Models > > For best results with vibe coding, we recommend using at least Claude Sonnet 4, Gemini 2.5 Pro, or GPT-4o. These models provide better code generation accuracy and understand complex architectural patterns. 1. Set up your local LLM [#1-set-up-your-local-llm] Before we write any code, let's set up Ollama so your local AI is ready to transform tweets. This runs entirely on your machine — no API keys, no usage limits, no internet required. Pull the Model [#pull-the-model] Open your terminal and download the Gemma 3 model: ```bash ollama pull gemma3:4b ``` You should see a progress indicator like "pulling manifest…95%". This downloads approximately 3.3GB. Verify It's Working [#verify-its-working] Test that the model responds: ```bash ollama run gemma3:4b ``` Type something and confirm it responds. Press `Ctrl+C` to exit. You can also verify the API is accessible: ```bash curl http://localhost:11434/api/tags ``` You should see JSON output showing `gemma3:4b` is installed: ```json { "models": [{ "name": "gemma3:4b", "family": "gemma3", "parameter_size": "4.3B", "quantization_level": "Q4_K_M" }] } ``` > [!NOTE] > Why Gemma 3 4B? > > This model is the sweet spot for local development: > > * **4.3B parameters** — Smart enough for tweet formatting > * **Q4\_K\_M quantization** — Memory-efficient (\~3.3GB) > * **Runs great on M-series Macs** with 16GB RAM > * **No API keys or costs** — Completely free and private Your local LLM is ready! Ollama runs as a background service, so you don't need to keep a terminal open. 2. Create Your Next.js Project [#2-create-your-nextjs-project] Let's create a fresh Next.js application: #### npm ```bash npx create-next-app@latest tweetsmith ``` #### pnpm ```bash pnpm dlx create-next-app@latest tweetsmith ``` #### yarn ```bash yarn dlx create-next-app@latest tweetsmith ``` #### bun ```bash bunx --bun create-next-app@latest tweetsmith ``` When prompted, select: * TypeScript: **Yes** * ESLint: **Yes** * Tailwind CSS: **Yes** * `src/` directory: **No** * App Router: **Yes** * Turbopack: **Yes** (optional) * Import alias: **@/**\* (default) Navigate into your project: ```bash cd tweetsmith ``` Quick Check [#quick-check] Start your development server to verify everything works: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` Open `http://localhost:3000` — you should see the default Next.js page. > [!NOTE] > Good Practice: Commit Early and Often > > Throughout this tutorial, we'll commit our changes regularly. This makes it easy to track progress and roll back if something goes wrong. > > ```bash > git init > git add . > git commit -m "Initial setup: Next.js app" > ``` 3. Build the TweetSmith UI [#3-build-the-tweetsmith-ui] Now let's create a minimalist, dark-themed UI inspired by tools like [Typefully](https://typefully.com/). Copy and paste this prompt to your AI assistant: ```markdown I have a fresh Next.js 15 project with Tailwind CSS already set up. I need you to create a minimalist single-page UI for a TweetSmith app called "TweetSmith". **Design requirements:** - Dark theme only (no light/dark toggle) - Typefully-inspired aesthetic: sophisticated, clean, minimal - Color palette: - Background: #141414 (soft charcoal) - Card/inputs: #1c1c1c - Borders: #2a2a2a - Muted text: #888888 - Foreground/text: #fafafa - Typography: Geist font (already configured), small refined sizes - Labels should be uppercase with letter-spacing **What to create:** 1. Update `app/globals.css` with the dark color palette and CSS variables 2. Update `app/layout.tsx` with proper metadata (title: "TweetSmith") and force the dark background 3. Create `app/components/TweetTransformer.tsx` - a client component with: - A textarea input for draft tweets - A character counter (X / 280) - A "Transform" button (disabled when empty) - An output section for the result (only visible when there's a result) - Loading state ready for future API integration - The handleTransform function should just console.log for now 4. Update `app/page.tsx` with: - Simple header with app name and tagline - The TweetTransformer component - Subtle footer saying "powered by ollama" Keep it minimal, no extra features, just clean functional UI. Maximum width should be max-w-md for a focused feel. ``` Quick Check [#quick-check-1] 1. Restart your dev server if needed 2. You should see a dark-themed page with a textarea and transform button 3. Type something and verify the character counter updates 4. The button should be disabled when the textarea is empty Once it looks good, commit your changes: ```bash git add . git commit -m "Add TweetSmith UI" ``` 4. Connect to Your Local LLM [#4-connect-to-your-local-llm] Now let's wire up the UI to your local Ollama instance. We'll create a helper file and an API route. Create the Ollama Helper [#create-the-ollama-helper] Copy and paste this prompt: ```markdown Create `app/lib/ollama.ts` - a helper file to communicate with a local Ollama LLM. Requirements: - Ollama runs at http://localhost:11434 - Model name: "gemma3:4b" - Use the /api/generate endpoint - Create TypeScript types for OllamaRequest and OllamaResponse - Export a function `generateWithOllama(prompt: string)` that: - Sends a POST request with the prompt - Uses stream: false (no streaming, keep it simple) - Returns the response text as a string - Throws an error if the request fails Keep it minimal with clear comments explaining what each part does. ``` Create the Transform API Route [#create-the-transform-api-route] Copy and paste this prompt: ```markdown Create `app/api/transform/route.ts` - a Next.js API route that transforms tweets. Requirements: - POST endpoint that accepts { draft: string } in the body - Validate that draft exists and is a string (return 400 if invalid) - Use the generateWithOllama function from "@/app/lib/ollama" - Build a prompt that tells the LLM to: - Act as a tweet formatter - Make the draft cleaner, more engaging, well-formatted - Keep it under 280 characters - Return only the improved tweet, nothing else - Return { transformed: string } on success - Return { error: string } with status 500 if Ollama fails - Add a helpful error message asking if Ollama is running Use NextRequest and NextResponse from next/server. ``` Connect the Frontend [#connect-the-frontend] Copy and paste this prompt: ```markdown Update the TweetTransformer component to call the transform API: 1. Add an "error" state (useState) to handle errors 2. Update handleTransform to: - Reset error and result states first - Set loading to true - Call POST /api/transform with { draft: draftTweet } - On success: set the transformed tweet from response - On error: set error message from the catch - Use finally to always set loading to false 3. Display error message in red below the button when there's an error Keep the existing UI structure, just wire up the real API call. ``` Quick Check [#quick-check-2] 1. Make sure Ollama is running in the background 2. Type a draft tweet like "just shipped a new feature, its pretty cool i think" 3. Click Transform 4. You should see a polished version appear after a few seconds If you get an error, check that: * Ollama is running (`curl http://localhost:11434/api/tags`) * The model name matches (`gemma3:4b`) 5. Add Temperature for Variety [#5-add-temperature-for-variety] You might notice the LLM returns the exact same output every time. That's because LLMs are deterministic by default — given the same input, they produce the same output. By adding a "temperature" parameter, we introduce controlled randomness that makes each response slightly different while keeping it coherent. ```markdown Update the ollama.ts file to add temperature for response variety: 1. Add an optional "options" field to OllamaRequest type with temperature?: number 2. In the request body, add: options: { temperature: 0.7 } ``` > [!NOTE] > What is Temperature? > > Temperature controls randomness in LLM responses. A value of `0` means deterministic (same output every time), while `1` means maximum creativity. We use `0.7` as the sweet spot — creative enough to give variety, but coherent enough to stay on topic. Now each transform will give slightly different results! ```bash git add . git commit -m "Connect to Ollama LLM for tweet transformation" ``` 6. Add Filter Options [#6-add-filter-options] Right now, every tweet gets the same treatment. But users have different needs — some want short, punchy tweets while others need the full 280 characters. Some love emojis, others prefer a cleaner look. Let's give users control over the output with filters for character limits and emoji usage. We'll create a collapsible panel with intuitive controls. First, install Lucide for icons: #### npm ```bash npm install lucide-react ``` #### pnpm ```bash pnpm add lucide-react ``` #### yarn ```bash yarn add lucide-react ``` #### bun ```bash bun add lucide-react ``` Then copy and paste this prompt: ```markdown Create `app/components/FilterOptions.tsx` with filters for tweet generation. Requirements: - Export a `Filters` type with: maxChars (number) and emojiMode ("none" | "few" | "many") - Export two components: 1. `FilterButton` - a toggle button showing current filter values (e.g., "Filters 280 · few") 2. `FilterPanel` - the expanded controls panel FilterButton props: isOpen, onToggle, filters FilterPanel props: filters, onFiltersChange FilterPanel should include: - A range slider for maxChars (100-280, step 20) - Three icon buttons for emoji mode using Lucide icons: - Ban icon for "none" - Smile icon for "few" - SmilePlus icon for "many" - Display inline with dividers between sections - Compact design with small buttons (h-7 w-7) Use SlidersHorizontal and ChevronDown from lucide-react for the button. Style: dark theme, rounded-lg, border-border, bg-card. ``` 7. Add Context Settings [#7-add-context-settings] Filters control the format, but what about the *voice*? A tech founder tweets differently than a lifestyle blogger. By letting users define their personal context — their tone, style, and audience — the AI can generate tweets that actually sound like them. We'll add a context panel where users can describe their voice, and this gets saved to localStorage so it persists across sessions. ```markdown Create `app/components/ContextSettings.tsx` with context management. Export two components: 1. `ContextButton` - toggle button with User icon from lucide-react - Props: isOpen, onToggle, hasContext (boolean) - Show a small dot indicator when context is set 2. `ContextPanel` - just the textarea - Props: onContextChange - Load/save to localStorage with key "TweetSmith-context" Use User and ChevronDown icons from lucide-react. Keep the textarea at 2 rows, placeholder about style/tone. ``` Integrate the Panels [#integrate-the-panels] ```markdown Update `app/components/TweetTransformer.tsx` to use the new component structure. Changes: 1. Import ContextButton, ContextPanel from ContextSettings 2. Import FilterButton, FilterPanel, Filters from FilterOptions 3. Add state for which panel is open: type OpenPanel = "none" | "context" | "filters" 4. Track hasContext state (check localStorage on mount) Layout structure: - Settings row: flex container with gap-2 containing both buttons INLINE - Below the row: conditionally render either ContextPanel or FilterPanel (only one at a time) - Clicking one panel closes the other This keeps both buttons always on the same line, with expanded content appearing below. Default filters: maxChars 280, emojiMode "few" ``` Update the API to Use Filters [#update-the-api-to-use-filters] ```markdown Update `app/api/transform/route.ts` to use the filter values. Key changes: 1. Extract filter values directly: maxChars and emojiMode with defaults (280, "few") 2. Build emoji rule as a simple string based on mode 3. Put STRICT LIMITS at the TOP of the prompt (most important): - "Maximum {maxChars} characters (THIS IS MANDATORY)" - Emoji rule - "No hashtags" 4. Add context as "Author style:" if provided 5. Keep GUIDELINES brief: lead with value, sound human, be engaging 6. End with: 'Respond with ONLY the rewritten tweet. No quotes, no explanation.' Remove any complex buildFilterRules function - inline everything for clarity. The prompt should be shorter and more direct for better local LLM compliance. ``` Quick Check [#quick-check-3] 1. Open the Filters panel and adjust the character limit 2. Toggle between emoji modes 3. Add some context like "Tech founder, casual tone" 4. Transform a tweet and verify the output respects your settings ```bash git add . git commit -m "Add filter options and context settings" ``` 8. Create a Tweet Preview Card [#8-create-a-tweet-preview-card] Plain text output works, but it doesn't feel *real*. When users see their transformed tweet styled like an actual Twitter/X post — complete with profile picture, verified badge, and proper formatting — it becomes much easier to visualize and share. Let's create a tweet preview card that mimics the real thing, with loading skeletons for a polished feel: ```markdown Create `app/components/TweetPreview.tsx` - a tweet-like preview card with 3 states. Props: content (string | null), isLoading (boolean) Structure: 1. Header with profile image, name, verified badge, and handle 2. Content area (changes based on state) 3. Footer with character count or placeholder Three states: 1. EMPTY (no content, not loading): - Show placeholder text styled like a tweet but in text-muted - Example: "Follow us on X to stay updated on all the latest features and releases from Prisma! 🚀\n\nYour polished tweet will appear here ✨" - Footer shows "prisma.io" 2. LOADING (isLoading true): - Show 3 animated skeleton bars with animate-pulse - Different widths: 90%, 75%, 60% - Footer skeleton bar 3. CONTENT (has content): - Show the actual tweet text - Copy button in header (using Copy/Check icons from lucide-react) - Footer shows "X / 280 characters" Use Image from next/image for the profile picture. Add verified badge as inline SVG (Twitter blue checkmark). ``` Add a Logo [#add-a-logo] Add a logo image (like `icon-logo.png`) to your `public/` folder, then: ```markdown Update `app/page.tsx` to use a logo image instead of text for the header. Changes: 1. Import Image from "next/image" 2. Replace the h1 text with an Image component: - src="/icon-logo.png" (or your logo file) - width={80} height={80} - Add className="mb-3" for spacing 3. Keep the tagline text below: "polish your tweets with AI" 4. Use flex flex-col items-center on the header The header should now show: Logo image centered, tagline below. ``` ```bash git add . git commit -m "Add tweet preview card and logo" ``` 9. Add Prisma Postgres [#9-add-prisma-postgres] Now let's add a database to save favorite tweets! We'll use Prisma ORM with Prisma Postgres. Install Dependencies [#install-dependencies] #### npm ```bash npm install prisma tsx --save-dev npm install @prisma/adapter-pg @prisma/client dotenv ``` #### pnpm ```bash pnpm add prisma tsx --save-dev pnpm add @prisma/adapter-pg @prisma/client dotenv ``` #### yarn ```bash yarn add prisma tsx --dev yarn add @prisma/adapter-pg @prisma/client dotenv ``` #### bun ```bash bun add prisma tsx --dev bun add @prisma/adapter-pg @prisma/client dotenv ``` Initialize Prisma [#initialize-prisma] > [!WARNING] > User Action Required > > Run the following commands in your terminal. `prisma init` creates the project files, and `create-db` gives you the `postgres://...` connection string you need for Prisma Postgres. #### npm ```bash npx prisma init --output ../app/generated/prisma npx create-db ``` #### pnpm ```bash pnpm dlx prisma init --output ../app/generated/prisma pnpm dlx create-db ``` #### yarn ```bash yarn dlx prisma init --output ../app/generated/prisma yarn dlx create-db ``` #### bun ```bash bunx --bun prisma init --output ../app/generated/prisma bun x create-db ``` Replace the generated `DATABASE_URL` in `.env` with the `postgres://...` connection string from `npx create-db`. > [!NOTE] > Important: Check Your DATABASE_URL > > Ensure your `.env` file uses a standard PostgreSQL URL format: > > ```bash > DATABASE_URL="postgres://..." > ``` > > If it still shows `prisma+postgres://...`, replace it with the `postgres://...` connection string from `npx create-db`. Update the Schema [#update-the-schema] Replace the contents of `prisma/schema.prisma` with: ```prisma generator client { provider = "prisma-client" output = "../app/generated/prisma" } datasource db { provider = "postgresql" } model SavedTweet { id String @id @default(cuid()) original String // The draft tweet input transformed String // The polished/transformed tweet context String? // Optional user context/style used imageUrl String? // Optional image URL imageAlt String? // Optional alt text for accessibility createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` Create the Prisma Client [#create-the-prisma-client] Create `lib/prisma.ts`: ```typescript import { PrismaClient } from "../app/generated/prisma/client" import { PrismaPg } from "@prisma/adapter-pg" const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }) const globalForPrisma = global as unknown as { prisma: PrismaClient } const prisma = globalForPrisma.prisma || new PrismaClient({ adapter, }) if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma export default prisma ``` Add Database Scripts [#add-database-scripts] Update your `package.json` scripts: ```json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "eslint", "db:test": "tsx scripts/test-database.ts", "db:studio": "prisma studio" } } ``` Create a Test Script [#create-a-test-script] Create `scripts/test-database.ts`: ```typescript import "dotenv/config" import prisma from "../lib/prisma" async function testDatabase() { console.log("🔍 Testing Prisma Postgres connection...\n") try { console.log("✅ Connected to database!") console.log("\n📝 Creating a test saved tweet...") const newTweet = await prisma.savedTweet.create({ data: { original: "just shipped a new feature, its pretty cool i think", transformed: "Just shipped a new feature! 🚀 Pretty excited about this one ✨", context: "Tech founder, casual tone", }, }) console.log("✅ Created saved tweet:", newTweet) console.log("\n📋 Fetching all saved tweets...") const allTweets = await prisma.savedTweet.findMany() console.log(`✅ Found ${allTweets.length} saved tweet(s)`) console.log("\n🎉 All tests passed! Your database is working perfectly.\n") } catch (error) { console.error("❌ Error:", error) process.exit(1) } } testDatabase() ``` Push Schema and Test [#push-schema-and-test] #### npm ```bash npx prisma db push npx prisma generate npm run db:test ``` #### pnpm ```bash pnpm dlx prisma db push pnpm dlx prisma generate pnpm run db:test ``` #### yarn ```bash yarn dlx prisma db push yarn dlx prisma generate yarn db:test ``` #### bun ```bash bunx --bun prisma db push bun x prisma generate bun run db:test ``` You should see success messages. Open Prisma Studio to view your data: #### npm ```bash npm run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### bun ```bash bun run db:studio ``` Create the Tweets API [#create-the-tweets-api] Copy and paste this prompt: ```markdown Create `app/api/tweets/route.ts` with GET, POST, and DELETE handlers. Requirements: - GET: Fetch all saved tweets ordered by createdAt desc - POST: Save a new tweet with { original, transformed, context?, imageUrl?, imageAlt? } - DELETE: Delete a tweet by id (passed as query param ?id=xxx) Use try-catch blocks and return appropriate error responses. Import prisma from "../../../lib/prisma" ``` Quick Check [#quick-check-4] Test the API with curl: ```bash # Save a tweet curl -X POST http://localhost:3000/api/tweets \ -H "Content-Type: application/json" \ -d '{"original":"test draft","transformed":"Test polished! ✨"}' # Get all tweets curl http://localhost:3000/api/tweets ``` ```bash git add . git commit -m "Add Prisma Postgres database" ``` 10. Add Save Functionality [#10-add-save-functionality] Now that we have a database, let's put it to use! Users often want to save their best transformed tweets for later — maybe they're not ready to post yet, or they want to build a collection of polished content. We'll add a save button to the tweet preview card with satisfying visual feedback: ```markdown Add a Save button to save transformed tweets to the database. Requirements: - Add a Save button next to the Copy button in TweetPreview - Use POST /api/tweets with { original, transformed, context } - Pass original (draft) and context from TweetTransformer to TweetPreview UX States: - Default: Bookmark icon with hover scale effect - Saving: Spinning Loader2 icon + "Saving" text - Saved: Green tinted background (emerald-500/10), checkmark icon with zoom animation Important: The "Saved" state must persist until a NEW tweet is generated. Use useRef to track previous content and useEffect to reset saved state only when content changes. Do not use setTimeout to reset the saved state. Match the minimal dark aesthetic of the app (200ms ease-out transitions, subtle hover states). ``` 11. Build the Tweet Library [#11-build-the-tweet-library] Saving tweets is great, but users need a way to access them! Let's build a slide-in library panel where users can browse their saved tweets, copy them for posting, or even load them back as drafts to iterate further. This is where the app starts feeling like a real product — a complete workflow from draft to polish to save to reuse: ```markdown Add a Library feature to browse and reuse saved tweets. Components to create: - LibraryButton.tsx - Fixed top-right button with count badge - LibraryPanel.tsx - Slide-in panel from right (360px, backdrop blur) - SavedTweetCard.tsx - Tweet cards that look like published tweets LibraryButton: - Fixed position top-right (fixed top-6 right-6) - Shows saved tweets count as badge - Toggles panel open/close LibraryPanel: - Slides in from right with 300ms ease-out animation - Backdrop overlay with blur - Header with title, count, and close button - Scrollable list of SavedTweetCard components - Empty state with icon when no tweets saved - Fetches tweets from GET /api/tweets when opened SavedTweetCard: - Looks like a real published tweet (profile image, name, verified badge, handle, date) - Shows transformed tweet content only (not original) - Footer: character count on left, Copy/Delete icons on right (subtle, brighten on hover) - Click anywhere on card → loads transformed text into Draft textarea and closes panel - Delete shows inline confirmation (Cancel/Delete buttons), not a modal Integration: - Add library state to TweetTransformer (isOpen, count) - Fetch count on mount and after saving - Pass onUseAsDraft callback to set draft and clear transformed tweet - Refresh count when panel closes (in case tweets were deleted) Styling: Match minimal dark aesthetic - subtle borders, muted colors, smooth 200ms transitions. ``` Quick Check [#quick-check-5] 1. Save a few transformed tweets 2. Click the Library button in the top-right 3. Verify your saved tweets appear in the panel 4. Click a tweet to load it back into the draft 5. Delete a tweet and verify it disappears ```bash git add . git commit -m "Add tweet library with save/browse/delete" ``` 12. Add Theme Switcher [#12-add-theme-switcher] Dark mode is standard, but why stop there? Let's add personality with multiple dark themes. Users can pick a vibe that matches their style — from purple twilight to warm desert tones to classic newspaper grey. This is a small touch that makes the app feel more personal and polished: ```markdown Add a theme system to my app with 3 dark themes and a minimal theme switcher. THEMES: 1. "Disco" - Purple/violet twilight vibes - Background: #17171c (deep blue-black) - Accent: #a78bfa (soft violet) 2. "Dust" - Desert warmth, amber tones - Background: #1a1816 (warm charcoal) - Accent: #d4a574 (warm amber/sand) 3. "Press" - Old newspaper, pure greys - Background: #262626 (true grey) - Accent: #a3a3a3 (neutral grey) IMPLEMENTATION: - Use CSS custom properties (:root and [data-theme="..."]) for all colors - Add a subtle radial gradient glow at the top of the page using the accent color - Create a ThemeSwitcher component with small colored dots (one per theme) - Place the switcher in the footer for minimal UI impact - Persist theme choice in localStorage - Add smooth transitions when switching themes (0.3s ease) - Prevent transition flash on page load with a "no-transitions" class UX REQUIREMENTS: - Each dot shows the accent color of that theme - Selected theme has a subtle ring + slight scale up - Unselected themes are dimmed (opacity 40%) and brighten on hover - Theme changes should animate smoothly across all UI elements ``` 13. Add Smooth Animated Panels [#13-add-smooth-animated-panels] You might have noticed that the filter and context panels appear/disappear abruptly. Good UX demands smooth transitions — they make the interface feel more responsive and polished. We'll use the CSS Grid height animation trick to create buttery smooth expand/collapse animations without the layout jumps that plague traditional height transitions: ```markdown Add smooth animated collapsible panels that expand/collapse without layout jumps. ANIMATED PANEL COMPONENT: Create a reusable AnimatedPanel component using the CSS Grid trick for height animation: - Use display: grid with gridTemplateRows - Closed state: gridTemplateRows: "0fr" (collapses to 0 height) - Open state: gridTemplateRows: "1fr" (expands to content height) - Wrap children in a div with overflow: hidden - Add opacity fade: 0 when closed, 1 when open - Transition: "grid-template-rows 0.25s cubic-bezier(0.32, 0.72, 0, 1), opacity 0.2s ease" COLLAPSE GAP TRICK: If parent uses gap/space between items, add negative margin when closed to collapse the gap: - marginTop: isOpen ? undefined : "-12px" (adjust based on your gap size) - Animate the margin too for smooth effect PREVENT SCROLLBAR LAYOUT SHIFT: Add to your global CSS on html element: - scrollbar-gutter: stable (reserves space for scrollbar) - overflow-x: hidden (prevents horizontal scroll) This creates buttery smooth expand/collapse without the jarring height jump or scrollbar layout shift. ``` ```bash git add . git commit -m "Add themes and smooth animations" ``` 14. Add Image Uploads [#14-add-image-uploads] Tweets with images get significantly more engagement. Let's give users the ability to attach images to their polished tweets. We'll use UploadThing for simple, reliable file uploads with a smart pattern: preview locally first, only upload when saving. This prevents orphaned files if users change their mind before saving: Install UploadThing [#install-uploadthing] #### npm ```bash npm install uploadthing @uploadthing/react ``` #### pnpm ```bash pnpm add uploadthing @uploadthing/react ``` #### yarn ```bash yarn add uploadthing @uploadthing/react ``` #### bun ```bash bun add uploadthing @uploadthing/react ``` Get Your API Token [#get-your-api-token] 1. Go to [uploadthing.com](https://uploadthing.com) and create an account 2. Create a new app in the dashboard 3. Copy your `UPLOADTHING_TOKEN` and add it to your `.env`: ```bash UPLOADTHING_TOKEN=your_token_here ``` Implement Image Upload [#implement-image-upload] ```markdown Add image upload to tweets using UploadThing. Requirements: 1. Users should be able to attach ONE image to their tweet 2. The image should only be uploaded to UploadThing when clicking "Save" (not when selecting the image) 3. While editing, show a local preview using URL.createObjectURL() - this avoids orphaned uploads if the user changes their mind 4. Show upload progress in the Save button ("Uploading..." → "Saving...") 5. Allow removing the selected image before saving (X button on the image preview) 6. Display saved images in the tweet library/cards Implementation steps: 1. Create UploadThing FileRouter at app/api/uploadthing/core.ts with a "tweetImage" route (4MB max, 1 file) 2. Create the route handler at app/api/uploadthing/route.ts 3. Create typed utilities at app/lib/uploadthing.ts with useUploadThing hook 4. Update TweetPreview component: - Add file state (File object) and preview URL state - Add hidden file input + "Add image" label/button - Show image preview with remove button - In handleSave: if file exists, call startUpload() first, then save tweet with the returned URL 5. Update SavedTweetCard to display imageUrl if present The schema already has imageUrl and imageAlt fields. Key pattern: Store File locally → preview with createObjectURL → upload only on save → save URL to database ``` Quick Check [#quick-check-6] 1. Transform a tweet 2. Click "Add image" and select a photo 3. Verify the preview appears with an X button to remove 4. Click Save and watch the button states: "Uploading..." → "Saving..." → "Saved!" 5. Open the Library and verify the image appears with the saved tweet ```bash git add . git commit -m "Add image upload with UploadThing" ``` Summary [#summary] You've built a complete tweet polishing application with: * ✅ Local AI with Ollama (no API keys!) * ✅ Customizable filters and context * ✅ Beautiful dark themes * ✅ Cloud database with Prisma Postgres * ✅ Image uploads with UploadThing * ✅ Smooth animations and polished UX What's Next? [#whats-next] Here are some ideas to extend your app: * Add user authentication with [Clerk](https://clerk.com) * Add multiple LLM model options * Implement tweet scheduling * Add analytics to track transformations * Create shareable public links Resources [#resources] * [Prisma Documentation](/orm) * [Next.js Documentation](https://nextjs.org/docs) * [Ollama Documentation](https://ollama.com/library) * [UploadThing Documentation](https://docs.uploadthing.com) * [Tailwind CSS Documentation](https://tailwindcss.com/docs) * [Lucide Icons](https://lucide.dev/icons) ## Related pages - [`Linktree Clone SaaS`](https://www.prisma.io/docs/ai/tutorials/linktree-clone): A complete vibe coding tutorial: build a full Linktree clone SaaS application from scratch using Next.js, Prisma ORM, Prisma Postgres, and Clerk authentication with AI assistance # platform (/docs/cli/console) Location: CLI > platform The `prisma platform` command group provides tools for interacting with the Prisma Data Platform. Usage [#usage] ```bash prisma platform [command] [options] ``` Options [#options] | Option | Description | | -------------- | -------------------- | | `-h`, `--help` | Display help message | Subcommands [#subcommands] | Command | Description | | ----------------------------------------------- | ---------------------------------------- | | [`prisma platform status`](/cli/console/status) | Show Prisma Data Platform service status | Examples [#examples] ```bash # Check service status prisma platform status # Output status as JSON prisma platform status --json ``` See also [#see-also] * [Console overview](/console) * [Getting started with Console](/console/getting-started) ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # status (/docs/cli/console/status) Location: CLI > Console > status The `prisma platform status` command shows the current status of Prisma Data Platform services. Usage [#usage] ```bash prisma platform status [options] ``` Options [#options] | Option | Description | | -------------- | ----------------------------------- | | `-h`, `--help` | Display help message | | `--json` | Output raw JSON from the status API | Examples [#examples] Check service status [#check-service-status] #### npm ```bash npx prisma platform status ``` #### pnpm ```bash pnpm dlx prisma platform status ``` #### yarn ```bash yarn dlx prisma platform status ``` #### bun ```bash bunx --bun prisma platform status ``` Output status as JSON [#output-status-as-json] #### npm ```bash npx prisma platform status --json ``` #### pnpm ```bash pnpm dlx prisma platform status --json ``` #### yarn ```bash yarn dlx prisma platform status --json ``` #### bun ```bash bunx --bun prisma platform status --json ``` # execute (/docs/cli/db/execute) Location: CLI > db > execute The `prisma db execute` command applies a SQL script to the database without interacting with the Prisma migrations table. > [!WARNING] > This command is currently not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Usage [#usage] ```bash prisma db execute [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). The script input must be provided using either `--file` or `--stdin`. The whole script is sent as a single command to the database. The output is connector-specific and reports success or failure only—it's not meant for returning data. Prerequisites [#prerequisites] Configure your database connection in `prisma.config.ts`: ```prisma file=schema.prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "sqlite" } ``` ```typescript file=prisma.config.ts import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Options [#options] | Option | Description | | -------------- | ----------------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--file` | Path to a file containing the script to execute | Flags [#flags] | Flag | Description | | --------- | ---------------------------------------------------- | | `--stdin` | Use terminal standard input as the script to execute | Either `--file` or `--stdin` is required. > [!NOTE] > **Prisma v7 breaking change**: The `--schema` and `--url` options have been removed. Configure your database connection in `prisma.config.ts` instead. Examples [#examples] Execute a SQL file [#execute-a-sql-file] #### npm ```bash npx prisma db execute --file ./script.sql ``` #### pnpm ```bash pnpm dlx prisma db execute --file ./script.sql ``` #### yarn ```bash yarn dlx prisma db execute --file ./script.sql ``` #### bun ```bash bunx --bun prisma db execute --file ./script.sql ``` Execute SQL from stdin [#execute-sql-from-stdin] ```bash echo 'TRUNCATE TABLE dev;' | prisma db execute --stdin ``` See also [#see-also] * [Migration troubleshooting in production](/orm/prisma-migrate/workflows/patching-and-hotfixing#fixing-failed-migrations-with-migrate-diff-and-db-execute) ## Related pages - [`pull`](https://www.prisma.io/docs/cli/db/pull): Pull the state from the database to the Prisma schema using introspection - [`push`](https://www.prisma.io/docs/cli/db/push): Push the state from your Prisma schema to your database - [`seed`](https://www.prisma.io/docs/cli/db/seed): Seed your database with test or initial data using custom scripts # db (/docs/cli/db) Location: CLI > db The `prisma db` command group provides tools to manage your database schema and lifecycle during development. Usage [#usage] ```bash prisma db [command] [options] ``` Global options [#global-options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Subcommands [#subcommands] | Command | Description | | -------------------------------------- | ------------------------------------------------------------------------- | | [`prisma db pull`](/cli/db/pull) | Pull the state from the database to the Prisma schema using introspection | | [`prisma db push`](/cli/db/push) | Push the state from Prisma schema to the database during prototyping | | [`prisma db seed`](/cli/db/seed) | Seed your database | | [`prisma db execute`](/cli/db/execute) | Execute native commands to your database | Examples [#examples] ```bash # Pull schema from database prisma db pull # Push schema to database prisma db push # Seed the database prisma db seed # Execute a SQL script prisma db execute --file ./script.sql ``` ## Related pages - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema - [`init`](https://www.prisma.io/docs/cli/init): Set up a new Prisma project in the current directory # pull (/docs/cli/db/pull) Location: CLI > db > pull The `prisma db pull` command connects to your database and adds Prisma models to your Prisma schema that reflect the current database schema. Usage [#usage] ```bash prisma db pull [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). > [!WARNING] > This command will overwrite the current `schema.prisma` file with the new schema. Back up your current schema or commit to version control before running `db pull` if it contains important modifications. > [!NOTE] > Introspection with `db pull` on the [MongoDB connector](/orm/core-concepts/supported-databases/mongodb) samples the data instead of reading a schema. Prerequisites [#prerequisites] Configure your database connection in `prisma.config.ts`: ```prisma file=schema.prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "sqlite" } ``` ```typescript file=prisma.config.ts import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Flags [#flags] | Flag | Description | | -------------- | ---------------------------------------------- | | `-h`, `--help` | Display help message | | `--force` | Ignore current Prisma schema file | | `--print` | Print the introspected Prisma schema to stdout | Options [#options] | Option | Description | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `--url` | Override the datasource URL from the Prisma config file | | `--composite-type-depth` | Depth for introspecting composite types (e.g., MongoDB Embedded Documents). Default `-1` for infinite depth, `0` to disable | | `--schemas` | Specify database schemas to introspect (overrides datasource block) | | `--local-d1` | Generate a Prisma schema from a local Cloudflare D1 database | Examples [#examples] Introspect the database [#introspect-the-database] #### npm ```bash npx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### bun ```bash bunx --bun prisma db pull ``` Output: ```text Introspecting based on datasource defined in schema.prisma … ✔ Introspected 2 models and wrote them into schema.prisma in 38ms Run prisma generate to generate Prisma Client. ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma db pull --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma db pull --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma db pull --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma db pull --schema=./alternative/schema.prisma ``` Print to stdout instead of writing to file [#print-to-stdout-instead-of-writing-to-file] #### npm ```bash npx prisma db pull --print ``` #### pnpm ```bash pnpm dlx prisma db pull --print ``` #### yarn ```bash yarn dlx prisma db pull --print ``` #### bun ```bash bunx --bun prisma db pull --print ``` Force overwrite existing schema [#force-overwrite-existing-schema] Ignore any customizations in the current schema: #### npm ```bash npx prisma db pull --force ``` #### pnpm ```bash pnpm dlx prisma db pull --force ``` #### yarn ```bash yarn dlx prisma db pull --force ``` #### bun ```bash bunx --bun prisma db pull --force ``` Set composite type depth for MongoDB [#set-composite-type-depth-for-mongodb] #### npm ```bash npx prisma db pull --composite-type-depth=2 ``` #### pnpm ```bash pnpm dlx prisma db pull --composite-type-depth=2 ``` #### yarn ```bash yarn dlx prisma db pull --composite-type-depth=2 ``` #### bun ```bash bunx --bun prisma db pull --composite-type-depth=2 ``` ## Related pages - [`execute`](https://www.prisma.io/docs/cli/db/execute): Execute native commands to your database - [`push`](https://www.prisma.io/docs/cli/db/push): Push the state from your Prisma schema to your database - [`seed`](https://www.prisma.io/docs/cli/db/seed): Seed your database with test or initial data using custom scripts # push (/docs/cli/db/push) Location: CLI > db > push The `prisma db push` command pushes the state of your Prisma schema to the database without using migrations. It creates the database if it does not exist. This command is a good choice when you don't need to version schema changes, such as during prototyping and local development. Usage [#usage] ```bash prisma db push [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). Prerequisites [#prerequisites] Configure your database connection in `prisma.config.ts`: ```prisma file=schema.prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "sqlite" } ``` ```typescript file=prisma.config.ts import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Options [#options] | Option | Description | | -------------------- | ------------------------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `--url` | Override the datasource URL from the Prisma config file | | `--accept-data-loss` | Ignore data loss warnings | | `--force-reset` | Force a reset of the database before push | > [!WARNING] > In Prisma v7, `db push` no longer runs `prisma generate` automatically. Run it explicitly if needed. Examples [#examples] Push the schema to the database [#push-the-schema-to-the-database] #### npm ```bash npx prisma db push ``` #### pnpm ```bash pnpm dlx prisma db push ``` #### yarn ```bash yarn dlx prisma db push ``` #### bun ```bash bunx --bun prisma db push ``` Accept data loss [#accept-data-loss] Proceed even if the changes might result in data loss: #### npm ```bash npx prisma db push --accept-data-loss ``` #### pnpm ```bash pnpm dlx prisma db push --accept-data-loss ``` #### yarn ```bash yarn dlx prisma db push --accept-data-loss ``` #### bun ```bash bunx --bun prisma db push --accept-data-loss ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma db push --schema=/tmp/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma db push --schema=/tmp/schema.prisma ``` #### yarn ```bash yarn dlx prisma db push --schema=/tmp/schema.prisma ``` #### bun ```bash bunx --bun prisma db push --schema=/tmp/schema.prisma ``` Force reset before push [#force-reset-before-push] Reset the database before applying changes: #### npm ```bash npx prisma db push --force-reset ``` #### pnpm ```bash pnpm dlx prisma db push --force-reset ``` #### yarn ```bash yarn dlx prisma db push --force-reset ``` #### bun ```bash bunx --bun prisma db push --force-reset ``` See also [#see-also] * [Conceptual overview of `db push` and when to use it over Prisma Migrate](/orm/prisma-migrate/workflows/prototyping-your-schema) * [Schema prototyping with `db push`](/orm/prisma-migrate/workflows/prototyping-your-schema) ## Related pages - [`execute`](https://www.prisma.io/docs/cli/db/execute): Execute native commands to your database - [`pull`](https://www.prisma.io/docs/cli/db/pull): Pull the state from the database to the Prisma schema using introspection - [`seed`](https://www.prisma.io/docs/cli/db/seed): Seed your database with test or initial data using custom scripts # seed (/docs/cli/db/seed) Location: CLI > db > seed The `prisma db seed` command seeds your database with initial data. Usage [#usage] ```bash prisma db seed [options] ``` Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--` | Pass custom arguments to the seed file | The `--` delimiter allows you to pass custom arguments to your seed script (available in version 4.15.0+). Examples [#examples] Run the seed script [#run-the-seed-script] #### npm ```bash npx prisma db seed ``` #### pnpm ```bash pnpm dlx prisma db seed ``` #### yarn ```bash yarn dlx prisma db seed ``` #### bun ```bash bunx --bun prisma db seed ``` Pass custom arguments [#pass-custom-arguments] #### npm ```bash npx prisma db seed -- --arg1 value1 --arg2 value2 ``` #### pnpm ```bash pnpm dlx prisma db seed -- --arg1 value1 --arg2 value2 ``` #### yarn ```bash yarn dlx prisma db seed -- --arg1 value1 --arg2 value2 ``` #### bun ```bash bunx --bun prisma db seed -- --arg1 value1 --arg2 value2 ``` See also [#see-also] * [Seeding your database](/orm/prisma-migrate/workflows/seeding) ## Related pages - [`execute`](https://www.prisma.io/docs/cli/db/execute): Execute native commands to your database - [`pull`](https://www.prisma.io/docs/cli/db/pull): Pull the state from the database to the Prisma schema using introspection - [`push`](https://www.prisma.io/docs/cli/db/push): Push the state from your Prisma schema to your database # dev (/docs/cli/dev) Location: CLI > dev The `prisma dev` command starts a [local Prisma Postgres](/postgres/database/local-development) database that you can run Prisma ORM commands against. It's useful for development and testing and allows easy migration to [Prisma Postgres](/postgres) in production. Usage [#usage] ```bash prisma dev [options] ``` Options [#options] | Option | Description | Default | | ------------------ | --------------------------------------------------------- | --------- | | `-n`, `--name` | Name of the server (helps isolate state between projects) | `default` | | `-p`, `--port` | Main port number the Prisma Dev server will listen on | `51213` | | `-P`, `--db-port` | Port number the database server will listen on | `51214` | | `--shadow-db-port` | Port number the shadow database server will listen on | `51215` | | `-d`, `--detach` | Run the server in the background | `false` | | `--debug` | Enable debug logging | `false` | Subcommands [#subcommands] | Command | Description | | ------------------------------------ | --------------------------------- | | [`prisma dev ls`](/cli/dev/ls) | List available servers | | [`prisma dev rm`](/cli/dev/rm) | Remove servers | | [`prisma dev start`](/cli/dev/start) | Start one or more stopped servers | | [`prisma dev stop`](/cli/dev/stop) | Stop servers | Examples [#examples] Start a local Prisma Postgres server [#start-a-local-prisma-postgres-server] #### npm ```bash npx prisma dev ``` #### pnpm ```bash pnpm dlx prisma dev ``` #### yarn ```bash yarn dlx prisma dev ``` #### bun ```bash bunx --bun prisma dev ``` Output: ```text ✔ Great Success! Your prisma dev server default is ready and listening on ports 63567-63569. ╭──────────────────────────────────╮ │[q]uit [h]ttp url [t]cp urls │ ╰──────────────────────────────────╯ ``` Start with a specific name [#start-with-a-specific-name] Create a named instance for project isolation: #### npm ```bash npx prisma dev --name="mydbname" ``` #### pnpm ```bash pnpm dlx prisma dev --name="mydbname" ``` #### yarn ```bash yarn dlx prisma dev --name="mydbname" ``` #### bun ```bash bunx --bun prisma dev --name="mydbname" ``` Run in detached mode [#run-in-detached-mode] Run the server in the background: #### npm ```bash npx prisma dev --detach ``` #### pnpm ```bash pnpm dlx prisma dev --detach ``` #### yarn ```bash yarn dlx prisma dev --detach ``` #### bun ```bash bunx --bun prisma dev --detach ``` This frees up your terminal. Use `prisma dev ls` to see running servers and `prisma dev stop` to stop them. Specify custom ports [#specify-custom-ports] #### npm ```bash npx prisma dev --port 5000 --db-port 5001 --shadow-db-port 5002 ``` #### pnpm ```bash pnpm dlx prisma dev --port 5000 --db-port 5001 --shadow-db-port 5002 ``` #### yarn ```bash yarn dlx prisma dev --port 5000 --db-port 5001 --shadow-db-port 5002 ``` #### bun ```bash bunx --bun prisma dev --port 5000 --db-port 5001 --shadow-db-port 5002 ``` ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema - [`init`](https://www.prisma.io/docs/cli/init): Set up a new Prisma project in the current directory # ls (/docs/cli/dev/ls) Location: CLI > dev > ls The `prisma dev ls` command lists all available [local Prisma Postgres](/postgres/database/local-development) instances on your system. Usage [#usage] ```bash prisma dev ls [options] ``` Options [#options] | Option | Description | Default | | --------- | -------------------- | ------- | | `--debug` | Enable debug logging | `false` | Examples [#examples] List all servers [#list-all-servers] #### npm ```bash npx prisma dev ls ``` #### pnpm ```bash pnpm dlx prisma dev ls ``` #### yarn ```bash yarn dlx prisma dev ls ``` #### bun ```bash bunx --bun prisma dev ls ``` This shows all instances on your system with their current status and configuration. ## Related pages - [`rm`](https://www.prisma.io/docs/cli/dev/rm): Remove local Prisma Postgres servers - [`start`](https://www.prisma.io/docs/cli/dev/start): Start one or more stopped local Prisma Postgres servers - [`stop`](https://www.prisma.io/docs/cli/dev/stop): Stop local Prisma Postgres servers # rm (/docs/cli/dev/rm) Location: CLI > dev > rm The `prisma dev rm` command removes the data of one or more [local Prisma Postgres](/postgres/database/local-development) databases from your file system. Usage [#usage] ```bash prisma dev rm [options] ``` Arguments [#arguments] | Argument | Description | | -------- | ----------------------------------------------------- | | `` | Name(s) or glob pattern(s) of the server(s) to remove | Options [#options] | Option | Description | Default | | --------- | --------------------------------------------- | ------- | | `--debug` | Enable debug logging | `false` | | `--force` | Stop any running servers before removing them | `false` | Without `--force`, the command fails if any server is running. Examples [#examples] Remove a specific database [#remove-a-specific-database] #### npm ```bash npx prisma dev rm mydb ``` #### pnpm ```bash pnpm dlx prisma dev rm mydb ``` #### yarn ```bash yarn dlx prisma dev rm mydb ``` #### bun ```bash bunx --bun prisma dev rm mydb ``` Remove multiple databases with a pattern [#remove-multiple-databases-with-a-pattern] Remove all databases starting with `mydb`: #### npm ```bash npx prisma dev rm mydb* ``` #### pnpm ```bash pnpm dlx prisma dev rm mydb* ``` #### yarn ```bash yarn dlx prisma dev rm mydb* ``` #### bun ```bash bunx --bun prisma dev rm mydb* ``` Force remove a running database [#force-remove-a-running-database] Stop and remove a database in one command: #### npm ```bash npx prisma dev rm --force mydb ``` #### pnpm ```bash pnpm dlx prisma dev rm --force mydb ``` #### yarn ```bash yarn dlx prisma dev rm --force mydb ``` #### bun ```bash bunx --bun prisma dev rm --force mydb ``` > [!NOTE] > The `rm` command is interactive and includes safety prompts to prevent accidental data loss. ## Related pages - [`ls`](https://www.prisma.io/docs/cli/dev/ls): List available local Prisma Postgres servers - [`start`](https://www.prisma.io/docs/cli/dev/start): Start one or more stopped local Prisma Postgres servers - [`stop`](https://www.prisma.io/docs/cli/dev/stop): Stop local Prisma Postgres servers # start (/docs/cli/dev/start) Location: CLI > dev > start The `prisma dev start` command starts existing [local Prisma Postgres](/postgres/database/local-development) instances in the background. Usage [#usage] ```bash prisma dev start [options] ``` Arguments [#arguments] | Argument | Description | | -------- | ---------------------------------------------------- | | `` | Name(s) or glob pattern(s) of the server(s) to start | Options [#options] | Option | Description | Default | | --------- | -------------------- | ------- | | `--debug` | Enable debug logging | `false` | > [!NOTE] > This command only works with instances that already exist. Use `prisma dev` to create a new instance. Examples [#examples] Start a specific database [#start-a-specific-database] #### npm ```bash npx prisma dev start mydb ``` #### pnpm ```bash pnpm dlx prisma dev start mydb ``` #### yarn ```bash yarn dlx prisma dev start mydb ``` #### bun ```bash bunx --bun prisma dev start mydb ``` Start multiple databases with a pattern [#start-multiple-databases-with-a-pattern] Start all databases starting with `mydb`: #### npm ```bash npx prisma dev start mydb* ``` #### pnpm ```bash pnpm dlx prisma dev start mydb* ``` #### yarn ```bash yarn dlx prisma dev start mydb* ``` #### bun ```bash bunx --bun prisma dev start mydb* ``` ## Related pages - [`ls`](https://www.prisma.io/docs/cli/dev/ls): List available local Prisma Postgres servers - [`rm`](https://www.prisma.io/docs/cli/dev/rm): Remove local Prisma Postgres servers - [`stop`](https://www.prisma.io/docs/cli/dev/stop): Stop local Prisma Postgres servers # stop (/docs/cli/dev/stop) Location: CLI > dev > stop The `prisma dev stop` command stops one or more [local Prisma Postgres](/postgres/database/local-development) databases. Usage [#usage] ```bash prisma dev stop [options] ``` Arguments [#arguments] | Argument | Description | | -------- | --------------------------------------------------- | | `` | Name(s) or glob pattern(s) of the server(s) to stop | Options [#options] | Option | Description | Default | | --------- | -------------------- | ------- | | `--debug` | Enable debug logging | `false` | Examples [#examples] Stop a specific database [#stop-a-specific-database] #### npm ```bash npx prisma dev stop mydb ``` #### pnpm ```bash pnpm dlx prisma dev stop mydb ``` #### yarn ```bash yarn dlx prisma dev stop mydb ``` #### bun ```bash bunx --bun prisma dev stop mydb ``` Stop multiple databases with a pattern [#stop-multiple-databases-with-a-pattern] Stop all databases starting with `mydb`: #### npm ```bash npx prisma dev stop mydb* ``` #### pnpm ```bash pnpm dlx prisma dev stop mydb* ``` #### yarn ```bash yarn dlx prisma dev stop mydb* ``` #### bun ```bash bunx --bun prisma dev stop mydb* ``` > [!NOTE] > The `stop` command is interactive and includes safety prompts to prevent accidental operations. ## Related pages - [`ls`](https://www.prisma.io/docs/cli/dev/ls): List available local Prisma Postgres servers - [`rm`](https://www.prisma.io/docs/cli/dev/rm): Remove local Prisma Postgres servers - [`start`](https://www.prisma.io/docs/cli/dev/start): Start one or more stopped local Prisma Postgres servers # deploy (/docs/cli/migrate/deploy) Location: CLI > migrate > deploy The `prisma migrate deploy` command applies all pending migrations and creates the database if it doesn't exist. Primarily used in non-development environments. > [!WARNING] > This command is not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate deploy [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). Characteristics [#characteristics] * Does **not** look for drift in the database or changes in the Prisma schema * Does **not** reset the database or generate artifacts * Does **not** rely on a shadow database Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Examples [#examples] Deploy pending migrations [#deploy-pending-migrations] #### npm ```bash npx prisma migrate deploy ``` #### pnpm ```bash pnpm dlx prisma migrate deploy ``` #### yarn ```bash yarn dlx prisma migrate deploy ``` #### bun ```bash bunx --bun prisma migrate deploy ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma migrate deploy --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate deploy --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate deploy --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma migrate deploy --schema=./alternative/schema.prisma ``` ## Related pages - [`dev`](https://www.prisma.io/docs/cli/migrate/dev): Create a migration from changes in Prisma schema, apply it to the database, and trigger generators - [`diff`](https://www.prisma.io/docs/cli/migrate/diff): Compare the database schema from two arbitrary sources - [`reset`](https://www.prisma.io/docs/cli/migrate/reset): Reset your database and apply all migrations. All data will be lost - [`resolve`](https://www.prisma.io/docs/cli/migrate/resolve): Resolve issues with database migrations in deployment databases - [`status`](https://www.prisma.io/docs/cli/migrate/status): Check the status of your database migrations # dev (/docs/cli/migrate/dev) Location: CLI > migrate > dev The `prisma migrate dev` command creates and applies migrations during development. It requires a [shadow database](/orm/prisma-migrate/understanding-prisma-migrate/shadow-database). **For use in development environments only.** > [!WARNING] > This command is not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate dev [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). How it works [#how-it-works] 1. Reruns the existing migration history in the shadow database to detect schema drift 2. Applies pending migrations to the shadow database 3. Generates a new migration from any changes you made to the Prisma schema 4. Applies all unapplied migrations to the development database and updates the `_prisma_migrations` table > [!NOTE] > **Prisma v7**: `migrate dev` no longer automatically triggers `prisma generate` or seed scripts. Run them explicitly if needed. Options [#options] | Option | Description | | --------------- | ------------------------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `--url` | Override the datasource URL from the Prisma config file | | `-n`, `--name` | Name the migration | | `--create-only` | Create a new migration but do not apply it | > [!NOTE] > If a [schema drift](/orm/prisma-migrate/understanding-prisma-migrate/shadow-database#detecting-schema-drift) is detected while running with `--create-only`, you will be prompted to reset your database. Examples [#examples] Create and apply migrations [#create-and-apply-migrations] #### npm ```bash npx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### bun ```bash bunx --bun prisma migrate dev ``` Name the migration [#name-the-migration] #### npm ```bash npx prisma migrate dev --name added_job_title ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name added_job_title ``` #### yarn ```bash yarn dlx prisma migrate dev --name added_job_title ``` #### bun ```bash bunx --bun prisma migrate dev --name added_job_title ``` Create migration without applying [#create-migration-without-applying] #### npm ```bash npx prisma migrate dev --create-only ``` #### pnpm ```bash pnpm dlx prisma migrate dev --create-only ``` #### yarn ```bash yarn dlx prisma migrate dev --create-only ``` #### bun ```bash bunx --bun prisma migrate dev --create-only ``` This creates the migration file but doesn't apply it. Run `prisma migrate dev` again to apply. Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma migrate dev --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate dev --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate dev --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma migrate dev --schema=./alternative/schema.prisma ``` See also [#see-also] * [Conceptual overview of Prisma Migrate](/orm/prisma-migrate) * [Developing with Prisma Migrate](/orm/prisma-migrate) ## Related pages - [`deploy`](https://www.prisma.io/docs/cli/migrate/deploy): Apply pending migrations to update the database schema in production/staging - [`diff`](https://www.prisma.io/docs/cli/migrate/diff): Compare the database schema from two arbitrary sources - [`reset`](https://www.prisma.io/docs/cli/migrate/reset): Reset your database and apply all migrations. All data will be lost - [`resolve`](https://www.prisma.io/docs/cli/migrate/resolve): Resolve issues with database migrations in deployment databases - [`status`](https://www.prisma.io/docs/cli/migrate/status): Check the status of your database migrations # diff (/docs/cli/migrate/diff) Location: CLI > migrate > diff The `prisma migrate diff` command compares two database schema sources and outputs a description of the migration needed to transform the first into the second. > [!NOTE] > This command is only partially supported for [MongoDB](/orm/core-concepts/supported-databases/mongodb). See options below for details. Usage [#usage] ```bash prisma migrate diff --from-... --to-... ``` The output can be a human-readable summary (default) or an executable script. > [!WARNING] > The `migrate diff` command can only compare database features [supported by Prisma](/orm/reference/database-features). Differences in unsupported features (views, triggers, etc.) won't be shown. Prerequisites [#prerequisites] If using `--from-config-datasource` or `--to-config-datasource`, configure your database connection in `prisma.config.ts`: ```prisma file=schema.prisma generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "sqlite" } ``` ```typescript file=prisma.config.ts import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` Source types [#source-types] Both sources must use the same database provider. From options (one required) [#from-options-one-required] | Option | Description | Notes | | -------------------------- | ---------------------------------------- | ------------------------ | | `--from-empty` | Assume the source is an empty data model | | | `--from-schema` | Path to a Prisma schema file | | | `--from-migrations` | Path to Prisma migrations directory | Not supported in MongoDB | | `--from-config-datasource` | Use datasource from Prisma config file | Prisma v7+ | To options (one required) [#to-options-one-required] | Option | Description | Notes | | ------------------------ | --------------------------------------------- | ------------------------ | | `--to-empty` | Assume the destination is an empty data model | | | `--to-schema` | Path to a Prisma schema file | | | `--to-migrations` | Path to Prisma migrations directory | Not supported in MongoDB | | `--to-config-datasource` | Use datasource from Prisma config file | Prisma v7+ | Other options [#other-options] | Option | Description | Notes | | ---------------- | -------------------------------------------------------- | --------------------------- | | `--config` | Custom path to your Prisma config file | | | `--script` | Output a SQL script instead of human-readable summary | Not supported in MongoDB | | `-o`, `--output` | Write to a file instead of stdout | Available since 5.12.1 | | `--exit-code` | Change exit code behavior: Empty=0, Error=1, Not empty=2 | Default: Success=0, Error=1 | | `--help` | Display help message | | > [!NOTE] > **Prisma v7 breaking change**: The `--from-url`, `--to-url`, `--from-schema-datasource`, `--to-schema-datasource`, and `--shadow-database-url` options have been removed. Use `--from-config-datasource` and `--to-config-datasource` instead. Examples [#examples] Compare database to schema [#compare-database-to-schema] Roll forward after a migration failed: #### npm ```bash npx prisma migrate diff \ --from-config-datasource \ --to-schema=next_datamodel.prisma \ --script ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --from-config-datasource \ --to-schema=next_datamodel.prisma \ --script ``` #### yarn ```bash yarn dlx prisma migrate diff \ --from-config-datasource \ --to-schema=next_datamodel.prisma \ --script ``` #### bun ```bash bunx --bun prisma migrate diff \ --from-config-datasource \ --to-schema=next_datamodel.prisma \ --script ``` Compare schema to database [#compare-schema-to-database] #### npm ```bash npx prisma migrate diff \ --from-schema=schema.prisma \ --to-config-datasource \ --script ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --from-schema=schema.prisma \ --to-config-datasource \ --script ``` #### yarn ```bash yarn dlx prisma migrate diff \ --from-schema=schema.prisma \ --to-config-datasource \ --script ``` #### bun ```bash bunx --bun prisma migrate diff \ --from-schema=schema.prisma \ --to-config-datasource \ --script ``` Compare migrations to database [#compare-migrations-to-database] Generate a migration for a hotfix already applied on production: #### npm ```bash npx prisma migrate diff \ --from-migrations ./migrations \ --to-config-datasource \ --script ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --from-migrations ./migrations \ --to-config-datasource \ --script ``` #### yarn ```bash yarn dlx prisma migrate diff \ --from-migrations ./migrations \ --to-config-datasource \ --script ``` #### bun ```bash bunx --bun prisma migrate diff \ --from-migrations ./migrations \ --to-config-datasource \ --script ``` Pipe output to db execute [#pipe-output-to-db-execute] #### npm ```bash npx prisma migrate diff \ --from-config-datasource \ --to-schema=schema.prisma \ --script | prisma db execute --stdin ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --from-config-datasource \ --to-schema=schema.prisma \ --script | prisma db execute --stdin ``` #### yarn ```bash yarn dlx prisma migrate diff \ --from-config-datasource \ --to-schema=schema.prisma \ --script | prisma db execute --stdin ``` #### bun ```bash bunx --bun prisma migrate diff \ --from-config-datasource \ --to-schema=schema.prisma \ --script | prisma db execute --stdin ``` Check if sources are in sync [#check-if-sources-are-in-sync] Exits with code 2 if changes are detected: #### npm ```bash npx prisma migrate diff \ --exit-code \ --from-config-datasource \ --to-schema=schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --exit-code \ --from-config-datasource \ --to-schema=schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate diff \ --exit-code \ --from-config-datasource \ --to-schema=schema.prisma ``` #### bun ```bash bunx --bun prisma migrate diff \ --exit-code \ --from-config-datasource \ --to-schema=schema.prisma ``` See also [#see-also] * [Migration troubleshooting in production](/orm/prisma-migrate/workflows/patching-and-hotfixing#fixing-failed-migrations-with-migrate-diff-and-db-execute) ## Related pages - [`deploy`](https://www.prisma.io/docs/cli/migrate/deploy): Apply pending migrations to update the database schema in production/staging - [`dev`](https://www.prisma.io/docs/cli/migrate/dev): Create a migration from changes in Prisma schema, apply it to the database, and trigger generators - [`reset`](https://www.prisma.io/docs/cli/migrate/reset): Reset your database and apply all migrations. All data will be lost - [`resolve`](https://www.prisma.io/docs/cli/migrate/resolve): Resolve issues with database migrations in deployment databases - [`status`](https://www.prisma.io/docs/cli/migrate/status): Check the status of your database migrations # migrate (/docs/cli/migrate) Location: CLI > migrate The `prisma migrate` command group provides tools to create and apply database migrations. > [!NOTE] > Prisma Migrate does not apply to MongoDB. Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate [command] [options] ``` Global options [#global-options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Development commands [#development-commands] | Command | Description | | -------------------------------------------- | ------------------------------------------------------------------------ | | [`prisma migrate dev`](/cli/migrate/dev) | Create a migration from schema changes, apply it, and trigger generators | | [`prisma migrate reset`](/cli/migrate/reset) | Reset your database and apply all migrations (all data will be lost) | Production/staging commands [#productionstaging-commands] | Command | Description | | ------------------------------------------------ | ---------------------------------------------------------------------------- | | [`prisma migrate deploy`](/cli/migrate/deploy) | Apply pending migrations to the database | | [`prisma migrate status`](/cli/migrate/status) | Check the status of your database migrations | | [`prisma migrate resolve`](/cli/migrate/resolve) | Resolve issues with database migrations (baseline, failed migration, hotfix) | Commands for any stage [#commands-for-any-stage] | Command | Description | | ------------------------------------------ | ------------------------------------------------------ | | [`prisma migrate diff`](/cli/migrate/diff) | Compare the database schema from two arbitrary sources | Examples [#examples] ```bash # Create and apply a migration in development prisma migrate dev # Reset the database (development only) prisma migrate reset # Apply pending migrations in production prisma migrate deploy # Check migration status prisma migrate status # Compare database schemas prisma migrate diff \ --from-config-datasource \ --to-schema=./prisma/schema.prisma \ --script ``` See also [#see-also] * [Conceptual overview of Prisma Migrate](/orm/prisma-migrate) * [Developing with Prisma Migrate](/orm/prisma-migrate) ## Related pages - [`db`](https://www.prisma.io/docs/cli/db): Manage your database schema and lifecycle during development - [`debug`](https://www.prisma.io/docs/cli/debug): Display Prisma debug information including schema paths, engine binaries, environment variables, and cache directories for troubleshooting - [`dev`](https://www.prisma.io/docs/cli/dev): Start a local Prisma Postgres server for development - [`format`](https://www.prisma.io/docs/cli/format): Format and validate your Prisma schema file with consistent structure - [`generate`](https://www.prisma.io/docs/cli/generate): Generate artifacts like Prisma Client based on your Prisma schema # reset (/docs/cli/migrate/reset) Location: CLI > migrate > reset The `prisma migrate reset` command resets your database and re-applies all migrations. **For use in development environments only.** > [!WARNING] > This command is not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate reset [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). How it works [#how-it-works] 1. Drops the database/schema if possible, or performs a soft reset if the environment doesn't allow it 2. Creates a new database/schema with the same name 3. Applies all migrations 4. Runs seed scripts Options [#options] | Option | Description | | --------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `-f`, `--force` | Skip the confirmation prompt | Examples [#examples] Reset the database [#reset-the-database] #### npm ```bash npx prisma migrate reset ``` #### pnpm ```bash pnpm dlx prisma migrate reset ``` #### yarn ```bash yarn dlx prisma migrate reset ``` #### bun ```bash bunx --bun prisma migrate reset ``` Skip confirmation prompt [#skip-confirmation-prompt] #### npm ```bash npx prisma migrate reset --force ``` #### pnpm ```bash pnpm dlx prisma migrate reset --force ``` #### yarn ```bash yarn dlx prisma migrate reset --force ``` #### bun ```bash bunx --bun prisma migrate reset --force ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma migrate reset --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate reset --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate reset --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma migrate reset --schema=./alternative/schema.prisma ``` AI safety guardrails [#ai-safety-guardrails] Prisma ORM includes built-in safety checks to prevent accidental destructive commands when run through AI coding assistants. When AI agents like Claude Code, Cursor, Gemini CLI, or others attempt `prisma migrate reset --force`, Prisma blocks execution and shows a protective error message. To proceed, you must provide explicit consent. The AI agent will: 1. Explain what action it's attempting 2. Warn that this action irreversibly destroys all data 3. Confirm whether this is a development or production database 4. Ask for your explicit consent before proceeding After consent, the AI sets the `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` environment variable and reruns the command. ## Related pages - [`deploy`](https://www.prisma.io/docs/cli/migrate/deploy): Apply pending migrations to update the database schema in production/staging - [`dev`](https://www.prisma.io/docs/cli/migrate/dev): Create a migration from changes in Prisma schema, apply it to the database, and trigger generators - [`diff`](https://www.prisma.io/docs/cli/migrate/diff): Compare the database schema from two arbitrary sources - [`resolve`](https://www.prisma.io/docs/cli/migrate/resolve): Resolve issues with database migrations in deployment databases - [`status`](https://www.prisma.io/docs/cli/migrate/status): Check the status of your database migrations # resolve (/docs/cli/migrate/resolve) Location: CLI > migrate > resolve The `prisma migrate resolve` command allows you to solve migration history issues in production by marking a failed migration as already applied (supports baselining) or rolled back. > [!WARNING] > This command is not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate resolve [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). > [!NOTE] > This command can only be used with a failed migration. Using it with a successful migration results in an error. Use cases [#use-cases] * Recover from failed migrations * Baseline databases when starting to use Prisma Migrate on existing databases * Reconcile hotfixes done manually on databases with your migration history Run `prisma migrate status` to identify if you need to use `resolve`. Options [#options] | Option | Description | | --------------- | ------------------------------------------ | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | | `--applied` | Record a specific migration as applied | | `--rolled-back` | Record a specific migration as rolled back | You must specify either `--applied` or `--rolled-back`. Examples [#examples] Mark a migration as applied [#mark-a-migration-as-applied] #### npm ```bash npx prisma migrate resolve --applied 20201231000000_add_users_table ``` #### pnpm ```bash pnpm dlx prisma migrate resolve --applied 20201231000000_add_users_table ``` #### yarn ```bash yarn dlx prisma migrate resolve --applied 20201231000000_add_users_table ``` #### bun ```bash bunx --bun prisma migrate resolve --applied 20201231000000_add_users_table ``` Mark a migration as rolled back [#mark-a-migration-as-rolled-back] #### npm ```bash npx prisma migrate resolve --rolled-back 20201231000000_add_users_table ``` #### pnpm ```bash pnpm dlx prisma migrate resolve --rolled-back 20201231000000_add_users_table ``` #### yarn ```bash yarn dlx prisma migrate resolve --rolled-back 20201231000000_add_users_table ``` #### bun ```bash bunx --bun prisma migrate resolve --rolled-back 20201231000000_add_users_table ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma ``` #### bun ```bash bunx --bun prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma ``` See also [#see-also] * [Resolving migration history issues](https://pris.ly/d/migrate-resolve) ## Related pages - [`deploy`](https://www.prisma.io/docs/cli/migrate/deploy): Apply pending migrations to update the database schema in production/staging - [`dev`](https://www.prisma.io/docs/cli/migrate/dev): Create a migration from changes in Prisma schema, apply it to the database, and trigger generators - [`diff`](https://www.prisma.io/docs/cli/migrate/diff): Compare the database schema from two arbitrary sources - [`reset`](https://www.prisma.io/docs/cli/migrate/reset): Reset your database and apply all migrations. All data will be lost - [`status`](https://www.prisma.io/docs/cli/migrate/status): Check the status of your database migrations # status (/docs/cli/migrate/status) Location: CLI > migrate > status The `prisma migrate status` command checks the migrations in `./prisma/migrations/*` and the entries in the `_prisma_migrations` table to report the state of your migrations. > [!WARNING] > This command is not supported on [MongoDB](/orm/core-concepts/supported-databases/mongodb). Use [`db push`](/cli/db/push) instead. Usage [#usage] ```bash prisma migrate status [options] ``` The datasource URL configuration is read from the Prisma config file (e.g., `prisma.config.ts`). Options [#options] | Option | Description | | -------------- | -------------------------------------- | | `-h`, `--help` | Display help message | | `--config` | Custom path to your Prisma config file | | `--schema` | Custom path to your Prisma schema | Exit codes [#exit-codes] In versions 4.3.0 and later, `prisma migrate status` exits with code 1 when: * A database connection error occurs * Migration files haven't been applied to the database * Migration history has diverged from the database state * No migration table is found * Failed migrations are found Example output [#example-output] ```text Status 3 migrations found in prisma/migrations Your local migration history and the migrations table from your database are different: The last common migration is: 20201127134938_new_migration The migration have not yet been applied: 20201208100950_test_migration The migrations from the database are not found locally in prisma/migrations: 20201208100950_new_migration ``` Examples [#examples] Check migration status [#check-migration-status] #### npm ```bash npx prisma migrate status ``` #### pnpm ```bash pnpm dlx prisma migrate status ``` #### yarn ```bash yarn dlx prisma migrate status ``` #### bun ```bash bunx --bun prisma migrate status ``` Specify a schema path [#specify-a-schema-path] #### npm ```bash npx prisma migrate status --schema=./alternative/schema.prisma ``` #### pnpm ```bash pnpm dlx prisma migrate status --schema=./alternative/schema.prisma ``` #### yarn ```bash yarn dlx prisma migrate status --schema=./alternative/schema.prisma ``` #### bun ```bash bunx --bun prisma migrate status --schema=./alternative/schema.prisma ``` ## Related pages - [`deploy`](https://www.prisma.io/docs/cli/migrate/deploy): Apply pending migrations to update the database schema in production/staging - [`dev`](https://www.prisma.io/docs/cli/migrate/dev): Create a migration from changes in Prisma schema, apply it to the database, and trigger generators - [`diff`](https://www.prisma.io/docs/cli/migrate/diff): Compare the database schema from two arbitrary sources - [`reset`](https://www.prisma.io/docs/cli/migrate/reset): Reset your database and apply all migrations. All data will be lost - [`resolve`](https://www.prisma.io/docs/cli/migrate/resolve): Resolve issues with database migrations in deployment databases # Database Metrics (/docs/console/features/metrics) Location: Console > Features > Database Metrics You can have a single workspace that hosts several databases. Within each database, you can view detailed reports on how your database is performing, with various metrics like: * Average response size * Average query duration * Total egress * Total operations * Cache utilization Databases [#databases] For Prisma Postgres projects, the **Database** tab in the project view lets you configure and manage your databases. This interface provides tools to monitor and maintain your database resources. The **Connections** section displays a table with the following columns: | Column Name | Description | | ------------- | -------------------------------------------------------------------------------- | | **Hint** | Provides the URL structure for the database in use. | | **Static IP** | Indicates whether static IP is enabled for the database and associated products. | | **Products** | Lists the products that are enabled using the database URL. | | **Action** | Allows you to disable all active products and remove the connection. | # Feature Maturity (/docs/console/more/feature-maturity) Location: Console > More > Feature Maturity Prisma releases updates to Console multiple times per week, as opposed to the Prisma ORM that we release on a set schedule every few weeks. This is why we consider the lifecycle and process for maturing features in Console differently. You can [check out the releases and maturity process for the Prisma ORM](/orm/more/releases) for further details. You can find information about releases across *all* Prisma tools and products in the [changelog](https://www.prisma.io/changelog). Early Access [#early-access] If a feature on the Console is labeled as **Early Access**: * We have validated a problem and are considering a solution to it but are not certain whether that solution is complete or a perfect fit. * We want to gather more feedback and adjust the solution as necessary, knowing that users are prepared for significant breaking changes. * We reserve ourselves the right to throttle or remove access to a feature in Early Access to preserve the stability of the platform, or enforce its use to stay within the scope defined in our [Terms of Service](https://pris.ly/terms). As always, your feedback in our [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text) is invaluable to shape the design of the features. This will help us ensure that they can solve your problems in the best way possible. Preview [#preview] If a feature on the Console is labeled as **Preview**: * We have refined the software based on the valuable feedback we obtained during the Early Access phase. * We developed the feature further, bringing it closer to the final version, though it's not completely ready for production usage. * We have lifted the invite gate, so users no longer need an invitation to access the feature. Users just need to sign up to gain access. * We have increased the stability of the software compared to the Early Access phase. While there might still be some issues, they should be less frequent and less critical. * We use the Preview phase as a final stress test to ensure the product is ready for heavy production workloads. We recommend testing the product in a staging environment and welcome any feedback in our [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text). This will assist us in improving the product for its final release. ## Related pages - [`Support`](https://www.prisma.io/docs/console/more/support): Find the right support for any Console question # Support (/docs/console/more/support) Location: Console > More > Support Your feedback is invaluable, and we encourage you to share your experiences with us on [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=intro_text). Support [#support] Your support options are based on your workspace's active plan. For more details, take a look at our [pricing page](https://www.prisma.io/pricing). Community support [#community-support] Reach out to us in our [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text). Standard support [#standard-support] * Email support, [support@prisma.io](mailto\:support@prisma.io), or reach out via the Console * 2 business days, Mon-Fri, 9am-5pm CET Premium support [#premium-support] * Email support, [support@prisma.io](mailto\:support@prisma.io), or reach out via the Console * 1 business hour, Mon-Fri, 9am-5pm CET Dedicated support [#dedicated-support] Dedicated contact person. Deleting your PDP account [#deleting-your-pdp-account] If you want to delete your PDP account, **email us at [support@prisma.io](mailto\:support@prisma.io)** specifying the email id or GitHub handle with which you signed up. To ensure that you're not accidentally disabling any infrastructure powering one of your applications, we require that you **disable Accelerate in *all* environments of *all* your projects** that live in the account to be deleted. Additionally there should be no active subscriptions in the account to be deleted. Please cancel any active subscriptions before requesting account deletion. ## Related pages - [`Feature Maturity`](https://www.prisma.io/docs/console/more/feature-maturity): Understand Early Access and Preview feature stages in the Console # Expand-and-contract migrations (/docs/guides/database/data-migration) Location: Guides > Database > Expand-and-contract migrations Introduction [#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 [#prerequisites] Before starting this guide, make sure you have: * Node.js installed (version 20 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 [#1-set-up-your-environment] 1.1. Review initial schema [#11-review-initial-schema] Start with a basic schema containing a Post model: ```prisma generator client { provider = "prisma-client" output = "./generated/prisma" } datasource db { provider = "postgresql" } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) } ``` 1.2. Configure Prisma [#12-configure-prisma] Create a `prisma.config.ts` file in the root of your project with the following content: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > You'll need to install the required packages. If you haven't already, install them using your package manager: > > > > > #### npm > ```bash > npm install prisma @types/pg --save-dev > ``` > > > #### pnpm > ```bash > pnpm add prisma @types/pg --save-dev > ``` > > > #### yarn > ```bash > yarn add prisma @types/pg --dev > ``` > > > #### bun > ```bash > bun add prisma @types/pg --dev > ``` > > > > > > > #### npm > ```bash > npm install @prisma/client @prisma/adapter-pg pg dotenv > ``` > > > #### pnpm > ```bash > pnpm add @prisma/client @prisma/adapter-pg pg dotenv > ``` > > > #### yarn > ```bash > yarn add @prisma/client @prisma/adapter-pg pg dotenv > ``` > > > #### bun > ```bash > bun add @prisma/client @prisma/adapter-pg pg dotenv > ``` > > > > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). 1.3. Create a development branch [#13-create-a-development-branch] Create a new branch for your changes: ```bash git checkout -b create-status-field ``` 2. Expand the schema [#2-expand-the-schema] 2.1. Add new column [#21-add-new-column] Update your schema to add the new Status enum and field: ```prisma 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 [#22-create-migration] Generate the migration: #### npm ```bash npx prisma migrate dev --name add-status-column ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name add-status-column ``` #### yarn ```bash yarn dlx prisma migrate dev --name add-status-column ``` #### bun ```bash bunx --bun prisma migrate dev --name add-status-column ``` Then generate Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 3. Migrate the data [#3-migrate-the-data] 3.1. Create migration script [#31-create-migration-script] Create a new TypeScript file for the data migration: ```typescript import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import "dotenv/config"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); 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 [#32-set-up-migration-script] Add the migration script to your package.json: ```json { "scripts": { "data-migration:add-status-column": "tsx ./prisma/migrations//data-migration.ts" } } ``` 3.3. Execute migration [#33-execute-migration] 1. Update your DATABASE\_URL to point to the production database 2. Run the migration script: #### npm ```bash npm run data-migration:add-status-column ``` #### pnpm ```bash pnpm run data-migration:add-status-column ``` #### yarn ```bash yarn data-migration:add-status-column ``` #### bun ```bash bun run data-migration:add-status-column ``` 4. Contract the schema [#4-contract-the-schema] 4.1. Create cleanup branch [#41-create-cleanup-branch] Create a new branch for removing the old column: ```bash git checkout -b drop-published-column ``` 4.2. Remove old column [#42-remove-old-column] Update your schema to remove the published field: ```prisma 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 [#43-generate-cleanup-migration] Create and run the final migration: #### npm ```bash npx prisma migrate dev --name drop-published-column ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name drop-published-column ``` #### yarn ```bash yarn dlx prisma migrate dev --name drop-published-column ``` #### bun ```bash bunx --bun prisma migrate dev --name drop-published-column ``` Then generate Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 5. Deploy to production [#5-deploy-to-production] 5.1. Set up deployment [#51-set-up-deployment] Add the following command to your CI/CD pipeline: #### npm ```bash npx prisma migrate deploy ``` #### pnpm ```bash pnpm dlx prisma migrate deploy ``` #### yarn ```bash yarn dlx prisma migrate deploy ``` #### bun ```bash bunx --bun prisma migrate deploy ``` 5.2. Monitor deployment [#52-monitor-deployment] Watch for any errors in your logs and monitor your application's behavior after deployment. Troubleshooting [#troubleshooting] Common issues and solutions [#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 [#next-steps] Now that you've completed your first expand and contract migration, you can: * Learn more about [Prisma Migrate](/orm/prisma-migrate) * Explore [schema prototyping](/orm/prisma-migrate/workflows/prototyping-your-schema) * Understand [customizing migrations](/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](/orm/prisma-migrate/workflows/development-and-production) ## Related pages - [`Multiple databases`](https://www.prisma.io/docs/guides/database/multiple-databases): Learn how to use multiple Prisma Clients in a single app to connect to multiple databases, handle migrations, and deploy your application to Vercel - [`Schema management in teams`](https://www.prisma.io/docs/guides/database/schema-changes): Learn how to use Prisma Migrate effectively when collaborating on a project as a team # Multiple databases (/docs/guides/database/multiple-databases) Location: Guides > Database > Multiple databases Introduction [#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 [#prerequisites] Before you begin, make sure that you have the following: * Node.js 20+ 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 [#1-set-up-a-nextjs-project] Create a new Next.js app using `create-next-app` from your desired directory: #### npm ```bash npx create-next-app@latest my-multi-client-app ``` #### pnpm ```bash pnpm dlx create-next-app@latest my-multi-client-app ``` #### yarn ```bash yarn dlx create-next-app@latest my-multi-client-app ``` #### bun ```bash bunx --bun 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. > [!NOTE] > For completeness, those are: > > * TypeScript > * ESLint > * Tailwind CSS > * No `src` directory > * App Router > * Turbopack > * Default custom import alias: `@/*` Then, navigate to the project directory: ```bash cd my-multi-client-app ``` 2. Set up your databases and Prisma Clients [#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 and the required dependencies: #### npm ```bash npm install prisma tsx @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma tsx @types/pg --dev ``` #### bun ```bash bun add prisma tsx @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg dotenv pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). You have installed the required dependencies for the project. 2.1. Create a Prisma Postgres instance to contain user data [#21-create-a-prisma-postgres-instance-to-contain-user-data] Initialize Prisma with a [Prisma Postgres](/postgres) instance by running: #### npm ```bash npx prisma@latest init --db ``` #### pnpm ```bash pnpm dlx prisma@latest init --db ``` #### yarn ```bash yarn dlx prisma@latest init --db ``` #### bun ```bash bunx --bun prisma@latest init --db ``` > [!NOTE] > 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 [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=guides) 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., `DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require"`). Rename the `prisma` folder to `prisma-user-database`: ```bash mv prisma prisma-user-database ``` Edit your `.env` file to rename `DATABASE_URL` to `PPG_USER_DATABASE_URL`: ```bash title=".env" DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code --] PPG_USER_DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code ++] ``` 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](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider) for the generated Prisma Client: ```prisma title="prisma-user-database/schema.prisma" generator client { provider = "prisma-client" output = "../prisma-user-database/user-database-client-types" // [!code ++] } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` Create a `prisma.config.ts` file for the user database: ```typescript title="prisma-user-database/prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; // [!code ++] // [!code ++] export default defineConfig({ // [!code ++] schema: "prisma-user-database/schema.prisma", // [!code ++] migrations: { // [!code ++] path: "prisma-user-database/migrations", // [!code ++] }, // [!code ++] datasource: { // [!code ++] url: env("PPG_USER_DATABASE_URL"), // [!code ++] }, // [!code ++] }); // [!code ++] ``` > [!NOTE] > You'll need to install the `dotenv` package if you haven't already: > > > > > #### npm > ```bash > npm install dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### bun > ```bash > bun add dotenv > ``` > > Your user database schema is now ready. 2.2. Create a Prisma Postgres instance for post data [#22-create-a-prisma-postgres-instance-for-post-data] Repeat the initialization for the post database: #### npm ```bash npx prisma init npx create-db ``` #### pnpm ```bash pnpm dlx prisma init pnpm dlx create-db ``` #### yarn ```bash yarn dlx prisma init yarn dlx create-db ``` #### bun ```bash bunx --bun prisma init bun x create-db ``` Replace the generated `DATABASE_URL` in your `.env` file with the value from `npx create-db`, then rename the new `prisma` folder to `prisma-post-database`: ```bash mv prisma prisma-post-database ``` Rename the `DATABASE_URL` variable in `.env` to `PPG_POST_DATABASE_URL`: ```bash title=".env" DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code --] PPG_POST_DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code ++] ``` Edit the `prisma-post-database/schema.prisma` file to define a `Post` model. Also, update the datasource URL and set a [custom `output` directory](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider): ```prisma title="prisma-post-database/schema.prisma" generator client { provider = "prisma-client" output = "../prisma-post-database/post-database-client-types" // [!code ++] } datasource db { provider = "postgresql" } model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] } // [!code ++] ``` Create a `prisma.config.ts` file for the post database: ```typescript title="prisma-post-database/prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; // [!code ++] // [!code ++] export default defineConfig({ // [!code ++] schema: "prisma-post-database/schema.prisma", // [!code ++] migrations: { // [!code ++] path: "prisma-post-database/migrations", // [!code ++] }, // [!code ++] datasource: { // [!code ++] url: env("PPG_POST_DATABASE_URL"), // [!code ++] }, // [!code ++] }); // [!code ++] ``` Your post database schema is now set. 2.3. Add helper scripts and migrate the schemas [#23-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: ```json title="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 && npx prisma generate --schema ./prisma-post-database/schema.prisma", // [!code ++] "generate": "npx prisma generate --schema ./prisma-user-database/schema.prisma && npx prisma generate --schema ./prisma-post-database/schema.prisma", // [!code ++] "migrate": "npx prisma migrate dev --schema ./prisma-user-database/schema.prisma && npx prisma migrate dev --schema ./prisma-post-database/schema.prisma", // [!code ++] "deploy": "npx prisma migrate deploy --schema ./prisma-user-database/schema.prisma && npx prisma migrate deploy --schema ./prisma-post-database/schema.prisma", // [!code ++] "studio": "npx prisma studio --schema ./prisma-user-database/schema.prisma --port 5555 & npx prisma studio --schema ./prisma-post-database/schema.prisma --port 5556" // [!code ++] } ``` 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](/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 ```bash npm run migrate ``` #### pnpm ```bash pnpm run migrate ``` #### yarn ```bash yarn migrate ``` #### bun ```bash bun run migrate ``` When prompted, name the migration for each database accordingly. 3. Prepare the application to use multiple Prisma Clients [#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: ```bash 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 [#31-instantiate-and-export-the-prisma-client-for-the-user-database] In `lib/user-prisma-client.ts`, add the following code: ```ts title="lib/user-prisma-client.ts" import { PrismaClient } from "../prisma-user-database/user-database-client-types/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.PPG_USER_DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const getPrisma = () => new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] const globalForUserDBPrismaClient = global as unknown as { // [!code ++] userDBPrismaClient: ReturnType; // [!code ++] }; // [!code ++] // [!code ++] export const userDBPrismaClient = globalForUserDBPrismaClient.userDBPrismaClient || getPrisma(); // [!code ++] // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") // [!code ++] globalForUserDBPrismaClient.userDBPrismaClient = userDBPrismaClient; // [!code ++] ``` 3.2. Instantiate and export the Prisma Client for the post database [#32-instantiate-and-export-the-prisma-client-for-the-post-database] In `lib/post-prisma-client.ts`, add this code: ```ts title="lib/post-prisma-client.ts" import { PrismaClient } from "../prisma-post-database/post-database-client-types/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.PPG_POST_DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const getPrisma = () => new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] const globalForPostDBPrismaClient = global as unknown as { // [!code ++] postDBPrismaClient: ReturnType; // [!code ++] }; // [!code ++] // [!code ++] export const postDBPrismaClient = globalForPostDBPrismaClient.postDBPrismaClient || getPrisma(); // [!code ++] // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") // [!code ++] globalForPostDBPrismaClient.postDBPrismaClient = postDBPrismaClient; // [!code ++] ``` 4. Integrate multiple Prisma Clients in your Next.js app [#4-integrate-multiple-prisma-clients-in-your-nextjs-app] Modify your application code to fetch data from both databases. Update the `app/page.tsx` file as follows: ```ts title="app/page.tsx" import { postDBPrismaClient } from "@/lib/post-prisma-client"; // [!code ++] import { userDBPrismaClient } from "@/lib/user-prisma-client"; // [!code ++] // [!code ++] export default async function Home() { // [!code ++] const user = await userDBPrismaClient.user.findFirst(); // [!code ++] const post = await postDBPrismaClient.post.findFirst(); // [!code ++] // [!code ++] return ( // [!code ++]
// [!code ++]
// [!code ++]
// [!code ++]

Multi-DB Showcase

// [!code ++]

// [!code ++] Data fetched from two distinct databases. // [!code ++]

// [!code ++]
// [!code ++] // [!code ++]
// [!code ++]

// [!code ++] User Data // [!code ++]

// [!code ++]
 // [!code ++]
            {user ? JSON.stringify(user, null, 2) : "No user data available."} // [!code ++]
          
// [!code ++]
// [!code ++] // [!code ++]
// [!code ++]

// [!code ++] Post Data // [!code ++]

// [!code ++]
 // [!code ++]
            {post ? JSON.stringify(post, null, 2) : "No post data available."} // [!code ++]
          
// [!code ++]
// [!code ++]
// [!code ++]
// [!code ++] ); // [!code ++] } // [!code ++] ``` 4.1. Populate your databases with data [#41-populate-your-databases-with-data] In a separate terminal window, open two instances of [Prisma Studio](/studio) to add data to your databases by running the script: #### npm ```bash npm run studio ``` #### pnpm ```bash pnpm run studio ``` #### yarn ```bash yarn studio ``` #### bun ```bash bun 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 [#42-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`: ```json title="package.json" "script":{ "dev": "next dev --turbopack", // [!code --] "dev": "next dev", // [!code ++] "build": "next build", "start": "next start", "lint": "next lint", "postinstall": "npx prisma generate --schema ./prisma-user-database/schema.prisma && npx prisma generate --schema ./prisma-post-database/schema.prisma", "generate": "npx prisma generate --schema ./prisma-user-database/schema.prisma && npx prisma generate --schema ./prisma-post-database/schema.prisma", "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 ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun 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 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 [#5-deploy-your-nextjs-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: ```bash git add . git commit -m "Initial commit with Prisma Postgres integration" git branch -M main git remote add origin https://github.com//.git git 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/deployments). 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 [#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](/guides/deployment/pnpm-workspaces) * [How to use Prisma ORM with Turborepo](/guides/deployment/turborepo) ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/database/data-migration): Learn how to perform data migrations using the expand and contract pattern with Prisma ORM - [`Schema management in teams`](https://www.prisma.io/docs/guides/database/schema-changes): Learn how to use Prisma Migrate effectively when collaborating on a project as a team # Schema management in teams (/docs/guides/database/schema-changes) Location: Guides > Database > Schema management in teams Introduction [#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 [#prerequisites] Before starting this guide, make sure you have: * Node.js installed (version 20 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`](/orm/prisma-migrate/workflows/prototyping-your-schema) is used for [MongoDB](/orm/core-concepts/supported-databases/mongodb). 1. Understand migration basics [#1-understand-migration-basics] 1.1. Migration order [#11-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 [#12-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 1.3. Configure Prisma [#13-configure-prisma] Create a `prisma.config.ts` file in the root of your project with the following content: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > You'll need to install the `dotenv` package to load environment variables. If you haven't already, install it using your package manager: > > > > > #### npm > ```bash > npm install dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### bun > ```bash > bun add dotenv > ``` > > 2. Incorporate team changes [#2-incorporate-team-changes] 2.1. Pull latest changes [#21-pull-latest-changes] To incorporate changes from collaborators: 1. Pull the changed Prisma schema and `./prisma/migrations` folder 2. Run the migrate command: #### npm ```bash npx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### bun ```bash bunx --bun prisma migrate dev ``` 2.2. Example scenario [#22-example-scenario] Let's walk through a sample scenario with three developers sharing schema changes: #### Before ```prisma title="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[] } ``` #### After ```prisma title="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 // [!code ++] bestPacmanScore Int? // Added by you // [!code ++] posts Post[] } // Added by Javier // [!code ++] model Tag { // [!code ++] tagName String @id // [!code ++] tagCategory Category // [!code ++] } // [!code ++] ``` 3. Handle concurrent changes [#3-handle-concurrent-changes] 3.1. Developer A's changes [#31-developer-as-changes] Ania adds a new field: ```prisma model User { /* ... */ favoriteColor String? } ``` And generates a migration: #### npm ```bash npx prisma migrate dev --name new-field ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name new-field ``` #### yarn ```bash yarn dlx prisma migrate dev --name new-field ``` #### bun ```bash bunx --bun prisma migrate dev --name new-field ``` #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 3.2. Developer B's changes [#32-developer-bs-changes] Javier adds a new model: ```prisma model Tag { tagName String @id tagCategory Category } ``` And generates a migration: #### npm ```bash npx prisma migrate dev --name new-model ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name new-model ``` #### yarn ```bash yarn dlx prisma migrate dev --name new-model ``` #### bun ```bash bunx --bun prisma migrate dev --name new-model ``` #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 3.3. Merge changes [#33-merge-changes] The migration history now has two new migrations: A diagram showing changes by two separate developers converging in a single migration history. 4. Integrate your changes [#4-integrate-your-changes] 4.1. Pull team changes [#41-pull-team-changes] 1. Pull the most recent changes: * Two new migrations * Updated schema file 2. Review the merged schema: ```prisma model User { /* ... */ favoriteColor String? bestPacmanScore Int? } model Tag { tagName String @id tagCategory Category posts Post[] } ``` 4.2. Generate your migration [#42-generate-your-migration] Run the migrate command: #### npm ```bash npx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### bun ```bash bunx --bun prisma migrate dev ``` #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 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 [#43-commit-changes] Commit: * The merged `schema.prisma` * Your new migration file Next steps [#next-steps] Now that you understand team schema management, you can: * Learn about [customizing migrations](/orm/prisma-migrate/workflows/customizing-migrations) * Explore [deployment workflows](/orm/prisma-migrate/workflows/development-and-production) For more information: * [Prisma Migrate documentation](/orm/prisma-migrate) * [Team development workflows](/orm/prisma-migrate/workflows/development-and-production) ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/database/data-migration): Learn how to perform data migrations using the expand and contract pattern with Prisma ORM - [`Multiple databases`](https://www.prisma.io/docs/guides/database/multiple-databases): Learn how to use multiple Prisma Clients in a single app to connect to multiple databases, handle migrations, and deploy your application to Vercel # Bun workspaces (/docs/guides/deployment/bun-workspaces) Location: Guides > Deployment > Bun workspaces Introduction [#introduction] This guide shows you how to use Prisma ORM in a [Bun Workspaces](https://bun.sh/docs/install/workspaces) monorepo. You'll set up a shared database package with Prisma ORM, then integrate it into a Next.js app in the same workspace. Prerequisites [#prerequisites] * [Bun](https://bun.sh/docs/installation) installed * A [Prisma Postgres](/postgres) database (or another [supported database](/orm/reference/supported-databases)) 1. Set up project [#1-set-up-project] Before integrating Prisma ORM, you need to set up your project structure. Start by creating a new directory for your project (for example, `my-monorepo`) and initialize a Node.js project: ```bash mkdir my-monorepo cd my-monorepo bun init -y ``` Next, add the `workspaces` array to your root `package.json` to define your workspace structure: ```json title="package.json" { "name": "my-monorepo", // [!code ++] "workspaces": ["apps/*", "packages/*"] // [!code ++] } ``` Finally, create directories for your applications and shared packages: ```bash mkdir apps mkdir -p packages/database ``` 2. Set up database package [#2-set-up-database-package] This section covers creating a standalone database package that uses Prisma ORM. The package will house all database models and the generated Prisma ORM client, making it reusable across your monorepo. 2.1. Install dependencies [#21-install-dependencies] Navigate to the `packages/database` directory and initialize a new package: ```bash cd packages/database bun init ``` Install the required Prisma ORM packages and other dependencies: ```bash bun add -d prisma typescript tsx @types/node @types/pg bun add @prisma/client @prisma/adapter-pg pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). 2.2. Set up Prisma ORM and schema [#22-set-up-prisma-orm-and-schema] Initialize Prisma ORM with an instance of [Prisma Postgres](/postgres) in the `database` package by running the following command: ```bash bunx --bun prisma init ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This command: * Creates a `prisma` directory containing a `schema.prisma` file for your database models. * Creates a `prisma.config.ts` file for configuring Prisma. * Creates a `.env` file with a local `DATABASE_URL`. Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: ```bash npx create-db ``` Edit the `schema.prisma` file to add a `User` model. The default generator already sets `output = "../generated/prisma"`: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` If the generated `prisma.config.ts` comments mention installing `dotenv`, install it so environment variables load: ```bash bun add dotenv ``` Add a `scripts` section to your database `package.json` (Bun init may not add one by default): ```json title="database/package.json" { "scripts": { // [!code ++] "db:generate": "prisma generate", // [!code ++] "db:migrate": "prisma migrate dev", // [!code ++] "db:deploy": "prisma migrate deploy", // [!code ++] "db:seed": "prisma db seed", // [!code ++] "db:studio": "prisma studio" // [!code ++] } // [!code ++] } ``` Use [Prisma Migrate](/orm/prisma-migrate) to migrate your database changes: ```bash bun run db:migrate ``` When prompted by the CLI, enter a descriptive name for your migration. After the migration completes, run generate so the Prisma ORM client is created: ```bash bun run db:generate ``` Create a `client.ts` file to initialize the Prisma ORM client with a driver adapter: ```ts title="database/client.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); // Use globalThis for broader environment compatibility const globalForPrisma = globalThis as typeof globalThis & { prisma?: PrismaClient; }; export const prisma: PrismaClient = globalForPrisma.prisma ?? new PrismaClient({ adapter, }); if (process.env.NODE_ENV !== "production") { globalForPrisma.prisma = prisma; } ``` Then, create an `index.ts` file to re-export the instance of the Prisma ORM client and all generated types: ```ts title="database/index.ts" export { prisma } from "./client"; export * from "./generated/prisma/client"; ``` 2.3. Seed the database [#23-seed-the-database] Add a seed script to populate the database with sample users. Create `prisma/seed.ts` in the database package: ```ts title="database/prisma/seed.ts" import "dotenv/config"; import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter }); async function main() { await prisma.user.createMany({ data: [ { email: "alice@example.com", name: "Alice" }, { email: "bob@example.com", name: "Bob" }, { email: "charlie@example.com", name: "Charlie" }, ], skipDuplicates: true, }); console.log("Seed complete."); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Add the `seed` option to the existing `migrations` config in your database package's `prisma.config.ts` (add the `seed` line inside `migrations`): ```ts title="database/prisma.config.ts" migrations: { path: "prisma/migrations", seed: "bun prisma/seed.ts", // [!code ++] }, ``` At this point, your shared database package is fully configured and ready for use across your monorepo. 2.4. Add root scripts [#24-add-root-scripts] Add the following scripts to the root `package.json` of your monorepo. They let you run database and app commands from the root: ```json title="package.json" "scripts": { // [!code ++] "build": "bun run --filter database db:deploy && bun run --filter database db:generate && bun run --filter web build", // [!code ++] "start": "bun run --filter web start", // [!code ++] "dev": "bun run --filter database db:generate && bun run --filter web dev", // [!code ++] "seed": "bun run --filter database db:seed", // [!code ++] "studio": "bun run --filter database db:studio" // [!code ++] } // [!code ++] ``` From the monorepo root, run `bun run seed` to add sample users. Run `bun run studio` to open [Prisma Studio](/studio) at [`http://localhost:5555`](http://localhost:5555) to view and edit your data. 3. Set up Next.js app [#3-set-up-nextjs-app] Now that the database package is set up, create a frontend application (using Next.js) that uses the shared Prisma ORM client to interact with your database. 3.1. Create Next.js app [#31-create-nextjs-app] Navigate to the `apps` directory: ```bash cd ../../apps ``` Create a new Next.js app named `web`: ```bash bun create next-app@latest web --yes ``` > [!NOTE] > important > > The `--yes` flag uses default configurations to bootstrap the Next.js app (which in this guide uses the app router without a `src/` directory). When prompted for a package manager, choose **Bun** so the app uses Bun within the workspace. > > Additionally, the flag may automatically initialize a Git repository in the `web` folder. If that happens, please remove the `.git` directory by running `rm -r .git`. Then, navigate into the web directory: ```bash cd web/ ``` Copy the `.env` file from the database package to ensure the same environment variables are available: ```bash cp ../../packages/database/.env . ``` Open the `package.json` file of your Next.js app and add the shared `database` package as a dependency: ```json title="web/package.json" "dependencies": { "database": "workspace:*" // [!code ++] } ``` Run the following command to install the `database` package: ```bash bun install ``` 3.2. Add database to app [#32-add-database-to-app] Modify your Next.js application code to use the Prisma ORM client from the database package. Update `app/page.tsx` as follows: ```tsx title="app/page.tsx" import { prisma } from "database"; export default async function Home() { const user = await prisma.user.findFirst({ select: { name: true, }, }); return (
{user?.name &&

Hello from {user.name}

} {!user?.name &&

No user has been added to the database yet.

}
); } ``` This code demonstrates importing and using the shared Prisma ORM client to query your `User` model. 3.3. Run the app [#33-run-the-app] Then head back to the root of the monorepo: ```bash cd ../../ ``` Start your development server by executing: ```bash bun run dev ``` Open your browser at [`http://localhost:3000`](http://localhost:3000) to see your app in action. You can run `bun run studio` to open [Prisma Studio](/studio) at [`http://localhost:5555`](http://localhost:5555) to view and edit your data. Next steps [#next-steps] You have now created a monorepo that uses Prisma ORM, with a shared database package integrated into a Next.js application. For further exploration and to enhance your setup, consider reading the [How to use Prisma ORM with Turborepo](/guides/deployment/turborepo) guide. ## Related pages - [`Cloudflare D1`](https://www.prisma.io/docs/guides/deployment/cloudflare-d1): Learn how to use Prisma ORM with Cloudflare D1 - [`Cloudflare Workers`](https://www.prisma.io/docs/guides/deployment/cloudflare-workers): Learn how to use Prisma ORM and Prisma Postgres in a Cloudflare Workers project - [`Docker`](https://www.prisma.io/docs/guides/deployment/docker): Learn step-by-step configure a Prisma ORM app in Docker - [`pnpm workspaces`](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces): Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently - [`Turborepo`](https://www.prisma.io/docs/guides/deployment/turborepo): Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently # Cloudflare D1 (/docs/guides/deployment/cloudflare-d1) Location: Guides > Deployment > Cloudflare D1 Introduction [#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 [#prerequisites] Before starting this guide, make sure you have: * A Cloudflare account * Node.js installed (version 20 or higher) * Wrangler CLI installed (version 3.39.0 or higher) * Basic familiarity with Cloudflare Workers and D1 1. Create a new Cloudflare Worker and initialize Prisma ORM [#1-create-a-new-cloudflare-worker-and-initialize-prisma-orm] Run the following command to create a [new Cloudflare Worker project](https://developers.cloudflare.com/d1/get-started/#1-create-a-worker): #### npm ```bash npm create cloudflare@latest d1-tutorial -- --type=hello-world --ts=true --git=true --deploy=false ``` #### pnpm ```bash pnpm create cloudflare d1-tutorial --type=hello-world --ts=true --git=true --deploy=false ``` #### yarn ```bash yarn create cloudflare d1-tutorial --type=hello-world --ts=true --git=true --deploy=false ``` #### bun ```bash bunx create-cloudflare d1-tutorial --type hello-world --ts=true --git=true --deploy=false ``` Then navigate into the newly created directory: ```bash cd d1-tutorial ``` And initialize Prisma ORM in the project: #### npm ```bash npx prisma init --datasource-provider sqlite ``` #### pnpm ```bash pnpm dlx prisma init --datasource-provider sqlite ``` #### yarn ```bash yarn dlx prisma init --datasource-provider sqlite ``` #### bun ```bash bunx --bun prisma init --datasource-provider sqlite ``` And install the Prisma ORM CLI as a development dependency: #### npm ```bash npm install --save-dev prisma ``` #### pnpm ```bash pnpm add --save-dev prisma ``` #### yarn ```bash yarn add --dev prisma ``` #### bun ```bash bun add --dev prisma ``` 2. Configure Prisma schema [#2-configure-prisma-schema] In your Prisma schema, set the `provider` of the `datasource` to `sqlite`. If you just bootstrapped the Prisma schema with `prisma init`, also be sure to add the `runtime = "cloudflare"` to the generator block and the following `User` model: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../src/generated/prisma" runtime = "cloudflare" } datasource db { provider = "sqlite" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` 3. Install dependencies [#3-install-dependencies] Next, install the required packages: #### npm ```bash npm install @prisma/client @prisma/adapter-d1 dotenv ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-d1 dotenv ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-d1 dotenv ``` #### bun ```bash bun add @prisma/client @prisma/adapter-d1 dotenv ``` 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. 4. Create a D1 database [#4-create-a-d1-database] Run the following command to create a new D1 database: #### npm ```bash npx wrangler@latest d1 create __YOUR_D1_DATABASE_NAME__ ``` #### pnpm ```bash pnpm dlx wrangler@latest d1 create __YOUR_D1_DATABASE_NAME__ ``` #### yarn ```bash yarn dlx wrangler@latest d1 create __YOUR_D1_DATABASE_NAME__ ``` #### bun ```bash bunx --bun wrangler@latest d1 create __YOUR_D1_DATABASE_NAME__ ``` > [!NOTE] > The `__YOUR_D1_DATABASE_NAME__` is a placeholder that should be replaced with the name you want to give your D1 database. For example, you can use `prisma-d1-example`. This command will authenticate you with Cloudflare and ask you to select a Cloudflare account. After that, it will create a new D1 database and output the database ID and name: ```bash ✅ Successfully created DB '__YOUR_D1_DATABASE_NAME__' in region __REGION__ Created your new D1 database. { "d1_databases": [ { "binding": "DB", "database_name": "__YOUR_D1_DATABASE_NAME__", "database_id": "" } ] } ``` Copy the terminal output and add the content to your `wrangler.jsonc` file. This file is used to configure your Cloudflare Worker and its bindings. To connect your Workers with the D1 instance, add the following binding to your `wrangler.jsonc`: ```json title="wrangler.jsonc" { "$schema": "node_modules/wrangler/config-schema.json", "name": "d1-tutorial", "main": "src/index.ts", "compatibility_date": "2025-08-05", "d1_databases": [ { "binding": "DB", "database_name": "__YOUR_D1_DATABASE_NAME__", // to be replaced "database_id": "__YOUR_D1_DATABASE_ID__" // to be replaced } ] } ``` > [!NOTE] > The `__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 the database 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. 5. Set up database migrations [#5-set-up-database-migrations] For Cloudflare D1, you'll use Prisma's migration workflow combined with Wrangler CLI to manage your database schema. Since D1 is a serverless SQLite database, we'll use `prisma migrate diff` to generate migration SQL and then apply it using Wrangler. 5.1 Set up environment variables [#51-set-up-environment-variables] Add a `.env` file in the root of your project with your local database URL: ```text title=".env" DATABASE_URL="file:./prisma/db.sqlite" ``` Also create a `prisma.config.ts` file in the root of your project: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 5.2 Generate migration SQL [#52-generate-migration-sql] First, create a migrations directory inside the `prisma` folder and create a file named `0001_init.sql`: ```bash mkdir -p prisma/migrations ``` Now use `prisma migrate diff` to generate the SQL needed to create your database schema: #### npm ```bash npx prisma migrate diff \ --from-empty \ --to-schema prisma/schema.prisma \ --script > prisma/migrations/0001_init.sql ``` #### pnpm ```bash pnpm dlx prisma migrate diff \ --from-empty \ --to-schema prisma/schema.prisma \ --script > prisma/migrations/0001_init.sql ``` #### yarn ```bash yarn dlx prisma migrate diff \ --from-empty \ --to-schema prisma/schema.prisma \ --script > prisma/migrations/0001_init.sql ``` #### bun ```bash bunx --bun prisma migrate diff \ --from-empty \ --to-schema prisma/schema.prisma \ --script > prisma/migrations/0001_init.sql ``` This command generates a SQL file that contains the statements needed to create your database tables. You can inspect the generated SQL in `prisma/migrations/0001_init.sql`. 5.3 Apply migrations to D1 [#53-apply-migrations-to-d1] Now apply the migration to both your local and remote D1 databases using Wrangler: #### npm ```bash # Apply to local database npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --local --file="./prisma/migrations/0001_init.sql" # Apply to remote database npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --remote --file="./prisma/migrations/0001_init.sql" ``` #### pnpm ```bash # Apply to local database pnpm dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --local --file="./prisma/migrations/0001_init.sql" # Apply to remote database pnpm dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --remote --file="./prisma/migrations/0001_init.sql" ``` #### yarn ```bash # Apply to local database yarn dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --local --file="./prisma/migrations/0001_init.sql" # Apply to remote database yarn dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --remote --file="./prisma/migrations/0001_init.sql" ``` #### bun ```bash # Apply to local database bun x wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --local --file="./prisma/migrations/0001_init.sql" # Apply to remote database bun x wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --remote --file="./prisma/migrations/0001_init.sql" ``` > [!NOTE] > Replace `__YOUR_D1_DATABASE_NAME__` with the actual name of your D1 database that you created in step 4. 5.4 Add sample data [#54-add-sample-data] Let's create some dummy data that we can query once the Worker is running: #### npm ```bash # For the local database npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Local)');" --local # For the remote database npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Remote)');" --remote ``` #### pnpm ```bash # For the local database pnpm dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Local)');" --local # For the remote database pnpm dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Remote)');" --remote ``` #### yarn ```bash # For the local database yarn dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Local)');" --local # For the remote database yarn dlx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Remote)');" --remote ``` #### bun ```bash # For the local database bun x wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Local)');" --local # For the remote database bun x wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command="INSERT INTO \"User\" (\"email\", \"name\") VALUES ('jane@prisma.io', 'Jane Doe (Remote)');" --remote ``` > [!NOTE] > For future schema changes, you can generate new migration files using: > > > > > #### npm > ```bash > npx prisma migrate diff \ > --from-local-d1 \ > --to-schema prisma/schema.prisma \ > --script > migrations/0002_add_new_field.sql > ``` > > > #### pnpm > ```bash > pnpm dlx prisma migrate diff \ > --from-local-d1 \ > --to-schema prisma/schema.prisma \ > --script > migrations/0002_add_new_field.sql > ``` > > > #### yarn > ```bash > yarn dlx prisma migrate diff \ > --from-local-d1 \ > --to-schema prisma/schema.prisma \ > --script > migrations/0002_add_new_field.sql > ``` > > > #### bun > ```bash > bunx --bun prisma migrate diff \ > --from-local-d1 \ > --to-schema prisma/schema.prisma \ > --script > migrations/0002_add_new_field.sql > ``` > > > > Then apply them using the same `wrangler d1 execute` commands as shown above. 6. Implement the Worker [#6-implement-the-worker] Before adding a Prisma Client query to your Worker, you need to generate Prisma Client with the following command: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun 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. This `DB` name matches the binding name you configured in `wrangler.jsonc`. (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, passing `env.DB` which accesses your D1 database binding. 3. Send a query using Prisma Client and return the result. Open `src/index.ts` and replace the entire content with the following: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/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); ctx.waitUntil(prisma.$disconnect()); // or just await prisma.$disconnect() return new Response(result); }, }; ``` We explicitly call `prisma.$disconnect()` here to guarantee timely release of resources or else the worker might run out of memory. 7. Run the Worker locally [#7-run-the-worker-locally] With the database query in place and Prisma Client generated, you can run the Worker locally. If your Worker needs any environment variables, create a `.dev.vars` file in the root of your project. For this example, we don't need any additional environment variables since the D1 binding is already configured in `wrangler.jsonc`. Now run the Worker locally: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` Now you can open your browser at [`http://localhost:8787`](http://localhost:8787/) to see the result of the database query: ```js no-copy [{ id: 1, email: "jane@prisma.io", name: "Jane Doe (Local)" }]; ``` 8. Deploy the Worker [#8-deploy-the-worker] To deploy the Worker, run the following command: #### npm ```bash npm run deploy ``` #### pnpm ```bash pnpm run deploy ``` #### yarn ```bash yarn deploy ``` #### bun ```bash bun run deploy ``` Your deployed Worker is accessible via `https://d1-tutorial.USERNAME.workers.dev` (replace `USERNAME` with your Cloudflare account username). If you navigate your browser to that URL, you should see the following data that's queried from your remote D1 database: ```js no-copy [{ id: 1, email: "jane@prisma.io", name: "Jane Doe (Remote)" }]; ``` Next steps [#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](/orm) * [Prisma Client API reference](/orm/prisma-client/setup-and-configuration/introduction) * [Cloudflare D1 documentation](https://developers.cloudflare.com/d1) ## Related pages - [`Bun workspaces`](https://www.prisma.io/docs/guides/deployment/bun-workspaces): Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo to build scalable and modular applications efficiently - [`Cloudflare Workers`](https://www.prisma.io/docs/guides/deployment/cloudflare-workers): Learn how to use Prisma ORM and Prisma Postgres in a Cloudflare Workers project - [`Docker`](https://www.prisma.io/docs/guides/deployment/docker): Learn step-by-step configure a Prisma ORM app in Docker - [`pnpm workspaces`](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces): Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently - [`Turborepo`](https://www.prisma.io/docs/guides/deployment/turborepo): Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently # Cloudflare Workers (/docs/guides/deployment/cloudflare-workers) Location: Guides > Deployment > Cloudflare Workers Introduction [#introduction] **Yes, Prisma Postgres works on Cloudflare Workers.** Standard PostgreSQL clients (like `pg` or `postgres.js`) use TCP connections, and Cloudflare Workers doesn't support TCP by default. That's why most Postgres databases can't be accessed directly from Workers. There are two ways around it with Prisma Postgres: 1. **Node.js compatibility mode** — add the `nodejs_compat` flag to your `wrangler.jsonc` and Prisma ORM can use TCP via Cloudflare's Node.js TCP API. That's what this guide does. 2. **Serverless HTTP driver** — the [`@prisma/ppg` driver](/postgres/database/serverless-driver) connects over HTTP instead of TCP. No compatibility flag needed. This guide uses the `nodejs_compat` approach. Prisma Postgres handles connection pooling, so you don't have to worry about Workers spinning up a new connection per request. You can find a complete example on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/cloudflare-workers). Prerequisites [#prerequisites] * [Node.js 20+](https://nodejs.org) * A [Cloudflare account](https://dash.cloudflare.com/sign-up/workers-and-pages) 1. Set up your project [#1-set-up-your-project] Create a new Cloudflare Workers project: #### npm ```bash npm create cloudflare@latest prisma-cloudflare-worker -- --type=hello-world --ts=true --git=true --deploy=false ``` #### pnpm ```bash pnpm create cloudflare prisma-cloudflare-worker --type=hello-world --ts=true --git=true --deploy=false ``` #### yarn ```bash yarn create cloudflare prisma-cloudflare-worker --type=hello-world --ts=true --git=true --deploy=false ``` #### bun ```bash bunx create-cloudflare prisma-cloudflare-worker --type hello-world --ts=true --git=true --deploy=false ``` Navigate into the newly created project directory: ```bash cd prisma-cloudflare-worker ``` 2. Install and configure Prisma [#2-install-and-configure-prisma] 2.1. Install dependencies [#21-install-dependencies] To get started with Prisma, you'll need to install a few dependencies: #### npm ```bash npm install prisma dotenv-cli @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma dotenv-cli @types/pg --save-dev ``` #### yarn ```bash yarn add prisma dotenv-cli @types/pg --dev ``` #### bun ```bash bun add prisma dotenv-cli @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg dotenv pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: #### npm ```bash npx prisma init ``` #### pnpm ```bash pnpm dlx prisma init ``` #### yarn ```bash yarn dlx prisma init ``` #### bun ```bash bunx --bun prisma init ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma/` directory with a `schema.prisma` file * A `prisma.config.ts` file with your Prisma configuration * A `.env` file with a local `DATABASE_URL` already set Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.2. Enable Node.js compatibility in Cloudflare Workers [#22-enable-nodejs-compatibility-in-cloudflare-workers] Cloudflare Workers needs Node.js compatibility enabled to work with Prisma. Add the `nodejs_compat` compatibility flag to your `wrangler.jsonc`: ```json title="wrangler.jsonc" { "name": "prisma-cloudflare-worker", "main": "src/index.ts", "compatibility_flags": ["nodejs_compat"], // [!code ++] "compatibility_date": "2024-01-01" } ``` 2.3. Define your Prisma Schema [#23-define-your-prisma-schema] In the `prisma/schema.prisma` file, add the following `User` model and set the runtime to `cloudflare`: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" runtime = "cloudflare" // [!code ++] output = "../src/generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String // [!code ++] name String // [!code ++] } // [!code ++] ``` > [!NOTE] > Both the `cloudflare` and `workerd` runtimes are supported. Read more about runtimes [here](/orm/prisma-schema/overview/generators#field-reference). This creates a `User` model with an auto-incrementing ID, email, and name. 2.4. Configure Prisma scripts [#24-configure-prisma-scripts] Add the following scripts to your `package.json` to work with Prisma in the Cloudflare Workers environment: ```json title="package.json" { "scripts": { "migrate": "prisma migrate dev", // [!code ++] "generate": "prisma generate", // [!code ++] "studio": "prisma studio" // [!code ++] // ... existing scripts } } ``` 2.5. Run migrations and generate Prisma Client [#25-run-migrations-and-generate-prisma-client] Now, run the following command to create the database tables: #### npm ```bash npm run migrate ``` #### pnpm ```bash pnpm run migrate ``` #### yarn ```bash yarn migrate ``` #### bun ```bash bun run migrate ``` When prompted, name your migration (e.g., `init`). Then generate the Prisma Client: #### npm ```bash npm run generate ``` #### pnpm ```bash pnpm run generate ``` #### yarn ```bash yarn generate ``` #### bun ```bash bun run generate ``` This generates the Prisma Client in the `src/generated/prisma/client` directory. 3. Integrate Prisma into Cloudflare Workers [#3-integrate-prisma-into-cloudflare-workers] 3.1. Import Prisma Client and configure types [#31-import-prisma-client-and-configure-types] At the top of `src/index.ts`, import the generated Prisma Client and the PostgreSQL adapter, and define the `Env` interface for type-safe environment variables: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/prisma/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] export interface Env { // [!code ++] DATABASE_URL: string; // [!code ++] } // [!code ++] export default { async fetch(request, env, ctx): Promise { return new Response("Hello World!"); }, } satisfies ExportedHandler; ``` 3.2. Handle favicon requests [#32-handle-favicon-requests] Add a check to filter out favicon requests, which browsers automatically send and can clutter your logs: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; export interface Env { DATABASE_URL: string; } export default { async fetch(request, env, ctx): Promise { const path = new URL(request.url).pathname; // [!code ++] if (path === "/favicon.ico") // [!code ++] return new Response("Resource not found", { // [!code ++] status: 404, // [!code ++] headers: { // [!code ++] "Content-Type": "text/plain", // [!code ++] }, // [!code ++] }); // [!code ++] return new Response("Hello World!"); }, } satisfies ExportedHandler; ``` 3.3. Initialize the Prisma Client [#33-initialize-the-prisma-client] Create a database adapter and initialize Prisma Client with it. This must be done for each request in edge environments: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; export interface Env { DATABASE_URL: string; } export default { async fetch(request, env, ctx): Promise { const path = new URL(request.url).pathname; if (path === "/favicon.ico") return new Response("Resource not found", { status: 404, headers: { "Content-Type": "text/plain", }, }); const adapter = new PrismaPg({ // [!code ++] connectionString: env.DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const prisma = new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] return new Response("Hello World!"); }, } satisfies ExportedHandler; ``` > [!WARNING] > In edge environments like Cloudflare Workers, you create a new Prisma Client instance per request. This is different from long-running Node.js servers where you typically instantiate a single client and reuse it. 3.4. Create a user and query the database [#34-create-a-user-and-query-the-database] Now use Prisma Client to create a new user and count the total number of users: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; export interface Env { DATABASE_URL: string; } export default { async fetch(request, env, ctx): Promise { const path = new URL(request.url).pathname; if (path === "/favicon.ico") return new Response("Resource not found", { status: 404, headers: { "Content-Type": "text/plain", }, }); const adapter = new PrismaPg({ connectionString: env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); const user = await prisma.user.create({ // [!code ++] data: { // [!code ++] email: `Prisma-Postgres-User-${Math.ceil(Math.random() * 1000)}@gmail.com`, // [!code ++] name: "Jon Doe", // [!code ++] }, // [!code ++] }); // [!code ++] // [!code ++] const userCount = await prisma.user.count(); // [!code ++] return new Response("Hello World!"); }, } satisfies ExportedHandler; ``` 3.5. Return the results [#35-return-the-results] Finally, update the response to display the newly created user and the total user count: ```typescript title="src/index.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; export interface Env { DATABASE_URL: string; } export default { async fetch(request, env, ctx): Promise { const path = new URL(request.url).pathname; if (path === "/favicon.ico") return new Response("Resource not found", { status: 404, headers: { "Content-Type": "text/plain", }, }); const adapter = new PrismaPg({ connectionString: env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); const user = await prisma.user.create({ data: { email: `Prisma-Postgres-User-${Math.ceil(Math.random() * 1000)}@gmail.com`, name: "Jon Doe", }, }); const userCount = await prisma.user.count(); return new Response(`\ // [!code highlight] Created new user: ${user.name} (${user.email}). // [!code highlight] Number of users in the database: ${userCount}. // [!code highlight] `); // [!code highlight] }, } satisfies ExportedHandler; ``` 3.6. Test your Worker locally [#36-test-your-worker-locally] First, generate the TypeScript types for your Worker environment: #### npm ```bash npx wrangler types --no-strict-vars ``` #### pnpm ```bash pnpm dlx wrangler types --no-strict-vars ``` #### yarn ```bash yarn dlx wrangler types --no-strict-vars ``` #### bun ```bash bunx --bun wrangler types --no-strict-vars ``` Then start the development server: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` Open [`http://localhost:8787`](http://localhost:8787) in your browser. Each time you refresh the page, a new user will be created. You should see output similar to: ``` Created new user: Jon Doe (Prisma-Postgres-User-742@gmail.com). Number of users in the database: 5. ``` 3.7. Inspect your data with Prisma Studio [#37-inspect-your-data-with-prisma-studio] To view your database contents, open Prisma Studio: #### npm ```bash npm run studio ``` #### pnpm ```bash pnpm run studio ``` #### yarn ```bash yarn studio ``` #### bun ```bash bun run studio ``` This will open a browser window where you can view and edit your `User` table data. 4. Deploy to Cloudflare Workers [#4-deploy-to-cloudflare-workers] 4.1. Set your database URL as a secret [#41-set-your-database-url-as-a-secret] Before deploying, you need to set your `DATABASE_URL` as a secret in Cloudflare Workers. This keeps your database connection string secure in production. #### npm ```bash npx wrangler secret put DATABASE_URL ``` #### pnpm ```bash pnpm dlx wrangler secret put DATABASE_URL ``` #### yarn ```bash yarn dlx wrangler secret put DATABASE_URL ``` #### bun ```bash bunx --bun wrangler secret put DATABASE_URL ``` When prompted, paste your database connection string from the `.env` file. 4.2. Deploy your Worker [#42-deploy-your-worker] Deploy your Worker to Cloudflare: #### npm ```bash npm run deploy ``` #### pnpm ```bash pnpm run deploy ``` #### yarn ```bash yarn deploy ``` #### bun ```bash bun run deploy ``` Once deployed, Cloudflare will provide you with a URL where your Worker is live (e.g., `https://prisma-postgres-worker.your-subdomain.workers.dev`). Visit the URL in your browser, and you'll see your Worker creating users in production! Next steps [#next-steps] Now that you have a working Cloudflare Workers app connected to a Prisma Postgres database, you can: * Add routes to handle different HTTP methods (GET, POST, PUT, DELETE) * Extend your Prisma schema with more models and relationships * Implement authentication and authorization * Use [Hono](https://hono.dev/) for a more robust routing framework with Cloudflare Workers (see our [Hono guide](/guides/frameworks/hono)) * Use the [`@prisma/ppg` serverless driver](/postgres/database/serverless-driver) to connect over HTTP instead of TCP — no `nodejs_compat` flag needed * [Deploy to Cloudflare](/orm/prisma-client/deployment/edge/deploy-to-cloudflare) — deeper reference on edge deployment options * [Cloudflare Workers documentation](https://developers.cloudflare.com/workers/) * [Prisma ORM documentation](/orm) ## Related pages - [`Bun workspaces`](https://www.prisma.io/docs/guides/deployment/bun-workspaces): Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo to build scalable and modular applications efficiently - [`Cloudflare D1`](https://www.prisma.io/docs/guides/deployment/cloudflare-d1): Learn how to use Prisma ORM with Cloudflare D1 - [`Docker`](https://www.prisma.io/docs/guides/deployment/docker): Learn step-by-step configure a Prisma ORM app in Docker - [`pnpm workspaces`](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces): Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently - [`Turborepo`](https://www.prisma.io/docs/guides/deployment/turborepo): Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently # Docker (/docs/guides/deployment/docker) Location: Guides > Deployment > Docker 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 [#prerequisites] * [Docker](https://docs.docker.com/) and [Docker Compose](https://docs.docker.com/compose/) installed * Node.js version: A [compatible Node.js version](/guides/upgrade-prisma-orm/v6#minimum-supported-nodejs-versions), required for Prisma 6. See our [system requirements](/orm/reference/system-requirements) for all minimum version requirements. 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: ```bash sudo systemctl stop postgresql # Linux brew services stop postgresql # macOS net stop postgresql # Windows (Run as Administrator) ``` To stop all running Docker containers and free up ports: ```bash docker ps -q | xargs docker stop ``` 1. Set up your Node.js and Prisma application [#1-set-up-your-nodejs-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 [#11-initialize-your-project] First, create a new project directory and initialize a Node.js project: #### npm ```bash mkdir docker-test cd docker-test npm init ``` #### pnpm ```bash mkdir docker-test cd docker-test pnpm init ``` #### yarn ```bash mkdir docker-test cd docker-test yarn init ``` #### bun ```bash mkdir docker-test cd docker-test bun init ``` This will generate a `package.json` file: ```json title="package.json" { "name": "docker-test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {}, "keywords": [], "author": "", "license": "ISC" } ``` 1.2. Install required dependencies [#12-install-required-dependencies] Next, install the Prisma CLI as a development dependency and Express.js for the server: #### npm ```bash npm install prisma @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma @types/pg --save-dev ``` #### yarn ```bash yarn add prisma @types/pg --dev ``` #### bun ```bash bun add prisma @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg pg dotenv express ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg pg dotenv express ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg pg dotenv express ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg pg dotenv express ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). 1.3. Set up Prisma ORM [#13-set-up-prisma-orm] Now, initialize Prisma to generate the necessary files: #### npm ```bash npx prisma init --output ../generated/prisma ``` #### pnpm ```bash pnpm dlx prisma init --output ../generated/prisma ``` #### yarn ```bash yarn dlx prisma init --output ../generated/prisma ``` #### bun ```bash bunx --bun 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 title="prisma/schema.prisma" datasource db { provider = "postgresql" } generator client { provider = "prisma-client" output = "../generated/prisma_client" // [!code ++] } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] createdAt DateTime @default(now()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` > [!NOTE] > In the `schema.prisma` file, we specify a [custom `output` path](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider) 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. Now, create a `prisma.config.ts` file in the root of your project: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > You'll need to install the `dotenv` package to load environment variables: > > > > > #### npm > ```bash > npm install dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### bun > ```bash > bun add dotenv > ``` > > 1.4. Create an Express.js server [#14-create-an-expressjs-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: ```bash touch index.js ``` Add the following code to set up a basic Express server: ```js title="index.js" const express = require("express"); // [!code ++] const { PrismaClient } = require("./generated/prisma_client/client"); // [!code ++] const { PrismaPg } = require("@prisma/adapter-pg"); // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const app = express(); // [!code ++] const prisma = new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] app.use(express.json()); // [!code ++] // [!code ++] // Get all users // [!code ++] app.get("/", async (req, res) => { // [!code ++] const userCount = await prisma.user.count(); // [!code ++] res.json( // [!code ++] userCount == 0 // [!code ++] ? "No users have been added yet." // [!code ++] : "Some users have been added to the database.", // [!code ++] ); // [!code ++] }); // [!code ++] // [!code ++] const PORT = 3000; // [!code ++] // [!code ++] app.listen(PORT, () => { // [!code ++] console.log(`Server is running on http://localhost:${PORT}`); // [!code ++] }); // [!code ++] ``` Update the `package.json` scripts to include commands for running the server and deploying migrations: ```json title="package.json" "scripts": { "test": "echo \"Error: no test specified\" && exit 1", // [!code --] "dev": "node index.js", // [!code ++] "db:deploy": "npx prisma migrate deploy && npx prisma generate" // [!code ++] } ``` 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 [#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 [#21-create-a-docker-compose-file-for-postgresql] Create a `docker-compose.postgres.yml` file in the root directory: ```yml title="docker-compose.postgres.yml" version: '3.7' // [!code ++] // [!code ++] services: // [!code ++] postgres: // [!code ++] image: postgres:15 // [!code ++] restart: always // [!code ++] environment: // [!code ++] - POSTGRES_DB=postgres // [!code ++] - POSTGRES_USER=postgres // [!code ++] - POSTGRES_PASSWORD=prisma // [!code ++] ports: // [!code ++] - "5432:5432" // [!code ++] networks: // [!code ++] - prisma-network // [!code ++] healthcheck: // [!code ++] test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] // [!code ++] interval: 5s // [!code ++] timeout: 2s // [!code ++] retries: 20 // [!code ++] volumes: // [!code ++] - postgres_data:/var/lib/postgresql/data // [!code ++] command: postgres -c listen_addresses='*' // [!code ++] logging: // [!code ++] options: // [!code ++] max-size: "10m" // [!code ++] max-file: "3" // [!code ++] // [!code ++] networks: // [!code ++] prisma-network: // [!code ++] // [!code ++] volumes: // [!code ++] postgres_data: // [!code ++] ``` 2.2. Start the PostgreSQL container [#22-start-the-postgresql-container] Run the following command to start the database: ```bash docker compose -f docker-compose.postgres.yml up -d ``` 2.3. Perform database migrations [#23-perform-database-migrations] With the database running, update the `.env` file with the following database connection url: ```bash title=".env" DATABASE_URL="postgresql://postgres:prisma@localhost:5432/postgres?schema=public" # [!code highlight] ``` Run the migration to create the database schema: #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` Then generate Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` This should generate a `migrations` folder in the `prisma` folder and the Prisma Client in the `generated/prisma_client` directory. 2.4. Test the application [#24-test-the-application] Start the server and verify it works: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` Visit [`http://localhost:3000`](http://localhost:3000) to see the message: ```bash No users have been added yet. ``` Stop the local server. 2.5. Clean up the standalone database [#25-clean-up-the-standalone-database] Once testing is complete, remove the standalone PostgreSQL container: ```bash 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 [#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: ```bash 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 [#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`: ```shell title="Dockerfile" FROM node:lts-alpine3.17 WORKDIR /usr/src/app COPY package.json package-lock.json ./ RUN npm ci COPY . . 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 [#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`: ```shell title="Dockerfile" FROM node:slim RUN apt-get update -y \ && apt-get install -y openssl WORKDIR /usr/src/app COPY package.json package-lock.json ./ RUN npm ci COPY . . 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 [#32-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: ```bash touch docker-compose.yml ``` Add the following configuration to the file: ```yml title="docker-compose.yml" version: '3.7' // [!code ++] // [!code ++] services: // [!code ++] postgres_db: // [!code ++] image: postgres:15 // [!code ++] hostname: postgres_db // [!code ++] container_name: postgres_db // [!code ++] restart: always // [!code ++] environment: // [!code ++] POSTGRES_DB: postgres // [!code ++] POSTGRES_USER: postgres // [!code ++] POSTGRES_PASSWORD: prisma // [!code ++] ports: // [!code ++] - '5432:5432' // [!code ++] networks: // [!code ++] - prisma-network // [!code ++] healthcheck: // [!code ++] test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] // [!code ++] interval: 5s // [!code ++] timeout: 2s // [!code ++] retries: 20 // [!code ++] // [!code ++] server: // [!code ++] build: // [!code ++] context: . // [!code ++] dockerfile: Dockerfile // [!code ++] ports: // [!code ++] - '3000:3000' // [!code ++] stdin_open: true // [!code ++] tty: true # Keeps the container running for debugging // [!code ++] depends_on: // [!code ++] postgres_db: // [!code ++] condition: service_healthy // [!code ++] env_file: // [!code ++] - .env.prod // [!code ++] networks: // [!code ++] - prisma-network // [!code ++] networks: // [!code ++] prisma-network: // [!code ++] name: prisma-network // [!code ++] ``` 3.3. Configure environment variable for the container [#33-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: ```bash title=".env.prod" DATABASE_URL="postgresql://postgres:prisma@postgres_db:5432/postgres?schema=public" # [!code highlight] ``` 3.4. Build and run the application [#34-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: ```bash docker compose -f docker-compose.yml up --build -d ``` Visit `http://localhost:3000` to see your app running with the message: ```bash No users have been added yet. ``` 3.5. Bonus: Add Prisma Studio for database management [#35-bonus-add-prisma-studio-for-database-management] [Prisma Studio](/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: ```yml title="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: // [!code ++] image: node:lts-alpine3.17 // [!code ++] working_dir: /usr/src/app // [!code ++] volumes: // [!code ++] - .:/usr/src/app // [!code ++] command: npx prisma studio --port 5555 --browser none // [!code ++] ports: // [!code ++] - "5555:5555" // [!code ++] env_file: // [!code ++] - .env.prod // [!code ++] networks: // [!code ++] - prisma-network // [!code ++] depends_on: // [!code ++] postgres_db: // [!code ++] condition: service_healthy // [!code ++] server: // [!code ++] condition: service_started // [!code ++] networks: 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: ```bash 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. ## Related pages - [`Bun workspaces`](https://www.prisma.io/docs/guides/deployment/bun-workspaces): Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo to build scalable and modular applications efficiently - [`Cloudflare D1`](https://www.prisma.io/docs/guides/deployment/cloudflare-d1): Learn how to use Prisma ORM with Cloudflare D1 - [`Cloudflare Workers`](https://www.prisma.io/docs/guides/deployment/cloudflare-workers): Learn how to use Prisma ORM and Prisma Postgres in a Cloudflare Workers project - [`pnpm workspaces`](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces): Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently - [`Turborepo`](https://www.prisma.io/docs/guides/deployment/turborepo): Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently # pnpm workspaces (/docs/guides/deployment/pnpm-workspaces) Location: Guides > Deployment > pnpm workspaces Prisma is a powerful ORM for managing your database, and when combined with [pnpm Workspaces](https://pnpm.io/workspaces), you can maintain a lean and modular monorepo architecture. In this guide, we’ll walk through setting up Prisma in its own package within a pnpm Workspaces monorepo, enabling maintainable type sharing and efficient database management across your apps. What you'll learn: [#what-youll-learn] * How to initialize a monorepo using pnpm Workspaces. * Steps to integrate Prisma as a standalone package. * How to generate and share the Prisma Client across packages. * Integrating the Prisma package into an application within your workspace. 1. Prepare your project and configure pnpm workspaces [#1-prepare-your-project-and-configure-pnpm-workspaces] Before integrating Prisma, you need to set up your project structure. Start by creating a new directory for your project (for example, `my-monorepo`) and initialize a Node.js project: ```bash mkdir my-monorepo cd my-monorepo pnpm init ``` Next, create a `pnpm-workspace.yaml` file to define your workspace structure and pin the Prisma version: ```bash touch pnpm-workspace.yaml ``` Add the following configuration to `pnpm-workspace.yaml`: ```yaml title="pnpm-workspace.yaml" packages: - "apps/*" - "packages/*" catalogs: prisma: prisma: latest ``` > [!NOTE] > The `catalogs` help you pin a certain version of prisma across your repositories. You can learn more about them [here](https://pnpm.io/catalogs). *Explicitly* pin the latest version of [prisma](https://www.npmjs.com/package/prisma) in the `pnpm-workspace.yaml` file. At the time of writing, this is version `6.3.1`. Finally, create directories for your applications and shared packages: ```bash mkdir apps mkdir -p packages/database ``` 2. Setup the shared database package [#2-setup-the-shared-database-package] This section covers creating a standalone database package that uses Prisma. The package will house all database models and the generated Prisma Client, making it reusable across your monorepo. 2.1. Initialize the package and install dependencies [#21-initialize-the-package-and-install-dependencies] Navigate to the `packages/database` directory and initialize a new package: ```bash cd packages/database pnpm init ``` Add Prisma as a development dependency in your `package.json` using the pinned `catalog`: ```json title="database/package.json" "devDependencies": { // [!code ++] "prisma": "catalog:prisma" // [!code ++] } // [!code ++] ``` Then install Prisma: ```bash pnpm install ``` Then, add additional dependencies: ```bash pnpm add typescript tsx @types/node @types/pg -D pnpm add @prisma/adapter-pg pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Initialize a `tsconfig.json` file for your `database` package: ```bash pnpm tsc --init ``` 2.2. Setup Prisma ORM in your database package [#22-setup-prisma-orm-in-your-database-package] Initialize Prisma ORM with an instance of [Prisma Postgres](/postgres) in the `database` package by running the following command: ```bash pnpm dlx prisma init ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This command: * Creates a `prisma` directory containing a `schema.prisma` file for your database models. * Creates a `.env` file with a local `DATABASE_URL`. Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: ```bash npx create-db ``` Edit the `schema.prisma` file to define a `User` model in your database and specify a [custom `output` directory](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider) to generate the Prisma Client. This ensures that generated types are resolved correctly: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/client" // [!code ++] } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` Now, create a `prisma.config.ts` file in the `database` package to configure Prisma: ```typescript title="database/prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; // [!code ++] // [!code ++] export default defineConfig({ // [!code ++] schema: "prisma/schema.prisma", // [!code ++] migrations: { // [!code ++] path: "prisma/migrations", // [!code ++] }, // [!code ++] datasource: { // [!code ++] url: env("DATABASE_URL"), // [!code ++] }, // [!code ++] }); // [!code ++] ``` > [!NOTE] > You'll need to install the `dotenv` package to load environment variables from the `.env` file: > > ```bash > pnpm add dotenv > ``` Next, add helper scripts to your `package.json` to simplify Prisma commands: ```json title="database/package.json" { "scripts": { "test": "echo \"Error: no test specified\" && exit 1", // [!code --] "db:generate": "prisma generate", // [!code ++] "db:migrate": "prisma migrate dev", // [!code ++] "db:deploy": "prisma migrate deploy", // [!code ++] "db:studio": "prisma studio" // [!code ++] } } ``` Use [Prisma Migrate](/orm/prisma-migrate) to migrate your database changes: ```bash pnpm run db:migrate ``` When prompted by the CLI, enter a descriptive name for your migration. Once the migration is successful, create a `client.ts` file to initialize Prisma Client with a driver adapter: ```ts title="database/client.ts" import { PrismaClient } from "./generated/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] // Use globalThis for broader environment compatibility // [!code ++] const globalForPrisma = globalThis as typeof globalThis & { // [!code ++] prisma?: PrismaClient; // [!code ++] }; // [!code ++] // [!code ++] // Named export with global memoization // [!code ++] export const prisma: PrismaClient = // [!code ++] globalForPrisma.prisma ?? new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") { // [!code ++] globalForPrisma.prisma = prisma; // [!code ++] } // [!code ++] ``` Then, create an `index.ts` file to re-export the instance of Prisma Client and all generated types: ```ts title="database/index.ts" export { prisma } from "./client"; // [!code ++] export * from "./generated/client"; // [!code ++] ``` At this point, your shared database package is fully configured and ready for use across your monorepo. 3. Set up and integrate your frontend application [#3-set-up-and-integrate-your-frontend-application] Now that the database package is set up, create a frontend application (using Next.js) that uses the shared Prisma Client to interact with your database. 3.1. Bootstrap a Next.js application [#31-bootstrap-a-nextjs-application] Navigate to the `apps` directory: ```bash cd ../../apps ``` Create a new Next.js app named `web`: ```bash pnpm create next-app@latest web --yes ``` > [!NOTE] > important > > The `--yes` flag uses default configurations to bootstrap the Next.js app (which in this guide uses the app router without a `src/` directory and `pnpm` as the installer). > > Additionally, the flag may automatically initialize a Git repository in the `web` folder. If that happens, please remove the `.git` directory by running `rm -r .git`. Then, navigate into the web directory: ```bash cd web/ ``` Copy the `.env` file from the database package to ensure the same environment variables are available: ```bash cp ../../packages/database/.env . ``` Open the `package.json` file of your Next.js app and add the shared `database` package as a dependency: ```json title="web/package.json" "dependencies": { "database": "workspace:*", // [!code ++] // additional dependencies // ... } ``` Run the following command to install the `database` package: ```bash pnpm install ``` 3.2. Integrate the shared database package in your app code [#32-integrate-the-shared-database-package-in-your-app-code] Modify your Next.js application code to use Prisma Client from the database package. Update `app/page.tsx` as follows: ```tsx title="app/page.tsx" import { prisma } from "database"; // [!code ++] // [!code ++] export default async function Home() { // [!code ++] const user = await prisma.user.findFirst({ // [!code ++] select: { // [!code ++] name: true, // [!code ++] }, // [!code ++] }); // [!code ++] // [!code ++] return ( // [!code ++]
{" "} // [!code ++] {user?.name &&

Hello from {user.name}

} // [!code ++] {!user?.name &&

No user has been added to the database yet.

} // [!code ++]
// [!code ++] ); // [!code ++] } // [!code ++] ``` This code demonstrates importing and using the shared Prisma Client to query your `User` model. 3.3. Add helper scripts and run your application [#33-add-helper-scripts-and-run-your-application] Add the following scripts to the root `package.json` of your monorepo. They ensure that database migrations, type generation, and app builds run in the proper order: ```json "scripts": { "build": "pnpm --filter database db:deploy && pnpm --filter database db:generate && pnpm --filter web build", // [!code ++] "start": "pnpm --filter web start", // [!code ++] "dev": "pnpm --filter database db:generate && pnpm --filter web dev", // [!code ++] "studio": "pnpm --filter database db:studio" // [!code ++] } ``` 3.4. Run your application [#34-run-your-application] Then head back to the root of the monorepo: ```bash cd ../../ ``` Start your development server by executing: ```bash pnpm run dev ``` Open your browser at [`http://localhost:3000`](http://localhost:3000) to see your app in action. 3.5. (Optional) Add data to your database using Prisma Studio [#35-optional-add-data-to-your-database-using-prisma-studio] There shouldn't be data in your database yet. You can execute `pnpm run studio` in your CLI to start a [Prisma Studio](/studio) in [`http://localhost:5555`](http://localhost:5555) to interact with your database and add data to it. Next Steps [#next-steps] You have now created a monorepo that uses Prisma ORM effectively, with a shared database package integrated into a Next.js application. For further exploration and to enhance your setup, consider reading the [How to use Prisma ORM with Turborepo](/guides/deployment/turborepo) guide. ## Related pages - [`Bun workspaces`](https://www.prisma.io/docs/guides/deployment/bun-workspaces): Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo to build scalable and modular applications efficiently - [`Cloudflare D1`](https://www.prisma.io/docs/guides/deployment/cloudflare-d1): Learn how to use Prisma ORM with Cloudflare D1 - [`Cloudflare Workers`](https://www.prisma.io/docs/guides/deployment/cloudflare-workers): Learn how to use Prisma ORM and Prisma Postgres in a Cloudflare Workers project - [`Docker`](https://www.prisma.io/docs/guides/deployment/docker): Learn step-by-step configure a Prisma ORM app in Docker - [`Turborepo`](https://www.prisma.io/docs/guides/deployment/turborepo): Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently # Turborepo (/docs/guides/deployment/turborepo) Location: Guides > Deployment > Turborepo Prisma is a powerful ORM for managing databases, and [Turborepo](https://turborepo.dev/docs) simplifies monorepo workflows. By combining these tools, you can create a scalable, modular architecture for your projects. This guide will show you how to set up Prisma as a standalone package in a Turborepo monorepo, enabling efficient configuration, type sharing, and database management across multiple apps. What you'll learn: [#what-youll-learn] * How to set up Prisma in a Turborepo monorepo. * Steps to generate and reuse PrismaClient across packages. * Integrating the Prisma package into other applications in the monorepo. Prerequisites [#prerequisites] * [Node.js 20.19.0+](https://nodejs.org/) * [TypeScript 5.4.0+](https://www.typescriptlang.org/) 1. Set up your project [#1-set-up-your-project] To set up a Turborepo monorepo named `turborepo-prisma`, run the following command: #### npm ```bash npx create-turbo@latest turborepo-prisma ``` #### pnpm ```bash pnpm dlx create-turbo@latest turborepo-prisma ``` #### yarn ```bash yarn dlx create-turbo@latest turborepo-prisma ``` #### bun ```bash bunx --bun create-turbo@latest turborepo-prisma ``` You'll be prompted to select your package manager, this guide will use `npm`: > [!NOTE] > * *Which package manager do you want to use?* `npm` After the setup, navigate to the project root directory: ```bash cd turborepo-prisma ``` 2. Add a new database package to the monorepo [#2-add-a-new-database-package-to-the-monorepo] 2.1 Create the package and install Prisma [#21-create-the-package-and-install-prisma] Create a `database` directory inside `packages` and navigate into it: ```bash mkdir -p packages/database cd packages/database ``` Then initialize it with a `package.json`: ```json title="packages/database/package.json" { "name": "@repo/db", "version": "0.0.0" } ``` Then install the required Prisma ORM dependencies: #### npm ```bash npm install prisma --save-dev npm install @prisma/client @prisma/adapter-pg pg dotenv ``` #### pnpm ```bash pnpm add prisma --save-dev pnpm add @prisma/client @prisma/adapter-pg pg dotenv ``` #### yarn ```bash yarn add prisma --dev yarn add @prisma/client @prisma/adapter-pg pg dotenv ``` #### bun ```bash bun add prisma --dev bun add @prisma/client @prisma/adapter-pg pg dotenv ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). 2.2. Initialize Prisma and define models [#22-initialize-prisma-and-define-models] Inside the `database` directory, initialize Prisma by running: #### npm ```bash npx prisma init ``` #### pnpm ```bash pnpm dlx prisma init ``` #### yarn ```bash yarn dlx prisma init ``` #### bun ```bash bunx --bun prisma init ``` This will create several files inside `packages/database`: * A `prisma` directory with a `schema.prisma` file. * A `prisma.config.ts` file for configuring Prisma. * A `.env` file containing a local `DATABASE_URL` in the `packages/database` directory. Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: ```bash npx create-db ``` In the `packages/database/prisma/schema.prisma` file, add the following models: ```prisma title="packages/database/prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] posts Post[] // [!code ++] } // [!code ++] // [!code ++] model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] published Boolean @default(false) // [!code ++] authorId Int // [!code ++] author User @relation(fields: [authorId], references: [id]) // [!code ++] } // [!code ++] ``` The `prisma.config.ts` file created in the `packages/database` directory should look like this: ```typescript title="packages/database/prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!WARNING] > It is recommended to add `packages/database/generated` to your root `.gitignore` because generated Prisma Client code is a build artifact that can be recreated with `db:generate`. The importance of generating Prisma types in a custom directory [#the-importance-of-generating-prisma-types-in-a-custom-directory] In the `schema.prisma` file, we specify a custom [`output`](/orm/reference/prisma-schema-reference#fields-for-prisma-client-provider) path where Prisma will generate its types. This ensures Prisma's types are resolved correctly across different package managers. > [!NOTE] > In this guide, the types will be generated in the `database/generated/prisma` directory. 2.3. Add scripts and run migrations [#23-add-scripts-and-run-migrations] Let's add some scripts to the `package.json` inside `packages/database`: ```json title="packages/database/package.json" { "name": "@repo/db", "version": "0.0.0", "type": "module", // [!code ++] "scripts": { // [!code ++] "db:generate": "prisma generate", // [!code ++] "db:migrate": "prisma migrate dev", // [!code ++] "db:deploy": "prisma migrate deploy" // [!code ++] }, // [!code ++] "devDependencies": { "prisma": "^7.0.0" }, "dependencies": { "@prisma/client": "^7.0.0", "@prisma/adapter-pg": "^7.0.0", "pg": "^8.0.0", "dotenv": "^16.0.0" } } ``` Let's also add these scripts to `turbo.json` in the root and ensure that `DATABASE_URL` is added to the environment: ```json title="turbo.json" { "$schema": "https://turborepo.dev/schema.json", "ui": "tui", "globalEnv": ["DATABASE_URL"], // [!code ++] "tasks": { "build": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": [".next/**", "!.next/cache/**"] }, "lint": { "dependsOn": ["^lint"] }, "check-types": { "dependsOn": ["^check-types"] }, "dev": { "cache": false, "persistent": true }, "db:generate": { // [!code ++] "cache": false // [!code ++] }, // [!code ++] "db:migrate": { // [!code ++] "cache": false // [!code ++] }, // [!code ++] "db:deploy": { // [!code ++] "cache": false // [!code ++] } // [!code ++] } } ``` Run your first migration and generate Prisma Client Navigate to the project root and run the following command to create and apply your first migration: #### npm ```bash npx turbo run db:migrate -- --name init ``` #### pnpm ```bash pnpm dlx turbo run db:migrate -- --name init ``` #### yarn ```bash yarn dlx turbo run db:migrate -- --name init ``` #### bun ```bash bunx --bun turbo run db:migrate -- --name init ``` In Prisma 7, `migrate dev` no longer runs `prisma generate` automatically, so run generate explicitly: #### npm ```bash npx turbo run db:generate ``` #### pnpm ```bash pnpm dlx turbo run db:generate ``` #### yarn ```bash yarn dlx turbo run db:generate ``` #### bun ```bash bunx --bun turbo run db:generate ``` Use the same `npx turbo run db:generate` command after future schema changes. 2.4. Export the Prisma client and types [#24-export-the-prisma-client-and-types] Next, export the generated types and an instance of `PrismaClient` so it can be used in your applications. In the `packages/database` directory, create a `src` folder and add a `client.ts` file. This file will define an instance of `PrismaClient`: ```ts title="packages/database/src/client.ts" import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }; export const prisma = globalForPrisma.prisma || new PrismaClient({ adapter, }); if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; ``` Then create an `index.ts` file in the `src` folder to re-export the generated prisma types and the `PrismaClient` instance: ```ts title="packages/database/src/index.ts" export { prisma } from "./client"; // exports instance of prisma export * from "../generated/prisma/client"; // exports generated types from prisma ``` Follow the [Just-in-Time packaging pattern](https://turborepo.dev/docs/core-concepts/internal-packages#just-in-time-packages) and create an entrypoint to the package inside `packages/database/package.json`: > [!WARNING] > If you're not using a bundler, use the [Compiled Packages](https://turborepo.dev/docs/core-concepts/internal-packages#compiled-packages) strategy instead. ```json title="packages/database/package.json" { "name": "@repo/db", "version": "0.0.0", "type": "module", "scripts": { "db:generate": "prisma generate", "db:migrate": "prisma migrate dev", "db:deploy": "prisma migrate deploy" }, "devDependencies": { "prisma": "^7.0.0" }, "dependencies": { "@prisma/client": "^7.0.0", "@prisma/adapter-pg": "^7.0.0", "pg": "^8.0.0", "dotenv": "^16.0.0" }, "exports": { // [!code ++] ".": "./src/index.ts" // [!code ++] } // [!code ++] } ``` By completing these steps, you'll make the Prisma types and `PrismaClient` instance accessible throughout the monorepo. 3. Import the database package in the web app [#3-import-the-database-package-in-the-web-app] The `turborepo-prisma` project should have an app called `web` at `apps/web`. Add the `database` dependency to `apps/web/package.json`: #### npm ```json { // ... "dependencies": { "@repo/db": "*" // [!code ++] // ... } // ... } ``` #### pnpm ```json { // ... "dependencies": { "@repo/db": "workspace:*" // [!code ++] // ... } // ... } ``` #### bun ```json { // ... "dependencies": { "@repo/db": "workspace:*" // [!code ++] // ... } // ... } ``` Run your package manager's install command from the project root to link the workspace dependency: #### npm ```bash npm install ``` #### pnpm ```bash pnpm install ``` #### yarn ```bash yarn install ``` #### bun ```bash bun install ``` Let's import the instantiated `prisma` client from the `database` package in the `web` app. In the `apps/web/app` directory, open the `page.tsx` file and add the following code: ```tsx title="apps/web/app/page.tsx" import styles from "./page.module.css"; import { prisma } from "@repo/db"; export default async function Home() { const user = await prisma.user.findFirst(); return
{user?.name ?? "No user added yet"}
; } ``` Then, create a `.env` file in the `web` directory and copy into it the contents of the `.env` file from the `/database` directory containing the `DATABASE_URL`: ```text title="apps/web/.env" DATABASE_URL="Same database URL as used in the database directory" ``` > [!NOTE] > If you want to use a single `.env` file in the root directory across your apps and packages in a Turborepo setup, consider using a package like [`dotenvx`](https://dotenvx.com/docs/monorepos/turborepo). > > To implement this, update the `package.json` files for each package or app to ensure they load the required environment variables from the shared `.env` file. For detailed instructions, refer to the [`dotenvx` guide for Turborepo](https://dotenvx.com/docs/monorepos/turborepo). > > Keep in mind that Turborepo [recommends using separate `.env` files for each package](https://turborepo.dev/docs/crafting-your-repository/using-environment-variables#use-env-files-in-packages) to promote modularity and avoid potential conflicts. 4. Configure task dependencies in Turborepo [#4-configure-task-dependencies-in-turborepo] The `db:generate` script is essential for `dev` and `build` tasks in a monorepo setup. If a new developer runs `turbo dev` on an application without first running `db:generate`, they will encounter errors. To prevent this, ensure that `db:generate` is always executed before running `dev` or `build`. Keep `db:deploy` uncached for staging/production migration runs in CI. Here's how to configure this in your `turbo.json` file: ```json title="turbo.json" { "$schema": "https://turborepo.dev/schema.json", "ui": "tui", "globalEnv": ["DATABASE_URL"], "tasks": { "build": { "dependsOn": ["^build", "^db:generate"], // [!code highlight] "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": [".next/**", "!.next/cache/**"] }, "lint": { "dependsOn": ["^lint"] }, "check-types": { "dependsOn": ["^check-types"] }, "dev": { "dependsOn": ["^db:generate"], // [!code ++] "cache": false, "persistent": true }, "db:generate": { "cache": false }, "db:migrate": { "cache": false }, "db:deploy": { "cache": false } } } ``` 5. Run the project in development [#5-run-the-project-in-development] Then from the project root run the project: #### npm ```bash npx turbo run dev --filter=web ``` #### pnpm ```bash pnpm dlx turbo run dev --filter=web ``` #### yarn ```bash yarn dlx turbo run dev --filter=web ``` #### bun ```bash bunx --bun turbo run dev --filter=web ``` Navigate to the `http://localhost:3000` and you should see the message: ``` No user added yet ``` > [!NOTE] > You can add users to your database by creating a seed script or manually by using [Prisma Studio](/studio). > > To use Prisma Studio to add manually data via a GUI, navigate inside the `packages/database` directory and run `prisma studio` using your package manager: > > > > > #### npm > ```bash > npx prisma studio > ``` > > > #### pnpm > ```bash > pnpm dlx prisma studio > ``` > > > #### yarn > ```bash > yarn dlx prisma studio > ``` > > > #### bun > ```bash > bunx --bun prisma studio > ``` > > > > This command starts a server with a GUI at [http://localhost:5555](http://localhost:5555), allowing you to view and modify your data. Congratulations, you're done setting up Prisma for Turborepo! Next Steps [#next-steps] * Expand your Prisma models to handle more complex data relationships. * Implement additional CRUD operations to enhance your application's functionality. * Check out [Prisma Postgres](https://www.prisma.io/postgres) to see how you can scale your application. More Info [#more-info] * [Turborepo Docs](https://turborepo.dev/docs) * [Next.js Docs](https://nextjs.org/docs) * [Prisma ORM Docs](/orm) ## Related pages - [`Bun workspaces`](https://www.prisma.io/docs/guides/deployment/bun-workspaces): Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo to build scalable and modular applications efficiently - [`Cloudflare D1`](https://www.prisma.io/docs/guides/deployment/cloudflare-d1): Learn how to use Prisma ORM with Cloudflare D1 - [`Cloudflare Workers`](https://www.prisma.io/docs/guides/deployment/cloudflare-workers): Learn how to use Prisma ORM and Prisma Postgres in a Cloudflare Workers project - [`Docker`](https://www.prisma.io/docs/guides/deployment/docker): Learn step-by-step configure a Prisma ORM app in Docker - [`pnpm workspaces`](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces): Learn step-by-step how to integrate Prisma ORM in a pnpm workspaces monorepo to build scalable and modular applications efficiently # Astro (/docs/guides/frameworks/astro) Location: Guides > Frameworks > Astro Introduction [#introduction] Prisma ORM offers type-safe database access, and [Astro](https://astro.build/) is built for performance. Together with [Prisma Postgres](https://www.prisma.io/postgres), you get a fast, content-first stack with zero cold starts and end-to-end speed. In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in an Astro project from scratch. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/astro). Quick start [#quick-start] Run one command to scaffold an Astro project with Prisma ORM and Prisma Postgres ready to go: #### npm ```bash npm create prisma@latest -- --template astro ``` #### pnpm ```bash pnpm create prisma@latest --template astro ``` #### yarn ```bash yarn create prisma@latest --template astro ``` #### bun ```bash bun create prisma@latest --template astro ``` Or follow the steps below to set it up manually. Prerequisites [#prerequisites] * [Node.js 20+](https://nodejs.org) * [Astro VSCode extension (recommended)](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode) 1. Set up your project [#1-set-up-your-project] Create a new Astro project: #### npm ```bash npx create-astro@latest ``` #### pnpm ```bash pnpm dlx create-astro@latest ``` #### yarn ```bash yarn dlx create-astro@latest ``` #### bun ```bash bunx --bun create-astro@latest ``` > [!NOTE] > * *Where should we create your new project?* `astro-prisma` > * *How would you like to start your new project?* `Use minimal (empty) template ` > * *Install dependencies? (recommended)* `Yes` > * *Initialize a new git repository? (optional)* `Yes` Navigate into the newly created project directory: ```bash cd astro-prisma ``` 2. Install and Configure Prisma [#2-install-and-configure-prisma] 2.1. Install dependencies [#21-install-dependencies] To get started with Prisma, you'll need to install a few dependencies: #### npm ```bash npm install prisma tsx @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma tsx @types/pg --dev ``` #### bun ```bash bun add prisma tsx @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg dotenv pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: #### npm ```bash npx prisma init --output ../prisma/generated ``` #### pnpm ```bash pnpm dlx prisma init --output ../prisma/generated ``` #### yarn ```bash yarn dlx prisma init --output ../prisma/generated ``` #### bun ```bash bunx --bun prisma init --output ../prisma/generated ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma/` directory with a `schema.prisma` file * A `prisma.config.ts` file for configuring Prisma * A `.env` file with a local `DATABASE_URL` already set Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.2. Define your Prisma Schema [#22-define-your-prisma-schema] In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../prisma/generated" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] posts Post[] // [!code ++] } // [!code ++] // [!code ++] model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] published Boolean @default(false) // [!code ++] authorId Int // [!code ++] author User @relation(fields: [authorId], references: [id]) // [!code ++] } // [!code ++] ``` This creates two models: `User` and `Post`, with a one-to-many relationship between them. 2.3 Add dotenv to prisma.config.ts [#23-add-dotenv-to-prismaconfigts] To get access to the variables in the `.env` file, they can either be loaded by your runtime, or by using `dotenv`. Include an import for `dotenv` at the top of the `prisma.config.ts` ```ts import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 2.4. Run migrations and generate Prisma Client [#24-run-migrations-and-generate-prisma-client] Now, run the following command to create the database tables: #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` Then generate Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 2.5. Seed the database [#25-seed-the-database] Let's add some seed data to populate the database with sample users and posts. Create a new file called `seed.ts` in the `prisma/` directory: ```typescript title="prisma/seed.ts" import { PrismaClient, Prisma } from "../prisma/generated/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter, }); 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() { console.log("Starting to seed..."); for (const u of userData) { await prisma.user.upsert({ where: { email: u.email }, update: {}, create: u, }); } console.log("Seeding finished."); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Now, tell Prisma how to run this script by updating your `prisma.config.ts`: ```ts title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", seed: `tsx prisma/seed.ts`, }, datasource: { url: env("DATABASE_URL"), }, }); ``` Run the seed script: #### npm ```bash npx prisma db seed ``` #### pnpm ```bash pnpm dlx prisma db seed ``` #### yarn ```bash yarn dlx prisma db seed ``` #### bun ```bash bunx --bun prisma db seed ``` And open Prisma Studio to inspect your data: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` 3. Integrate Prisma into Astro [#3-integrate-prisma-into-astro] 3.1. Create TypeScript environment definitions [#31-create-typescript-environment-definitions] First, create an `env.d.ts` file in your `src` directory to provide TypeScript definitions for environment variables: ```typescript title="src/env.d.ts" interface ImportMetaEnv { readonly DATABASE_URL: string; } interface ImportMeta { readonly env: ImportMetaEnv; } ``` 3.2. Create a Prisma Client [#32-create-a-prisma-client] Inside of `/src`, create a `lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. ```bash mkdir src/lib touch src/lib/prisma.ts ``` Set up the Prisma client like this: ```typescript title="src/lib/prisma.ts" import { PrismaClient } from "../../prisma/generated/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: import.meta.env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); export default prisma; ``` > [!WARNING] > We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently. > > If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections. 3.3. Create an API route [#33-create-an-api-route] An API route is the best way to fetch data from your database in an Astro app. Create a new file called `api/users.ts` in the `src/pages` directory: ```bash mkdir src/pages/api touch src/pages/api/users.ts ``` Now, create a GET route that fetches the `Users` data from your database, making sure to include each user's `Posts` by adding them to the `include` field: ```typescript title="src/pages/api/users.ts" import type { APIRoute } from "astro"; import prisma from "../../lib/prisma"; export const GET: APIRoute = async () => { const users = await prisma.user.findMany({ include: { posts: true }, }); return new Response(JSON.stringify(users), { headers: { "Content-Type": "application/json" }, }); }; ``` 3.4. Fetch the data from the API route (Recommended Method) [#34-fetch-the-data-from-the-api-route-recommended-method] Instead of using `fetch()` with HTTP requests, Astro recommends importing endpoint functions directly. This approach is more efficient and avoids URL parsing issues. Start by creating a new type that combines the `User` and `Post` models called `UserWithPosts`: ```tsx title="src/pages/index.astro" --- import type { User, Post } from "../../prisma/generated/client"; // [!code ++] import { GET } from "./api/users.ts"; // [!code ++] // [!code ++] type UserWithPosts = User & { posts: Post[] }; // [!code ++] // [!code ++] const response = await GET(Astro); // [!code ++] const users: UserWithPosts[] = await response.json(); // [!code ++] --- Astro + Prisma

Astro + Prisma

    // [!code ++] {users.map((user: UserWithPosts) => ( // [!code ++]
  • // [!code ++]

    {user.name}

    // [!code ++]
      // [!code ++] {user.posts.map((post: Post) => ( // [!code ++]
    • {post.title}
    • // [!code ++] ))} // [!code ++]
    // [!code ++]
  • // [!code ++] ))} // [!code ++]
// [!code ++] ``` 3.5. Run your app [#35-run-your-app] Now start your development server to see your Astro app in action: #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` Open your browser at [`http://localhost:4321`](http://localhost:4321) to see the users and their posts displayed on the page. Summary [#summary] You're done! You've just created an Astro app with Prisma that's connected to a Prisma Postgres database. Below are some next steps to explore, as well as some more resources to help you get started expanding your project. Next Steps [#next-steps] Now that you have a working Astro 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 More Info [#more-info] * [Prisma Documentation](/orm) * [Astro Documentation](https://astro.build/docs) ## Related pages - [`Elysia`](https://www.prisma.io/docs/guides/frameworks/elysia): Learn how to use Prisma ORM in an Elysia app - [`Hono`](https://www.prisma.io/docs/guides/frameworks/hono): Learn how to use Prisma ORM in a Hono app - [`NestJS`](https://www.prisma.io/docs/guides/frameworks/nestjs): Learn how to use Prisma ORM in a NestJS app - [`Next.js`](https://www.prisma.io/docs/guides/frameworks/nextjs): Learn how to use Prisma ORM in a Next.js app and deploy it to Vercel - [`Nuxt`](https://www.prisma.io/docs/guides/frameworks/nuxt): A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app # Elysia (/docs/guides/frameworks/elysia) Location: Guides > Frameworks > Elysia Introduction [#introduction] [Elysia](https://elysiajs.com/) is an ergonomic web framework for building high-performance backend servers with Bun. It offers end-to-end type safety, an expressive API, and exceptional performance. Combined with Prisma ORM and [Prisma Postgres](https://www.prisma.io/postgres), you get a fast, type-safe backend stack. In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in an Elysia application. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/elysia). Quick start [#quick-start] Run one command to scaffold an Elysia project with Prisma ORM and Prisma Postgres ready to go: #### npm ```bash npm create prisma@latest -- --template elysia ``` #### pnpm ```bash pnpm create prisma@latest --template elysia ``` #### yarn ```bash yarn create prisma@latest --template elysia ``` #### bun ```bash bun create prisma@latest --template elysia ``` Or follow the steps below to set it up manually. Prerequisites [#prerequisites] * [Bun](https://bun.sh/docs/installation) installed on your system 1. Set up your project [#1-set-up-your-project] Create a new Elysia project using the Bun scaffolding command: ```bash bun create elysia elysia-prisma ``` Navigate to the project directory: ```bash cd elysia-prisma ``` 2. Install and configure Prisma [#2-install-and-configure-prisma] 2.1. Install dependencies [#21-install-dependencies] Install the required Prisma packages, database adapter, and Prismabox (for generated TypeBox schemas): ```bash bun add -d prisma bun-types bun add @prisma/client @prisma/adapter-pg pg prismabox ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: ```bash bunx --bun prisma init --output ../src/generated/prisma ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma/` directory with a `schema.prisma` file * A `prisma.config.ts` file for configuring Prisma * A `.env` file with a local `DATABASE_URL` already set Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.2. Define your Prisma Schema [#22-define-your-prisma-schema] In the `prisma/schema.prisma` file, mirror the example app structure with Prismabox TypeBox generators and a `Todo` model: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../src/generated/prisma" } generator prismabox { provider = "prismabox" typeboxImportDependencyName = "elysia" typeboxImportVariableName = "t" inputModel = true output = "../src/generated/prismabox" } datasource db { provider = "postgresql" } model Todo { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] completed Boolean @default(false) // [!code ++] createdAt DateTime @default(now()) // [!code ++] updatedAt DateTime @updatedAt // [!code ++] } // [!code ++] ``` This matches the Prisma Elysia example: it generates Prisma Client to `src/generated/prisma` and Prismabox TypeBox schemas to `src/generated/prismabox`. What is Prismabox? [#what-is-prismabox] * A Prisma generator that reads your Prisma schema and emits Elysia-friendly TypeBox models. * Generates files like `src/generated/prismabox/Todo.ts` (and one per model) with `TodoPlain`, `TodoPlainInputCreate`, etc. * Use those generated models in routes to validate requests/responses and keep Elysia types in sync with your Prisma schema (also useful for OpenAPI/Eden). 2.3. Run migrations and generate Prisma Client [#23-run-migrations-and-generate-prisma-client] Run the following commands to create the database tables and generate the Prisma Client: ```bash bunx --bun prisma migrate dev --name init bunx --bun prisma generate ``` 2.4. Seed the database [#24-seed-the-database] Add some seed data to populate the database with sample todos (mirrors the example repo). Create a new file called `seed.ts` in the `prisma/` directory: ```typescript title="prisma/seed.ts" import { PrismaClient } from "../src/generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; if (!process.env.DATABASE_URL) { throw new Error("DATABASE_URL is not set"); } const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }); const prisma = new PrismaClient({ adapter }); const todoData = [ { title: "Learn Elysia" }, { title: "Learn Prisma" }, { title: "Build something awesome", completed: true }, ]; async function main() { console.log("Start seeding..."); for (const todo of todoData) { const created = await prisma.todo.create({ data: todo, }); console.log(`Created todo with id: ${created.id}`); } console.log("Seeding finished."); } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); ``` Run the seed script: ```bash bunx --bun prisma db seed ``` And open Prisma Studio to inspect your data: ```bash bunx --bun prisma studio ``` 3. Integrate Prisma into Elysia [#3-integrate-prisma-into-elysia] 3.1. Create a Prisma Client instance [#31-create-a-prisma-client-instance] Inside the `src/` directory, create a `lib` directory with a `prisma.ts` file. This file will create and export your Prisma Client instance and add the following code: ```typescript title="src/lib/prisma.ts" import { PrismaClient } from "../generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { throw new Error("DATABASE_URL is not set"); } const adapter = new PrismaPg({ connectionString: databaseUrl }); export const prisma = new PrismaClient({ adapter }); ``` 3.2. Create API routes [#32-create-api-routes] Update your `src/index.ts` file to match the Prisma Elysia example, including Prismabox-generated validation types: ```typescript title="src/index.ts" import { Elysia, t } from "elysia"; import { prisma } from "./lib/prisma"; import { TodoPlain, TodoPlainInputCreate, TodoPlainInputUpdate } from "./generated/prismabox/Todo"; const app = new Elysia() // Health check .get("/", () => { return { message: "Hello Elysia with Prisma!" }; }) // Get all todos .get( "/todos", async () => { const todos = await prisma.todo.findMany({ orderBy: { createdAt: "desc" }, }); return todos; }, { response: t.Array(TodoPlain), }, ) // Get a single todo by ID .get( "/todos/:id", async ({ params, set }) => { const id = Number(params.id); const todo = await prisma.todo.findUnique({ where: { id }, }); if (!todo) { set.status = 404; return { error: "Todo not found" }; } return todo; }, { params: t.Object({ id: t.Numeric(), }), response: { 200: TodoPlain, 404: t.Object({ error: t.String(), }), }, }, ) // Create a new todo .post( "/todos", async ({ body }) => { const todo = await prisma.todo.create({ data: { title: body.title, }, }); return todo; }, { body: TodoPlainInputCreate, response: TodoPlain, }, ) // Update a todo .put( "/todos/:id", async ({ params, body, set }) => { const id = Number(params.id); try { const todo = await prisma.todo.update({ where: { id }, data: { title: body.title, completed: body.completed, }, }); return todo; } catch { set.status = 404; return { error: "Todo not found" }; } }, { params: t.Object({ id: t.Numeric(), }), body: TodoPlainInputUpdate, response: { 200: TodoPlain, 404: t.Object({ error: t.String(), }), }, }, ) // Toggle todo completion .patch( "/todos/:id/toggle", async ({ params, set }) => { const id = Number(params.id); try { const todo = await prisma.todo.findUnique({ where: { id }, }); if (!todo) { set.status = 404; return { error: "Todo not found" }; } const updated = await prisma.todo.update({ where: { id }, data: { completed: !todo.completed }, }); return updated; } catch { set.status = 404; return { error: "Todo not found" }; } }, { params: t.Object({ id: t.Numeric(), }), response: { 200: TodoPlain, 404: t.Object({ error: t.String(), }), }, }, ) // Delete a todo .delete( "/todos/:id", async ({ params, set }) => { const id = Number(params.id); try { const todo = await prisma.todo.delete({ where: { id }, }); return todo; } catch { set.status = 404; return { error: "Todo not found" }; } }, { params: t.Object({ id: t.Numeric(), }), response: { 200: TodoPlain, 404: t.Object({ error: t.String(), }), }, }, ) .listen(3000); console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`); ``` This creates the same endpoints as the official example: * `GET /` - Health check * `GET /todos` - Fetch all todos (newest first) * `GET /todos/:id` - Fetch a single todo * `POST /todos` - Create a todo * `PUT /todos/:id` - Update a todo * `PATCH /todos/:id/toggle` - Toggle completion * `DELETE /todos/:id` - Delete a todo Prismabox generates the `TodoPlain`/`TodoPlainInput*` TypeBox schemas so responses and request bodies are validated and typed. 3.3. Run the application [#33-run-the-application] Start your Elysia server: ```bash bun run dev ``` You should see `🦊 Elysia is running at localhost:3000` in the console. 3.4. Test the API [#34-test-the-api] Test the endpoints using `curl`: ```bash # Health check curl http://localhost:3000/ | jq # Get all todos curl http://localhost:3000/todos | jq # Get a single todo curl http://localhost:3000/todos/1 | jq # Create a new todo curl -X POST http://localhost:3000/todos \ -H "Content-Type: application/json" \ -d '{"title": "Ship the Prisma + Elysia guide"}' | jq # Toggle completion curl -X PATCH http://localhost:3000/todos/1/toggle | jq # Update a todo curl -X PUT http://localhost:3000/todos/1 \ -H "Content-Type: application/json" \ -d '{"title": "Updated title", "completed": true}' | jq # Delete a todo curl -X DELETE http://localhost:3000/todos/1 | jq ``` You're done! You've created an Elysia app with Prisma that's connected to a Prisma Postgres database. Next steps [#next-steps] Now that you have a working Elysia app connected to a Prisma Postgres database, you can: * Extend your Prisma schema with more models and relationships * Add update and delete endpoints * Explore authentication with [Elysia plugins](https://elysiajs.com/plugins/overview.html) * Use [Eden](https://elysiajs.com/eden/overview.html) for end-to-end type-safe API calls More info [#more-info] * [Prisma Documentation](/orm) * [Elysia Documentation](https://elysiajs.com/) * [Elysia with Prisma Guide](https://elysiajs.com/integrations/prisma.html) ## Related pages - [`Astro`](https://www.prisma.io/docs/guides/frameworks/astro): Learn how to use Prisma ORM in an Astro app - [`Hono`](https://www.prisma.io/docs/guides/frameworks/hono): Learn how to use Prisma ORM in a Hono app - [`NestJS`](https://www.prisma.io/docs/guides/frameworks/nestjs): Learn how to use Prisma ORM in a NestJS app - [`Next.js`](https://www.prisma.io/docs/guides/frameworks/nextjs): Learn how to use Prisma ORM in a Next.js app and deploy it to Vercel - [`Nuxt`](https://www.prisma.io/docs/guides/frameworks/nuxt): A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app # Hono (/docs/guides/frameworks/hono) Location: Guides > Frameworks > Hono Introduction [#introduction] Prisma ORM offers type-safe database access, and [Hono](https://hono.dev/) is built for fast, lightweight web apps. Together with [Prisma Postgres](https://www.prisma.io/postgres), you get a fast, lightweight backend, that can be deployed through Node.js, Cloudflare, or many other runtimes. In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in a Hono backend application. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/hono). Quick start [#quick-start] Run one command to scaffold a Hono project with Prisma ORM and Prisma Postgres ready to go: #### npm ```bash npm create prisma@latest -- --template hono ``` #### pnpm ```bash pnpm create prisma@latest --template hono ``` #### yarn ```bash yarn create prisma@latest --template hono ``` #### bun ```bash bun create prisma@latest --template hono ``` Or follow the steps below to set it up manually. Prerequisites [#prerequisites] * [Node.js 20+](https://nodejs.org) 1. Set up your project [#1-set-up-your-project] Create a new Hono project: #### npm ```bash npm create hono@latest ``` #### pnpm ```bash pnpm create hono@latest ``` #### yarn ```bash yarn create hono@latest ``` #### bun ```bash bun create hono@latest ``` > [!NOTE] > * *Target directory?* `my-app` > * *Which template do you want to use?* `nodejs` > * *Install dependencies? (recommended)* `Yes` > * *Which package manager do you want to use?* `npm` 2. Install and configure Prisma [#2-install-and-configure-prisma] 2.1. Install dependencies [#21-install-dependencies] To get started with Prisma, you'll need to install a few dependencies: #### npm ```bash npm install prisma tsx @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma tsx @types/pg --dev ``` #### bun ```bash bun add prisma tsx @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg dotenv pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: #### npm ```bash npx prisma init --output ../src/generated/prisma ``` #### pnpm ```bash pnpm dlx prisma init --output ../src/generated/prisma ``` #### yarn ```bash yarn dlx prisma init --output ../src/generated/prisma ``` #### bun ```bash bunx --bun prisma init --output ../src/generated/prisma ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma/` directory with a `schema.prisma` file * A `prisma.config.ts` with your Prisma configuration * A `.env` file with a local `DATABASE_URL` already set Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.2. Define your Prisma Schema [#22-define-your-prisma-schema] In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../src/generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] posts Post[] // [!code ++] } // [!code ++] // [!code ++] model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] published Boolean @default(false) // [!code ++] authorId Int // [!code ++] author User @relation(fields: [authorId], references: [id]) // [!code ++] } // [!code ++] ``` This creates two models: `User` and `Post`, with a one-to-many relationship between them. In `prisma.config.ts`, import `dotenv` at the top of the file ```typescript title="prisma.config.ts" import { defineConfig, env } from "prisma/config"; import "dotenv/config"; // [!code ++] export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 2.3. Configure the Prisma Client generator [#23-configure-the-prisma-client-generator] Now, run the following command to create the database tables and generate the Prisma Client: #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 2.4. Seed the database [#24-seed-the-database] Let's add some seed data to populate the database with sample users and posts. Create a new file called `seed.ts` in the `prisma/` directory: ```typescript title="prisma/seed.ts" import { PrismaClient, Prisma } from "../src/generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter, }); 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() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Now, tell Prisma how to run this script by updating your `prisma.config.ts`: ```typescript title="prisma.config.ts" import { defineConfig, env } from "prisma/config"; import "dotenv/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", seed: "tsx prisma/seed.ts", // [!code ++] }, datasource: { url: env("DATABASE_URL"), }, }); ``` Run the seed script: #### npm ```bash npx prisma db seed ``` #### pnpm ```bash pnpm dlx prisma db seed ``` #### yarn ```bash yarn dlx prisma db seed ``` #### bun ```bash bunx --bun prisma db seed ``` And open Prisma Studio to inspect your data: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` 3. Integrate Prisma into Hono [#3-integrate-prisma-into-hono] 3.1. Create a Prisma middleware [#31-create-a-prisma-middleware] Inside of `/src`, create a `lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. Set up the Prisma client like this: ```tsx title="src/lib/prisma.ts" import type { Context, Next } from "hono"; import { PrismaClient } from "../generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; import "dotenv/config"; const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { throw new Error("DATABASE_URL is not set"); } const adapter = new PrismaPg({ connectionString: databaseUrl, }); const prisma = new PrismaClient({ adapter }); function withPrisma(c: Context, next: Next) { if (!c.get("prisma")) { c.set("prisma", prisma); } return next(); } export default withPrisma; ``` > [!WARNING] > We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently. > > If you choose not to use one, in long-lived environments (for example, a Node.js server) instantiate a single `PrismaClient` and reuse it across requests to avoid exhausting database connections. In serverless environments or when using a pooler (for example, Accelerate), creating a client per request is acceptable. 3.2 Environment Variables & Types [#32-environment-variables--types] By default, Hono does not load any environment variables from a `.env`. `dotenv` handles this and will be read that file and expose them via `process.env`. Hono can get additional types to know that the `withPrisma` middleware will set a `prisma` key on the Hono context ```ts title="src/index.ts" import { Hono } from "hono"; import { serve } from "@hono/node-server"; import type { PrismaClient } from "./generated/prisma/client.js"; // [!code ++] type ContextWithPrisma = { // [!code ++] Variables: { // [!code ++] prisma: PrismaClient; // [!code ++] }; // [!code ++] }; // [!code ++] const app = new Hono(); // [!code highlight] app.get("/", (c) => { return c.text("Hello Hono!"); }); serve( { fetch: app.fetch, port: 3000, }, (info) => { console.log(`Server is running on http://localhost:${info.port}`); }, ); ``` If using Cloudflare Workers, the environment variables will automatically be set to Hono's context, so `dotenv` can be skipped. 3.3. Create A GET Route [#33-create-a-get-route] Fetch data from the database using Hono's `app.get` function. This will perform any database queries and return the data as JSON. Create a new route inside of `src/index.ts`: Now, create a GET route that fetches the `Users` data from your database, making sure to include each user's `Posts` by adding them to the `include` field: ```ts title="src/index.ts" import withPrisma from "./lib/prisma.js"; app.get("/users", withPrisma, async (c) => { const prisma = c.get("prisma"); const users = await prisma.user.findMany({ include: { posts: true }, }); return c.json({ users }); }); ``` 3.4. Display The Data [#34-display-the-data] Start the Hono app by call the `dev` script in the `package.json` #### npm ```bash npm run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### bun ```bash bun run dev ``` There should be a "Server is running on [http://localhost:3000](http://localhost:3000)" log printed out. From here, the data can be viewed by visiting `http://localhost:3000/users` or by running `curl` from the command line ```bash curl http://localhost:3000/users | jq ``` You're done! You've created a Hono app with Prisma that's connected to a Prisma Postgres database. For next steps there are some resources below for you to explore as well as next steps for expanding your project. Next Steps [#next-steps] Now that you have a working Hono 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 More Info [#more-info] * [Prisma Documentation](/orm) * [Hono Documentation](https://hono.dev/docs/) ## Related pages - [`Astro`](https://www.prisma.io/docs/guides/frameworks/astro): Learn how to use Prisma ORM in an Astro app - [`Elysia`](https://www.prisma.io/docs/guides/frameworks/elysia): Learn how to use Prisma ORM in an Elysia app - [`NestJS`](https://www.prisma.io/docs/guides/frameworks/nestjs): Learn how to use Prisma ORM in a NestJS app - [`Next.js`](https://www.prisma.io/docs/guides/frameworks/nextjs): Learn how to use Prisma ORM in a Next.js app and deploy it to Vercel - [`Nuxt`](https://www.prisma.io/docs/guides/frameworks/nuxt): A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app # NestJS (/docs/guides/frameworks/nestjs) Location: Guides > Frameworks > NestJS Introduction [#introduction] This guide shows you how to use Prisma ORM with [NestJS](https://nestjs.com/), a progressive Node.js framework for building efficient and scalable server-side applications. You'll build a REST API with NestJS that uses Prisma ORM to store and retrieve data from a database. [Prisma ORM](https://www.prisma.io) is an open-source ORM for Node.js and TypeScript. It is used as an **alternative** to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](https://knexjs.org/)) or ORMs (like [TypeORM](https://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL, SQL Server, SQLite, MongoDB and CockroachDB. While Prisma can be used with plain JavaScript, it embraces TypeScript and provides a level of type-safety that goes beyond the guarantees other ORMs in the TypeScript ecosystem offer. You can find a ready-to-run example [here](https://github.com/prisma/prisma-examples/tree/latest/orm/nest) Quick start [#quick-start] Run one command to scaffold a NestJS project with Prisma ORM and Prisma Postgres ready to go: #### npm ```bash npm create prisma@latest -- --template nestjs ``` #### pnpm ```bash pnpm create prisma@latest --template nestjs ``` #### yarn ```bash yarn create prisma@latest --template nestjs ``` #### bun ```bash bun create prisma@latest --template nestjs ``` Or follow the steps below to set it up manually. Prerequisites [#prerequisites] * [Node.js 20+](https://nodejs.org) 1. Create your NestJS project [#1-create-your-nestjs-project] Install the NestJS CLI and create a new project: #### npm ```bash npm install -g @nestjs/cli ``` #### pnpm ```bash pnpm add -g @nestjs/cli ``` #### yarn ```bash yarn global add @nestjs/cli ``` #### bun ```bash bun add --global @nestjs/cli ``` ```bash nest new nestjs-prisma ``` When prompted, select **npm** as your package manager. Navigate to the project directory: ```bash cd nestjs-prisma ``` You can run `npm start` to start your application at `http://localhost:3000/`. Over the course of this guide, you'll add routes to store and retrieve data about *users* and *posts*. In `package.json`, add the `type` field set to `"module"`: ```json title="package.json" { "type": "module" // [!code ++] } ``` 2. Set up Prisma [#2-set-up-prisma] 2.1. Install Prisma and dependencies [#21-install-prisma-and-dependencies] Install the necessary Prisma packages and database drivers: #### npm ```bash npm install prisma --save-dev ``` #### pnpm ```bash pnpm add prisma --save-dev ``` #### yarn ```bash yarn add prisma --dev ``` #### bun ```bash bun add prisma --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). 2.2. Initialize Prisma [#22-initialize-prisma] Initialize Prisma in your project: #### npm ```bash npx prisma init --output ../src/generated/prisma ``` #### pnpm ```bash pnpm dlx prisma init --output ../src/generated/prisma ``` #### yarn ```bash yarn dlx prisma init --output ../src/generated/prisma ``` #### bun ```bash bunx --bun prisma init --output ../src/generated/prisma ``` This creates a new `prisma` directory with the following contents: * `schema.prisma`: Specifies your database connection and contains the database schema * `prisma.config.ts`: A configuration file for your projects * `.env`: A [dotenv](https://github.com/motdotla/dotenv) file, typically used to store your database credentials in a group of environment variables Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.3. Set the generator output path [#23-set-the-generator-output-path] Specify your output `path` for the generated Prisma client by either passing `--output ../src/generated/prisma` during `prisma init` or directly in your Prisma schema: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../src/generated/prisma" } ``` 2.4. Configure your database connection [#24-configure-your-database-connection] Your database connection is configured in the `datasource` block in your `schema.prisma` file. By default it's set to `postgresql` which is what you need for this guide. ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../src/generated/prisma" } datasource db { provider = "postgresql" } ``` Now, open up `.env` and you should see a `DATABASE_URL` already specified: ```text title=".env" DATABASE_URL="postgres://..." ``` > [!NOTE] > Make sure you have a [ConfigModule](https://docs.nestjs.com/techniques/configuration) configured, otherwise the `DATABASE_URL` variable will not be picked up from `.env`. 2.5. Define your data model [#25-define-your-data-model] Add the following two models to your `schema.prisma` file: ```prisma title="prisma/schema.prisma" model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean? @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` 2.6. Create and run your migration [#26-create-and-run-your-migration] With your Prisma models in place, you can generate your SQL migration files and run them against the database. Run the following commands in your terminal: #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` This `prisma migrate dev` command generates SQL files and directly runs them against the database. In this case, the following migration files was created in the existing `prisma` directory: ```bash $ tree prisma prisma ├── migrations │ └── 20201207100915_init │ └── migration.sql └── schema.prisma ``` 2.7. Generate Prisma Client [#27-generate-prisma-client] Once installed, you can run the generate command to generate the types and Client needed for your project. If any changes are made to your schema, you will need to rerun the `generate` command to keep those types in sync. #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 3. Create a Prisma service [#3-create-a-prisma-service] You're now able to send database queries with Prisma Client. When setting up your NestJS application, you'll want to abstract away the Prisma Client API for database queries within a service. To get started, you can create a new `PrismaService` that takes care of instantiating `PrismaClient` and connecting to your database. Inside the `src` directory, create a new file called `prisma.service.ts` and add the following code to it: ```typescript title="src/prisma.service.ts" import { Injectable } from "@nestjs/common"; import { PrismaClient } from "./generated/prisma/client.js"; import { PrismaPg } from "@prisma/adapter-pg"; @Injectable() export class PrismaService extends PrismaClient { constructor() { const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL as string, }); super({ adapter }); } } ``` 4. Create User and Post services [#4-create-user-and-post-services] Next, you can write services that you can use to make database calls for the `User` and `Post` models from your Prisma schema. 4.1. Create the User service [#41-create-the-user-service] Still inside the `src` directory, create a new file called `user.service.ts` and add the following code to it: ```typescript title="src/user.service.ts" import { Injectable } from "@nestjs/common"; import { PrismaService } from "./prisma.service.js"; import { User, Prisma } from "./generated/prisma/client.js"; @Injectable() export class UserService { constructor(private prisma: PrismaService) {} async user(userWhereUniqueInput: Prisma.UserWhereUniqueInput): Promise { return this.prisma.user.findUnique({ where: userWhereUniqueInput, }); } async users(params: { skip?: number; take?: number; cursor?: Prisma.UserWhereUniqueInput; where?: Prisma.UserWhereInput; orderBy?: Prisma.UserOrderByWithRelationInput; }): Promise { const { skip, take, cursor, where, orderBy } = params; return this.prisma.user.findMany({ skip, take, cursor, where, orderBy, }); } async createUser(data: Prisma.UserCreateInput): Promise { return this.prisma.user.create({ data, }); } async updateUser(params: { where: Prisma.UserWhereUniqueInput; data: Prisma.UserUpdateInput; }): Promise { const { where, data } = params; return this.prisma.user.update({ data, where, }); } async deleteUser(where: Prisma.UserWhereUniqueInput): Promise { return this.prisma.user.delete({ where, }); } } ``` Notice how you're using Prisma Client's generated types to ensure that the methods that are exposed by your service are properly typed. You therefore save the boilerplate of typing your models and creating additional interface or DTO files. 4.2. Create the Post service [#42-create-the-post-service] Now do the same for the `Post` model. Still inside the `src` directory, create a new file called `post.service.ts` and add the following code to it: ```typescript title="src/post.service.ts" import { Injectable } from "@nestjs/common"; import { PrismaService } from "./prisma.service.js"; import { Post, Prisma } from "./generated/prisma/client.js"; @Injectable() export class PostService { constructor(private prisma: PrismaService) {} async post(postWhereUniqueInput: Prisma.PostWhereUniqueInput): Promise { return this.prisma.post.findUnique({ where: postWhereUniqueInput, }); } async posts(params: { skip?: number; take?: number; cursor?: Prisma.PostWhereUniqueInput; where?: Prisma.PostWhereInput; orderBy?: Prisma.PostOrderByWithRelationInput; }): Promise { const { skip, take, cursor, where, orderBy } = params; return this.prisma.post.findMany({ skip, take, cursor, where, orderBy, }); } async createPost(data: Prisma.PostCreateInput): Promise { return this.prisma.post.create({ data, }); } async updatePost(params: { where: Prisma.PostWhereUniqueInput; data: Prisma.PostUpdateInput; }): Promise { const { data, where } = params; return this.prisma.post.update({ data, where, }); } async deletePost(where: Prisma.PostWhereUniqueInput): Promise { return this.prisma.post.delete({ where, }); } } ``` Your `UserService` and `PostService` currently wrap the CRUD queries that are available in Prisma Client. In a real world application, the service would also be the place to add business logic to your application. For example, you could have a method called `updatePassword` inside the `UserService` that would be responsible for updating the password of a user. 5. Implement REST API routes [#5-implement-rest-api-routes] 5.1. Create the controller [#51-create-the-controller] Finally, you'll use the services you created in the previous sections to implement the different routes of your app. For the purpose of this guide, you'll put all your routes into the already existing `AppController` class. Replace the contents of the `app.controller.ts` file with the following code: ```typescript title="src/app.controller.ts" import { Controller, Get, Param, Post, Body, Put, Delete } from "@nestjs/common"; import { UserService } from "./user.service.js"; import { PostService } from "./post.service.js"; import { User as UserModel } from "./generated/prisma/client.js"; import { Post as PostModel } from "./generated/prisma/client.js"; @Controller() export class AppController { constructor( private readonly UserService: UserService, private readonly postService: PostService, ) {} @Get("post/:id") async getPostById(@Param("id") id: string): Promise { return this.postService.post({ id: Number(id) }); } @Get("feed") async getPublishedPosts(): Promise { return this.postService.posts({ where: { published: true }, }); } @Get("filtered-posts/:searchString") async getFilteredPosts(@Param("searchString") searchString: string): Promise { return this.postService.posts({ where: { OR: [ { title: { contains: searchString }, }, { content: { contains: searchString }, }, ], }, }); } @Post("post") async createDraft( @Body() postData: { title: string; content?: string; authorEmail: string }, ): Promise { const { title, content, authorEmail } = postData; return this.postService.createPost({ title, content, author: { connect: { email: authorEmail }, }, }); } @Post("user") async signupUser(@Body() userData: { name?: string; email: string }): Promise { return this.UserService.createUser(userData); } @Put("publish/:id") async publishPost(@Param("id") id: string): Promise { return this.postService.updatePost({ where: { id: Number(id) }, data: { published: true }, }); } @Delete("post/:id") async deletePost(@Param("id") id: string): Promise { return this.postService.deletePost({ id: Number(id) }); } } ``` This controller implements the following routes: GET [#get] * `/post/:id`: Fetch a single post by its `id` * `/feed`: Fetch all *published* posts * `/filtered-posts/:searchString`: Filter posts by `title` or `content` POST [#post] * `/post`: Create a new post * Body: * `title: String` (required): The title of the post * `content: String` (optional): The content of the post * `authorEmail: String` (required): The email of the user that creates the post * `/user`: Create a new user * Body: * `email: String` (required): The email address of the user * `name: String` (optional): The name of the user PUT [#put] * `/publish/:id`: Publish a post by its `id` DELETE [#delete] * `/post/:id`: Delete a post by its `id` 5.2. Register services in the app module [#52-register-services-in-the-app-module] Remember to register the new services in the app module. Update `src/app.module.ts` to register all services: ```typescript title="src/app.module.ts" import { Module } from "@nestjs/common"; import { AppController } from "./app.controller"; import { ConfigModule } from "@nestjs/config"; import { AppService } from "./app.service.js"; import { PrismaService } from "./prisma.service.js"; // [!code ++] import { UserService } from "./user.service.js"; // [!code ++] import { PostService } from "./post.service.js"; // [!code ++] @Module({ imports: [ConfigModule.forRoot()], controllers: [AppController], providers: [AppService, PrismaService, UserService, PostService], // [!code ++] }) export class AppModule {} ``` 6. Test your API [#6-test-your-api] Start your application: #### npm ```bash npm start ``` #### pnpm ```bash pnpm start ``` #### yarn ```bash yarn start ``` #### bun ```bash bun start ``` Test your endpoints with curl, [Postman](https://www.postman.com/), or [HTTPie](https://httpie.io/). **Create a user:** ```bash curl -X POST http://localhost:3000/user \ -H "Content-Type: application/json" \ -d '{"name": "Alice", "email": "alice@prisma.io"}' ``` **Create a post:** ```bash curl -X POST http://localhost:3000/post \ -H "Content-Type: application/json" \ -d '{"title": "Hello World", "authorEmail": "alice@prisma.io"}' ``` **Get published posts:** ```bash curl http://localhost:3000/feed ``` **Publish a post:** ```bash curl -X PUT http://localhost:3000/publish/1 ``` **Search posts:** ```bash curl http://localhost:3000/filtered-posts/hello ``` Summary [#summary] In this guide, you learned how to use Prisma ORM with NestJS to implement a REST API. The controller that implements the routes of the API is calling a `PrismaService` which in turn uses Prisma Client to send queries to a database to fulfill the data needs of incoming requests. If you want to learn more about using NestJS with Prisma, be sure to check out the following resources: * [NestJS & Prisma](https://www.prisma.io/nestjs) * [Ready-to-run example projects for REST & GraphQL](https://github.com/prisma/prisma-examples/) * [Production-ready starter kit](https://github.com/notiz-dev/nestjs-prisma-starter#instructions) * [Video: Accessing Databases using NestJS with Prisma (5min)](https://www.youtube.com/watch?v=UlVJ340UEuk\&ab_channel=Prisma) by [Marc Stammerjohann](https://github.com/marcjulian) ## Related pages - [`Astro`](https://www.prisma.io/docs/guides/frameworks/astro): Learn how to use Prisma ORM in an Astro app - [`Elysia`](https://www.prisma.io/docs/guides/frameworks/elysia): Learn how to use Prisma ORM in an Elysia app - [`Hono`](https://www.prisma.io/docs/guides/frameworks/hono): Learn how to use Prisma ORM in a Hono app - [`Next.js`](https://www.prisma.io/docs/guides/frameworks/nextjs): Learn how to use Prisma ORM in a Next.js app and deploy it to Vercel - [`Nuxt`](https://www.prisma.io/docs/guides/frameworks/nuxt): A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app # Next.js (/docs/guides/frameworks/nextjs) Location: Guides > Frameworks > Next.js Introduction [#introduction] This guide shows you how to use Prisma with Next.js, a fullstack React framework. You'll learn how to create a [Prisma Postgres](/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). Quick start [#quick-start] Run one command to scaffold a Next.js project with Prisma ORM and Prisma Postgres ready to go: #### npm ```bash npm create prisma@latest -- --template next ``` #### pnpm ```bash pnpm create prisma@latest --template next ``` #### yarn ```bash yarn create prisma@latest --template next ``` #### bun ```bash bun create prisma@latest --template next ``` Or follow the steps below to set it up manually. Prerequisites [#prerequisites] * [Node.js](https://nodejs.org) v20.19+, v22.12+, or v24.0+ * A Vercel account (if you want to deploy your application) 1. Set up your project [#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. #### npm ```bash npx create-next-app@latest nextjs-prisma ``` #### pnpm ```bash pnpm dlx create-next-app@latest nextjs-prisma ``` #### yarn ```bash yarn dlx create-next-app@latest nextjs-prisma ``` #### bun ```bash bunx --bun create-next-app@latest nextjs-prisma ``` You will be prompted to answer a few questions about your project. Select all of the defaults. > [!NOTE] > For reference, those are: > > * TypeScript > * ESLint > * Tailwind CSS > * No `src` directory > * App Router > * Turbopack > * No customized import alias Then, navigate to the project directory: ```bash cd nextjs-prisma ``` 2. Install and Configure Prisma [#2-install-and-configure-prisma] 2.1. Install dependencies [#21-install-dependencies] To get started with Prisma, you'll need to install a few dependencies: #### npm ```bash npm install prisma tsx @types/pg --save-dev ``` #### pnpm ```bash pnpm add prisma tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma tsx @types/pg --dev ``` #### bun ```bash bun add prisma tsx @types/pg --dev ``` #### npm ```bash npm install @prisma/client @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client @prisma/adapter-pg dotenv pg ``` #### bun ```bash bun add @prisma/client @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: #### npm ```bash npx prisma init --output ../app/generated/prisma ``` #### pnpm ```bash pnpm dlx prisma init --output ../app/generated/prisma ``` #### yarn ```bash yarn dlx prisma init --output ../app/generated/prisma ``` #### bun ```bash bunx --bun prisma init --output ../app/generated/prisma ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma` directory with a `schema.prisma` file. * A `prisma.config.ts` file for configuring Prisma. * A `.env` file containing a local `DATABASE_URL` at the project root. The `app/generated/prisma` output directory for the generated Prisma Client will be created when you run `prisma generate` or `prisma migrate dev` in a later step. Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### npm ```bash npx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### bun ```bash bunx --bun create-db ``` 2.2. Define your Prisma Schema [#22-define-your-prisma-schema] In the `prisma/schema.prisma` file, add the following models: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../app/generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] posts Post[] // [!code ++] } // [!code ++] // [!code ++] model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] published Boolean @default(false) // [!code ++] authorId Int // [!code ++] author User @relation(fields: [authorId], references: [id]) // [!code ++] } // [!code ++] ``` This creates two models: `User` and `Post`, with a one-to-many relationship between them. 2.3 Add dotenv to prisma.config.ts [#23-add-dotenv-to-prismaconfigts] To get access to the variables in the `.env` file, they can either be loaded by your runtime, or by using `dotenv`. Include an import for `dotenv` at the top of the `prisma.config.ts` ```typescript title="prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` 2.4. Run migrations and generate Prisma Client [#24-run-migrations-and-generate-prisma-client] Now, run the following command to create the database tables: #### npm ```bash npx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### bun ```bash bunx --bun prisma migrate dev --name init ``` Then generate Prisma Client: #### npm ```bash npx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### bun ```bash bunx --bun prisma generate ``` 2.5. Seed the database [#25-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: ```typescript title="prisma/seed.ts" import { PrismaClient, Prisma } from "../app/generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import "dotenv/config"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); 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 `prisma.config.ts`: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", seed: `tsx prisma/seed.ts`, // [!code ++] }, datasource: { url: env("DATABASE_URL"), }, }); ``` Finally, run `prisma db seed` to seed your database with the initial data we defined in the `seed.ts` file. Run the seed script: #### npm ```bash npx prisma db seed ``` #### pnpm ```bash pnpm dlx prisma db seed ``` #### yarn ```bash yarn dlx prisma db seed ``` #### bun ```bash bunx --bun prisma db seed ``` And open Prisma Studio to inspect your data: #### npm ```bash npx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### bun ```bash bunx --bun prisma studio ``` 2.6 Set up Prisma Client [#26-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. ```bash mkdir -p lib && touch lib/prisma.ts ``` Now, add the following code to your `lib/prisma.ts` file: ```typescript title="lib/prisma.ts" showLineNumbers import { PrismaClient } from "../app/generated/prisma/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const globalForPrisma = global as unknown as { // [!code ++] prisma: PrismaClient; // [!code ++] }; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const prisma = globalForPrisma.prisma || new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; // [!code ++] // [!code ++] export default prisma; // [!code ++] ``` 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 [#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: ```tsx title="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. ```tsx title="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) [#31-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 [#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. ```bash mkdir -p app/posts && touch app/posts/page.tsx ``` Second, add the following code to the `app/posts/page.tsx` file: ```tsx title="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: ```tsx title="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 [#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. ```bash 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/[id]/page.tsx` file: ```tsx title="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: ```tsx title="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 [#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. ```bash mkdir -p app/posts/new && touch app/posts/new/page.tsx ``` Now, add the following code to the `app/posts/new/page.tsx` file: ```tsx title="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