# 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 starting points depending on what you want to do first: deploy an app, create a database, use Prisma ORM locally, or add Prisma to an existing project. Choose your path [#choose-your-path] Deploy a full-stack app with a database [#deploy-a-full-stack-app-with-a-database] Use this path if you want to deploy a TypeScript app with Prisma Compute and run it alongside Prisma Postgres. * [Deploy your first app](/prisma-compute/deploy) on [Prisma Compute](/compute), currently in Public Beta, to run it next to your Prisma Postgres database Start a new project [#start-a-new-project] Use this path if you are creating a new app and want to set up Prisma from the beginning. * [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] Use this path if you already have an application or database and want to add Prisma ORM. * [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] Most Prisma ORM and Prisma Postgres guides follow the same basic flow: 1. Define a database connection and data model in your [Prisma schema](/orm/prisma-schema/overview). 2. Set up your database, either with [Prisma Postgres](/postgres) or another supported database. 3. Install Prisma CLI and [Prisma Client](/orm/prisma-client). 4. Run `prisma generate` to create a type-safe client for your schema. 5. Create or introspect your database. 6. Start sending queries from your application. Then you can deploy your app to [Prisma Compute](/compute). The flow is: 1. Sign in with `npx @prisma/cli@latest auth login`. 2. Run `npx @prisma/cli@latest app deploy` from your app directory to get a live URL. 3. Connect your app to [Prisma Postgres](/postgres) or another database with [environment variables](/compute/environment-variables). 4. Redeploy to apply the environment variables. 5. Keep deploying from the CLI, or [connect GitHub](/compute/github) to deploy on push. 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 - [`Introduction to Prisma Next`](https://www.prisma.io/docs/next): Prisma Next is the next major version of Prisma ORM, available in Early Access. # 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. #### bun ```bash bunx --bun prisma@latest init ``` #### pnpm ```bash pnpm dlx prisma@latest init ``` #### yarn ```bash yarn dlx prisma@latest init ``` #### npm ```bash npx prisma@latest 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). #### bun ```bash bunx create-db@latest ``` #### pnpm ```bash pnpm dlx create-db@latest ``` #### yarn ```bash yarn dlx create-db@latest ``` #### npm ```bash npx create-db@latest ``` [**Prisma Compute**](/compute) is TypeScript app hosting for running your app next to your Prisma Postgres database. It is currently in [Public Beta](/console/more/feature-maturity#public-beta). Deploy Next.js, Hono, TanStack Start, and Bun apps, with an isolated preview for every branch. #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` > [!NOTE] > Curious what's next? [Prisma Next](/next) is the next major version of Prisma ORM, available now in Early Access. Explore the new developer experience whenever you're ready. - [Use Prisma Compute](/prisma-compute/deploy): Deploy and run your TypeScript app next to your database, with a live preview for every branch. - [Use Prisma Postgres](/prisma-orm/quickstart/prisma-postgres): Get started with your favorite framework and Prisma Postgres as the database. # 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: #### bun ```bash bunx --bun 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" ``` #### npm ```bash npx 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. #### bun ```bash bunx skills add prisma/skills ``` #### pnpm ```bash pnpm dlx skills add prisma/skills ``` #### yarn ```bash yarn dlx skills add prisma/skills ``` #### npm ```bash npx 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 - [`Introduction to Prisma Next`](https://www.prisma.io/docs/next): Prisma Next is the next major version of Prisma ORM, available in Early Access. # 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 #### bun ```bash bun add @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 ``` #### npm ```bash npm install @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: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma generate --no-engine ``` #### pnpm ```bash pnpm dlx prisma generate --no-engine ``` #### yarn ```bash yarn dlx prisma generate --no-engine ``` #### npm ```bash npx 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: > > > > > #### bun > ```bash > bunx prisma generate --accelerate > ``` > > > #### pnpm > ```bash > pnpm dlx prisma generate --accelerate > ``` > > > #### yarn > ```bash > yarn dlx prisma generate --accelerate > ``` > > > #### npm > ```bash > npx prisma generate --accelerate > ``` > > > > If your Prisma version is below `5.0.0`, generate Prisma Client with the `--data-proxy` option: > > > > > #### bun > ```bash > bunx prisma generate --data-proxy > ``` > > > #### pnpm > ```bash > pnpm dlx prisma generate --data-proxy > ``` > > > #### yarn > ```bash > yarn dlx prisma generate --data-proxy > ``` > > > #### npm > ```bash > npx 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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 # 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] #### bun ```bash bunx prisma debug ``` #### pnpm ```bash pnpm dlx prisma debug ``` #### yarn ```bash yarn dlx prisma debug ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma@latest debug ``` #### pnpm ```bash pnpm dlx prisma@latest debug ``` #### yarn ```bash yarn dlx prisma@latest debug ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma format ``` #### pnpm ```bash pnpm dlx prisma format ``` #### yarn ```bash yarn dlx prisma format ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma generate --schema=./alternative/schema.prisma ``` Watch mode [#watch-mode] Automatically regenerate when the schema changes: #### bun ```bash bunx prisma generate --watch ``` #### pnpm ```bash pnpm dlx prisma generate --watch ``` #### yarn ```bash yarn dlx prisma generate --watch ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma generate --generator client ``` #### pnpm ```bash pnpm dlx prisma generate --generator client ``` #### yarn ```bash yarn dlx prisma generate --generator client ``` #### npm ```bash npx prisma generate --generator client ``` Multiple generators: #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bun add prisma --dev ``` #### pnpm ```bash pnpm add prisma --save-dev ``` #### yarn ```bash yarn add prisma --dev ``` #### npm ```bash npm install prisma --save-dev ``` > [!NOTE] > Looking for [Prisma Compute](/compute) commands? Deployments to Compute use the separate [`@prisma/cli`](/compute/getting-started) beta package, which exposes the `prisma-cli` binary so it can coexist with `prisma`. See [Get started with `@prisma/cli`](/compute/getting-started) and the [Prisma Compute CLI reference](/compute/cli-reference). 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 - [`Introduction to Prisma Next`](https://www.prisma.io/docs/next): Prisma Next is the next major version of Prisma ORM, available in Early Access. # 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: #### bun ```bash bunx --bun prisma init ``` #### pnpm ```bash pnpm dlx prisma init ``` #### yarn ```bash yarn dlx prisma init ``` #### npm ```bash npx prisma init ``` Specify a datasource provider [#specify-a-datasource-provider] Set up a new project with MySQL as the datasource provider: #### bun ```bash bunx --bun prisma init --datasource-provider mysql ``` #### pnpm ```bash pnpm dlx prisma init --datasource-provider mysql ``` #### yarn ```bash yarn dlx prisma init --datasource-provider mysql ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun 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 ``` #### npm ```bash npx prisma init --generator-provider prisma-client-js ``` Specify preview features [#specify-preview-features] Set up a project with specific preview features enabled: #### bun ```bash bunx --bun prisma init --preview-feature metrics ``` #### pnpm ```bash pnpm dlx prisma init --preview-feature metrics ``` #### yarn ```bash yarn dlx prisma init --preview-feature metrics ``` #### npm ```bash npx prisma init --preview-feature metrics ``` Multiple preview features: #### bun ```bash bunx --bun 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun prisma init --output ./generated-client ``` #### pnpm ```bash pnpm dlx prisma init --output ./generated-client ``` #### yarn ```bash yarn dlx prisma init --output ./generated-client ``` #### npm ```bash npx prisma init --output ./generated-client ``` Specify a custom datasource URL [#specify-a-custom-datasource-url] Set up a project with a specific database URL: #### bun ```bash bunx --bun 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun prisma init --with-model ``` #### pnpm ```bash pnpm dlx prisma init --with-model ``` #### yarn ```bash yarn dlx prisma init --with-model ``` #### npm ```bash npx prisma init --with-model ``` Provision a Prisma Postgres database [#provision-a-prisma-postgres-database] Create a new project with a managed Prisma Postgres database: #### bun ```bash bunx --bun prisma init --db ``` #### pnpm ```bash pnpm dlx prisma init --db ``` #### yarn ```bash yarn dlx prisma init --db ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### npm ```bash npx prisma studio ``` Start Studio on a custom port [#start-studio-on-a-custom-port] #### bun ```bash bunx prisma studio --port 7777 ``` #### pnpm ```bash pnpm dlx prisma studio --port 7777 ``` #### yarn ```bash yarn dlx prisma studio --port 7777 ``` #### npm ```bash npx prisma studio --port 7777 ``` Start Studio in a specific browser [#start-studio-in-a-specific-browser] #### bun ```bash bunx prisma studio --browser firefox ``` #### pnpm ```bash pnpm dlx prisma studio --browser firefox ``` #### yarn ```bash yarn dlx prisma studio --browser firefox ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma studio --browser none ``` #### pnpm ```bash pnpm dlx prisma studio --browser none ``` #### yarn ```bash yarn dlx prisma studio --browser none ``` #### npm ```bash npx prisma studio --browser none ``` Start Studio with a custom config file [#start-studio-with-a-custom-config-file] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma studio --config=./prisma.config.ts ``` Start Studio with a direct database connection string [#start-studio-with-a-direct-database-connection-string] #### bun ```bash bunx 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" ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma validate ``` #### pnpm ```bash pnpm dlx prisma validate ``` #### yarn ```bash yarn dlx prisma validate ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma validate --schema=./alternative/schema.prisma ``` Validate with a config file [#validate-with-a-config-file] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma version ``` #### pnpm ```bash pnpm dlx prisma version ``` #### yarn ```bash yarn dlx prisma version ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma -v ``` #### pnpm ```bash pnpm dlx prisma -v ``` #### yarn ```bash yarn dlx prisma -v ``` #### npm ```bash npx prisma -v ``` Display version as JSON [#display-version-as-json] #### bun ```bash bunx prisma version --json ``` #### pnpm ```bash pnpm dlx prisma version --json ``` #### yarn ```bash yarn dlx prisma version --json ``` #### npm ```bash npx 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 five 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. * [**Branches**](#branch): For projects that use [Prisma Compute](/compute), resources are grouped into branches. A branch is an isolated infrastructure boundary for one line of work, usually mapping to a Git branch. * [**Resources**](#resources): Resources represent the actual services or databases within a project. For example, in Prisma Postgres, each project can contain multiple databases. For Prisma Compute, each branch contains apps and their deployments. 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. Branch [#branch] For projects that use [Prisma Compute](/compute), a branch groups the resources for one line of work: ```text workspace → project → branch → { apps, databases } ``` A branch usually maps to a Git branch, but it's a real resource that owns the apps and databases for that work: * The **first branch** in a project is the production branch, usually `main`. It's protected and durable. * **Every other branch** is a preview branch by default: disposable infrastructure for testing changes before they merge. * [Environment variables](/compute/environment-variables) are scoped to production, to preview, or to a single preview branch. Learn more in [Branching](/compute/branching). 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 Prisma Compute**: Each branch contains apps. An app is an HTTP service, and each built version of an app is a deployment. See [Prisma Compute](/compute). * **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. * [Prisma Compute](/compute): Runs your app next to your Prisma Postgres database, currently in [Public Beta](/console/more/feature-maturity#public-beta). Inspect projects, branches, apps, and deployments in the Console; deploy with the [`@prisma/cli`](/compute/getting-started) beta package. 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 - [`Introduction to Prisma Next`](https://www.prisma.io/docs/next): Prisma Next is the next major version of Prisma ORM, available in Early Access. # 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: #### bun ```bash bun init bun add tsx typescript @types/node --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 ``` #### npm ```bash npm init npm install tsx typescript @types/node --save-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: #### bun ```bash bun add dotenv ``` #### pnpm ```bash pnpm add dotenv ``` #### yarn ```bash yarn add dotenv ``` #### npm ```bash npm install 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: #### bun ```bash bun add axios ``` #### pnpm ```bash pnpm add axios ``` #### yarn ```bash yarn add axios ``` #### npm ```bash npm install axios ``` You're all set, let's write some code to create a project and provision a Prisma Postgres database! 3. Programmatically create a new project with a database [#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: #### bun ```bash bunx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### npm ```bash npx 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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] #### bun ```bash bun add @prisma/management-api-sdk ``` #### pnpm ```bash pnpm add @prisma/management-api-sdk ``` #### yarn ```bash yarn add @prisma/management-api-sdk ``` #### npm ```bash npm install @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 # 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: #### bun ```bash bun create prisma@latest ``` #### pnpm ```bash pnpm create prisma@latest ``` #### yarn ```bash yarn create prisma@latest ``` #### npm ```bash npm 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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. - [`Introduction to Prisma Next`](https://www.prisma.io/docs/next): Prisma Next is the next major version of Prisma ORM, available in Early Access. # 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: #### bun ```bash bun add prisma --dev ``` #### pnpm ```bash pnpm add prisma --save-dev ``` #### yarn ```bash yarn add prisma --dev ``` #### npm ```bash npm install prisma --save-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 ## Related pages - [`Overview`](https://www.prisma.io/docs/guides/next): Practical, step-by-step guides for building with Prisma Next, each one run end to end before it ships. # Branching (/docs/compute/branching) Location: Compute > Branching A branch is an isolated environment for one line of work. Every branch in a project gets its own apps, databases, and deployments, so work on a preview never touches production. A platform branch usually matches a Git branch name, but in Prisma it is a real resource that owns its own apps and databases: Production and preview [#production-and-preview] Every branch has a role: * The **first branch** in a project is your production branch, usually `main`. It's protected and durable: after the first deploy, deploys to it need an explicit `--prod` flag, and automated cleanup never touches it. * **Every other branch** is a preview by default: disposable resources for testing changes before they merge. Preview deploys never ask for confirmation. To learn more, see the [Deployments docs](/compute/deployments). How the CLI picks a branch [#how-the-cli-picks-a-branch] When you deploy, the CLI resolves the branch in this order: 1. `--branch `, if you pass it. 2. Your active Git branch. 3. `main`. Inside a Git repo, deploying from `feature/search` targets the `feature/search` branch automatically. To target a branch explicitly: #### bun ```bash bunx @prisma/cli@latest app deploy --branch feature/search ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --branch feature/search ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --branch feature/search ``` #### npm ```bash npx @prisma/cli@latest app deploy --branch feature/search ``` Inspect platform branches: #### bun ```bash bunx @prisma/cli@latest branch list ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest branch list ``` #### yarn ```bash yarn dlx @prisma/cli@latest branch list ``` #### npm ```bash npx @prisma/cli@latest branch list ``` Listing branches doesn't expand the apps and databases inside them. Use the `app` commands to inspect those. Creating branches [#creating-branches] You rarely create branches manually. They appear when work needs them: * **On deploy**: `app deploy --branch feature/search` creates the branch if it doesn't exist. * **From GitHub**: when a repo is connected, branch and push events create or update the matching platform branch automatically. To set this up, see the [GitHub integration docs](/compute/github). Connecting GitHub doesn't create branches retroactively; it aligns your default branch with the repo's default branch and wires up automation for future events. Cleaning up [#cleaning-up] When GitHub is connected, deleting a Git branch tears down the matching platform branch, as long as it isn't your production or default branch. Those are always left alone. Next steps [#next-steps] * [Environment variables](/compute/environment-variables): preview values and per-branch overrides. * [GitHub integration](/compute/github): keep platform branches in sync with your repo. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. - [`Domains`](https://www.prisma.io/docs/compute/domains): Point a custom domain at a production app and the platform verifies DNS and provisions TLS for you. # CLI reference (/docs/compute/cli-reference) Location: Compute > CLI reference This page is the complete reference for the [`@prisma/cli`](https://github.com/prisma/prisma-cli) beta package. For a guided start, see [Get started with `@prisma/cli`](/compute/getting-started). The package installs an executable called `prisma-cli`. Run it without installing: #### bun ```bash bunx @prisma/cli@latest ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest ``` #### yarn ```bash yarn dlx @prisma/cli@latest ``` #### npm ```bash npx @prisma/cli@latest ``` Requires Node.js 22.12 or newer for `npx` and `pnpm`; `bunx` also works. The command groups are `auth`, `init`, `project`, `project env`, `git`, `branch`, `database`, `app`, `build`, `agent`, and `version`. There is no `schema` or `migrate` command in the beta. auth [#auth] Manage authentication. | Command | Description | | ------------- | ----------------------------------------------------- | | `auth login` | Log in to your Prisma platform account (browser flow) | | `auth logout` | Clear stored authentication credentials | | `auth whoami` | Show the authenticated user and accessible workspace | The browser step in `auth login` needs a human. Afterwards, anything running in that environment inherits the session, including coding agents. For CI, set [`PRISMA_SERVICE_TOKEN`](#environment-variables) instead. init [#init] Scaffold Compute configuration for the current directory. `init` detects your framework and writes `prisma.compute.ts` (or, with `--format json`, a dependency-free `prisma.compute.json`). The `app` commands read this file for app targets, framework, entry point, HTTP port, region, and env inputs. | Flag | Description | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `--framework ` | Framework override; detected when omitted | | `--entry ` | Source entrypoint for entrypoint frameworks (Bun, Hono) | | `--http-port ` | HTTP port the app listens on | | `--region ` | Region used when deploy creates the app | | `--name ` | App name | | `--link` / `--no-link` | Link this directory to a project, or skip that step | | `--project ` | Project to link this directory to | | `--install` / `--no-install` | Install `@prisma/compute-sdk` for config types, or skip that step | | `--format ` | `ts` (default) writes `prisma.compute.ts`; `json` writes `prisma.compute.json`; `--format ts` converts an existing `prisma.compute.json` | app [#app] Manage apps and deployments for a project. | Command | Description | | ------------------------------ | ---------------------------------------------------------------------------- | | `app build` | Build the app locally into a deployable artifact | | `app deploy` | Create a new deployment for the app | | `app show` | Show the app and its current deployment | | `app open` | Open the app's live URL | | `app logs` | Stream logs for the app's current deployment | | `app list-deploys` | List deployments for the app | | `app show-deploy ` | Show a deployment in detail | | `app promote ` | Make a deployment live behind the app endpoint, starting it first if stopped | | `app rollback` | Roll back production to the previous deployment, without rebuilding | | `app remove` | Remove the app from the current branch | Promote and rollback switch the live endpoint between existing deployments; nothing is rebuilt, and env vars stay as resolved when each deployment was created. Most `app` commands also accept an optional `[app]` positional argument to pick a target from `prisma.compute.ts` when the config defines multiple apps. app deploy options [#app-deploy-options] | Flag | Description | | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `--app ` | Target a specific app; otherwise resolved from `PRISMA_APP_ID`, the app name in `prisma.compute.ts`, the `package.json` name, then the directory name | | `--project ` | Target a specific project | | `--create-project ` | Create and link a new project before deploying | | `--branch ` | Deploy to a specific branch; otherwise your active Git branch, then `main` | | `--framework ` | One of `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, `bun` | | `--entry ` | Entry point, required for `bun` and useful when detection needs a hand | | `--http-port ` | HTTP port your app listens on | | `--region ` | Region for a newly created app; existing apps keep their region | | `--env ` | Environment variable assignment or dotenv file for this deployment (repeatable); `--env` flags replace config env inputs entirely | | `--prod` | Confirm intent to deploy to the production branch | | `--no-promote` | Build the deployment without promoting it to live; promote later with `app promote ` | After the first production deploy, every later production deploy needs `--prod`; without it the deploy fails with `PROD_DEPLOY_REQUIRES_FLAG`. With `--prod`, the CLI asks for confirmation; pass `-y` / `--yes` to accept it up front. In non-interactive mode, a `--prod` deploy without `--yes` fails with `CONFIRMATION_REQUIRED`. The first production deploy is auto-promoted and needs neither flag. A `--no-promote` deploy never replaces the live deployment, so the production gate does not apply. app build options [#app-build-options] | Flag | Description | | --------------------- | ------------------------------------------------------------------------------------- | | `--entry ` | Entry point for Bun apps | | `--build-type ` | One of `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, `bun` | Other app options [#other-app-options] | Flag | Applies to | Description | | -------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `--app`, `--project` | most inspection and deploy commands (`app show-deploy` takes only the deployment id; `app build` is local) | Select the app or project explicitly | | `--deployment ` | `app logs` | Stream logs for a specific deployment | | `--to ` | `app rollback` | Roll back to a specific deployment | | `--yes` | `app remove`, `--prod` deploys | Accept the confirmation prompt | app domain [#app-domain] Manage custom domains for an app. All commands take a `` argument plus `--app` / `--project` / `--branch`, and the optional `[app]` config target. Domains target the production branch; to learn more, see the [Domains docs](/compute/domains). | Command | Description | | ------------------------------ | --------------------------------------------------------- | | `app domain add ` | Register a custom domain on the app's production branch | | `app domain show ` | Show custom domain status and certificate details | | `app domain wait ` | Wait until a custom domain is active or failed | | `app domain retry ` | Retry custom domain DNS verification and TLS provisioning | | `app domain remove ` | Detach a custom domain from the app | `app domain wait` polls for up to 15 minutes by default; pass `--timeout ` to change that, or `--timeout 0` for a single status check. In `--json` mode it streams newline-delimited status events. project [#project] Manage projects and directory bindings. | Command | Description | | --------------------------- | --------------------------------------------- | | `project list` | List all projects in your workspace | | `project show` | Show this directory's project binding | | `project create ` | Create a project and link the directory to it | | `project link [id-or-name]` | Link the directory to an existing project | Linking writes `.prisma/local.json`, a gitignored local pin of the workspace and project. It is a cache, not committed config. Committed configuration lives in `prisma.compute.ts` (or `prisma.compute.json`), which [`init`](#init) writes and the `app` commands read. project env [#project-env] Manage environment variables for the active project. Writes require an explicit scope: exactly one of `--role ` or `--branch `. To learn more, see the [Environment variables docs](/compute/environment-variables). | Command | Description | | ------------------------------------- | ----------------------------------------------------------------------------------- | | `project env add ` | Create a variable; pass just `KEY` to read the value from your environment | | `project env update ` | Replace an existing variable's value; a bare `KEY` also reads from your environment | | `project env list` | List variable names and metadata for a scope, never values | | `project env remove ` | Remove a variable from a scope (`rm` also works) | `add` and `update` also accept `--file ` to read `KEY=VALUE` assignments from a dotenv file, and every `project env` command takes `--project `. Values are write-only: encrypted at rest and never returned by any surface. They resolve at deploy time; redeploy to apply changes. branch [#branch] Inspect platform branches for the resolved project without creating remote state. To learn more, see the [Branching docs](/compute/branching). | Command | Description | | ------------- | ----------------------------------------------- | | `branch list` | List platform branches for the resolved project | database [#database] Manage Prisma Postgres databases for the resolved project. Most commands take `--project ` and `--branch `. | Command | Description | | ----------------------------------------- | -------------------------------------------------------------------- | | `database list` | List databases | | `database show ` | Show a database in detail | | `database create ` | Create a database; `--region` sets the Prisma Postgres region | | `database usage ` | Show usage; `--from` / `--to` bound the period | | `database restore ` | Restore from a backup (`--backup`, `--source-database`, `--confirm`) | | `database remove ` | Remove a database (`--confirm `) | | `database backup list ` | List backups (`--limit `) | | `database connection list ` | List connections | | `database connection create ` | Create a connection (`--name `) | | `database connection rotate ` | Rotate a connection's credentials (`--confirm`) | | `database connection remove ` | Remove a connection (`--confirm`) | git [#git] Manage the GitHub repository connection. To learn more, see the [GitHub integration docs](/compute/github). | Command | Description | | ----------------------- | ------------------------------------------------------------------------------------- | | `git connect [git-url]` | Link the project to a GitHub repository; starts the GitHub App install flow if needed | | `git disconnect` | Stop push-triggered automation; keeps the project and existing branches | In `--json` / `--no-interactive` mode, `git connect` doesn't block: if the GitHub App isn't installed yet, it fails with `REPO_INSTALLATION_REQUIRED` and gives you the install URL. build [#build] Inspect builds that run on the platform (git-push and Console deploys). | Command | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `build logs ` | Stream logs for a platform build; `--follow` keeps streaming as the build runs, `--cursor ` resumes from a prior terminal cursor | agent [#agent] Install and inspect Prisma agent skills; see [Agent skills](#agent-skills) below. | Command | Description | | --------------- | ------------------------------------------------------------------ | | `agent install` | Install Prisma skills for coding agents | | `agent update` | Update installed Prisma skills | | `agent status` | Show installed Prisma skills; `--global` checks the user directory | `agent install` and `agent update` take `--agent ` (repeatable), `--all-agents`, `--skill ` (repeatable), `--global`, `--copy`, and `--dry-run`. version [#version] | Command | Description | | --------- | ------------------------------ | | `version` | Show CLI build and environment | Global flags [#global-flags] | Flag | Description | | ------------------------------------ | ----------------------------------------------------------------- | | `--json` | Emit structured JSON output | | `-y`, `--yes` | Accept supported confirmation prompts | | `-q`, `--quiet` / `-v`, `--verbose` | Adjust output verbosity | | `--trace` | Show deeper diagnostics for failures | | `--interactive` / `--no-interactive` | Force or disable prompts; non-interactive fails instead of asking | | `--color` / `--no-color` | Control colored output | | `--version` | Print the CLI version | JSON output [#json-output] In `--json` mode, every command returns an envelope you can branch on: * `ok`: `true` or `false`. * `result`: the command's data, when `ok` is `true`. * `error.code`, `error.summary`, `error.why`, `error.fix`: what failed and what to do about it. * `nextSteps` and `nextActions`: exact follow-up commands, useful for agents. Branch on `error.code`, not the message text: codes are a stable contract, while message wording can change between releases. Agent skills [#agent-skills] An agent skill teaches a coding agent the Compute deploy workflow. Install it into a repo with: #### bun ```bash bunx skills add prisma/skills --skill prisma-compute ``` #### pnpm ```bash pnpm dlx skills add prisma/skills --skill prisma-compute ``` #### yarn ```bash yarn dlx skills add prisma/skills --skill prisma-compute ``` #### npm ```bash npx skills add prisma/skills --skill prisma-compute ``` This adds the `prisma-compute` skill to `.agents/skills/`, where supported agents pick it up. To install every Prisma skill at once, run `npx skills add prisma/skills`, or use the CLI's [`agent install`](#agent) command, which wraps the same flow. To learn more, see [Agent skills](/compute/getting-started#agent-skills) in the getting started guide. Environment variables [#environment-variables] | Variable | Description | | ---------------------- | --------------------------------------------------------------------------- | | `PRISMA_SERVICE_TOKEN` | Authenticate without a browser (CI); takes priority over any stored session | | `PRISMA_PROJECT_ID` | Override the project resolved from `.prisma/local.json` | | `PRISMA_APP_ID` | Override the app resolution | Error codes [#error-codes] The common codes, grouped by area: **General** | Code | Meaning | | ----------------------- | --------------------------------------------------------------------------------------------------------------------- | | `AUTH_REQUIRED` | No session or service token. Run `auth login` or set `PRISMA_SERVICE_TOKEN`. | | `CONFIRMATION_REQUIRED` | A confirmation prompt can't run here (e.g. a `--prod` deploy in non-interactive mode, or `app remove`). Pass `--yes`. | | `USAGE_ERROR` | Invalid arguments or flags. Check the command's `--help`. | | `FEATURE_UNAVAILABLE` | The platform can't serve this yet (e.g. logs for some deployments). | **Projects and apps** | Code | Meaning | | ------------------------ | ------------------------------------------------------------ | | `PROJECT_SETUP_REQUIRED` | No project resolved. Pass `--project` or `--create-project`. | | `PROJECT_NOT_FOUND` | The named project doesn't exist or isn't visible to you. | | `APP_AMBIGUOUS` | More than one app matched. Pass `--app `. | | `FRAMEWORK_NOT_DETECTED` | The CLI couldn't detect your framework. Pass `--framework`. | **Deployments** | Code | Meaning | | --------------------------- | --------------------------------------------------------------------- | | `PROD_DEPLOY_REQUIRES_FLAG` | A production deploy is missing explicit intent. Re-run with `--prod`. | | `BUILD_FAILED` | The app failed to build. Check the build output. | | `DEPLOY_FAILED` | The deployment failed after the build. | | `DEPLOYMENT_NOT_FOUND` | The deployment id doesn't exist for this app. | | `NO_PREVIOUS_DEPLOYMENT` | Nothing to roll back to. | **Environment variables** | Code | Meaning | | -------------------------------- | ---------------------------------------------------- | | `ENV_VARIABLE_ALREADY_EXISTS` | The key exists in this scope. Use `update` instead. | | `ENV_VARIABLE_NOT_FOUND` | No variable with that key in this scope. | | `ENV_BRANCH_SCOPE_IS_PRODUCTION` | Branch overrides can't target the production branch. | **Domains** | Code | Meaning | | ----------------------------- | ------------------------------------------------------------------ | | `BRANCH_NOT_DEPLOYABLE` | Domain commands targeted a non-production branch. | | `DOMAIN_ALREADY_REGISTERED` | The hostname is already registered. | | `DOMAIN_DNS_NOT_CONFIGURED` | The CNAME record isn't visible yet. | | `DOMAIN_VERIFICATION_FAILED` | DNS verification or TLS provisioning failed. | | `DOMAIN_VERIFICATION_TIMEOUT` | `app domain wait` hit its timeout before the domain became active. | | `DOMAIN_QUOTA_EXCEEDED` | The app already has 3 custom domains. | | `DOMAIN_RETRY_NOT_ELIGIBLE` | The domain isn't in a retryable state. | **GitHub** | Code | Meaning | | ---------------------------- | ------------------------------------------------------- | | `REPO_NOT_CONNECTED` | No repository connected. Run `git connect` first. | | `REPO_ALREADY_CONNECTED` | The project is already connected to a repository. | | `REPO_INSTALLATION_REQUIRED` | The Prisma GitHub App isn't installed in the workspace. | | `REPO_PROVIDER_UNSUPPORTED` | `git connect` with a non-GitHub provider. | Related [#related] * [Get started with `@prisma/cli`](/compute/getting-started) * [Known limitations](/compute/limitations) * [Prisma ORM CLI reference](/cli) for the `prisma` binary ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. - [`Domains`](https://www.prisma.io/docs/compute/domains): Point a custom domain at a production app and the platform verifies DNS and provisions TLS for you. # Configuration (/docs/compute/configuration) Location: Compute > Configuration `prisma.compute.ts` is an optional, committed file that declares what you deploy. [`app deploy`](/compute/cli-reference#app) already works with zero config (it detects your framework and builds), so reach for a config file when you want one of these: * **Reproducible deploys.** Pin the framework, port, and build settings so every deploy (yours, a teammate's, or [deploy-on-push](/compute/github)) does the same thing without re-passing flags. * **A monorepo.** Declare several apps in one repository and deploy them together, or one at a time. * **Type safety.** Catch a typo'd field or an invalid framework in your editor, before you deploy. The file is read by `app deploy` and `app build`. It never selects your project, branch, or production; those stay explicit. It also does not configure a database; that stays on the [`--db` flag](/compute/cli-reference#app-deploy-options). A minimal config [#a-minimal-config] Export a single `app` with `defineComputeConfig`: ```ts title="prisma.compute.ts" import { defineComputeConfig } from "@prisma/compute-sdk/config"; export default defineComputeConfig({ app: { framework: "hono", entry: "src/index.ts", httpPort: 8080, }, }); ``` Every field is optional. An empty `app: {}` is valid and defers entirely to detection. The values you do set become the defaults for `app deploy`; explicit flags still win over them. > [!NOTE] > `defineComputeConfig` is an identity helper that gives the file full type checking. The CLI resolves the import when it reads your config, so the file works without a local install. To get editor types, add the package as a dev dependency: > > > > > #### bun > ```bash > bun add --dev @prisma/compute-sdk > ``` > > > #### pnpm > ```bash > pnpm add -D @prisma/compute-sdk > ``` > > > #### yarn > ```bash > yarn add --dev @prisma/compute-sdk > ``` > > > #### npm > ```bash > npm install -D @prisma/compute-sdk > ``` > > > > JavaScript configs work too: a plain `export default { app: { ... } }` from `prisma.compute.js`/`.mjs`/`.cjs` is valid, just without the type checking. So is a static `prisma.compute.json` with the same shape; it may include a `$schema` field for editor tooling, which is ignored at load time. App fields [#app-fields] Each app accepts these fields. All are optional. | Field | Type | Description | | ----------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The deployed app name. Defaults to the `apps` key, then to inference from `package.json`. | | `region` | region name | Region for a newly created app; existing apps keep their region. See [Regions](#regions). | | `root` | `string` | The app directory, relative to the config file. Defaults to the config file's directory. | | `framework` | framework name | One of `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, `bun`. Defaults to detection. | | `entry` | `string` | Entrypoint path for `bun` and `hono` apps, relative to the app root. Setting it with any other framework is a configuration error. | | `httpPort` | `number` | The port your app listens on. Defaults to the framework's default. | | `env` | `string` or `{ file, vars }` | Environment inputs for the deploy. See [Environment](#environment). | | `build` | `{ command, outputDirectory, entrypoint }` | Build settings. See [Build settings](#build-settings). | ```ts title="prisma.compute.ts" import { defineComputeConfig } from "@prisma/compute-sdk/config"; export default defineComputeConfig({ app: { name: "api", framework: "hono", entry: "src/index.ts", httpPort: 8080, }, }); ``` Regions [#regions] `region` is one of `us-east-1`, `us-west-1`, `eu-west-3`, `eu-central-1`, `ap-northeast-1`, or `ap-southeast-1`. It applies only when a deploy creates the app; an app that already exists keeps its current region. A top-level `region` (next to `app` or `apps`) sets the default for every app in the config; a per-app `region` overrides it. Environment [#environment] `env` is either a dotenv file path, or an object with file path(s) and inline variables: ```ts title="prisma.compute.ts" export default defineComputeConfig({ app: { // Shorthand: a single dotenv file. env: ".env", }, }); ``` ```ts title="prisma.compute.ts" export default defineComputeConfig({ app: { env: { file: [".env", ".env.production"], vars: { LOG_LEVEL: "info" }, }, }, }); ``` File paths resolve from the config file's directory. Any `--env` flag you pass on the command line **replaces** the config's env inputs entirely; they do not merge. > [!NOTE] > `prisma.compute.ts` is committed to your repository, so keep secrets out of inline `vars`. For real secrets and your database connection string, use scoped [environment variables](/compute/environment-variables) instead. Build settings [#build-settings] A `build` block lets you own how an app is built: ```ts title="prisma.compute.ts" export default defineComputeConfig({ app: { framework: "nextjs", build: { command: "pnpm run build", outputDirectory: ".next/standalone", }, }, }); ``` * Every field is optional. A field you set overrides the framework default; a field you omit is inferred. * `command: null` skips the build step entirely. * `entrypoint` names the built artifact's entry file, relative to `outputDirectory` when one is set (otherwise to the app root). For `hono` and `bun` apps it's required whenever you set `outputDirectory`, and setting both `entry` and a differing `build.entrypoint` is a configuration error. * A `build` block works with every framework. With the `custom` framework it's required, and must set both `outputDirectory` and `entrypoint`. Without a `build` block, the CLI infers everything (running your `package.json` build script when there is one, otherwise the framework default) and shows you what it chose during the deploy. Where the file lives [#where-the-file-lives] `app deploy` reads the **nearest** config file, searching from your current directory up to the repository or workspace root (the closest ancestor with a `.git`, `pnpm-workspace.yaml`, `bun.lock`, `bun.lockb`, or a `workspaces` field). Discovery never escapes the repository. Per directory, exactly one of `prisma.compute.ts`, `prisma.compute.mts`, `prisma.compute.js`, `prisma.compute.mjs`, `prisma.compute.cjs`, or `prisma.compute.json` may exist. The config file's directory is treated as the project directory: the [`.prisma/local.json`](/compute/getting-started#link-an-existing-project) project pin lives there, and paths in the config (`root`, `env.file`) resolve from there. That means the config means the same thing no matter which subdirectory you run the command from. Monorepos [#monorepos] Use `apps` instead of `app` to declare several apps in one repository, keyed by a target name: ```ts title="prisma.compute.ts" import { defineComputeConfig } from "@prisma/compute-sdk/config"; export default defineComputeConfig({ apps: { api: { root: "apps/api", framework: "hono", entry: "src/index.ts", }, web: { root: "apps/web", framework: "nextjs", }, }, }); ``` All the apps live in one project, deploying to the same branch. From here: * **Deploy everything** with a bare `app deploy`, which deploys every app in order. This is the default when no target is named or inferred: #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` * **Deploy one app** by naming its target, or by running from inside its `root` (the deepest matching root wins): #### bun ```bash bunx @prisma/cli@latest app deploy api ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy api ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy api ``` #### npm ```bash npx @prisma/cli@latest app deploy api ``` #### bun ```bash cd apps/api && bun x @prisma/cli@latest app deploy ``` #### pnpm ```bash cd apps/api && pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash cd apps/api && yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash cd apps/api && npx @prisma/cli@latest app deploy ``` When you deploy everything at once, per-app flags like `--framework` or `--entry` are rejected as ambiguous. Pass a target to apply them to one app. Project- and branch-level flags (`--branch`, `--db`, `--prod`, `--yes`) apply to the whole run. `app build` always targets a single app in a multi-app config. Unlike `deploy`, it has no all-apps form, so pass a target or run from inside the app's `root`. How config and flags interact [#how-config-and-flags-interact] Config values are deploy **defaults**. Explicit flags always win: * `--framework`, `--entry`, and `--http-port` override their config value. * Any `--env` flag replaces the config's env inputs entirely. * `--app` and `PRISMA_APP_ID` outrank the config's app `name` for app selection. The config never sets your project, branch, or production target; those are always resolved the same way, [from the directory's project link and your Git branch](/compute/cli-reference#app-deploy-options). Settings that did come from the file are labeled `set by prisma.compute.ts` in the deploy output, so you can always see where a value came from. A config that fails to load or validate stops the deploy before any remote work, with a clear message pointing at the field to fix. What's next [#whats-next] * [CLI reference](/compute/cli-reference): every command, flag, and error code. * [Deploy your first app](/prisma-compute/deploy): the end-to-end quickstart. * [Environment variables](/compute/environment-variables): scoped configuration, secrets, and your database connection string. * [GitHub integration](/compute/github): deploy-on-push, including monorepos. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. - [`Domains`](https://www.prisma.io/docs/compute/domains): Point a custom domain at a production app and the platform verifies DNS and provisions TLS for you. # Deployments (/docs/compute/deployments) Location: Compute > Deployments A deployment is one built version of your app. Deployments live inside a [branch](/compute/branching), and the live deployment is the one currently serving traffic. Deploy [#deploy] From your app directory: #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` The CLI resolves your project, branch, and app, builds the code, and returns a live URL. What it resolves: * **Project**: from your linked directory, or `--project` / `--create-project`. * **Branch**: `--branch`, then your active Git branch, then `main`. * **App**: `--app`, or inferred from your `package.json` name or directory. If more than one app matches in non-interactive mode, the deploy fails with `APP_AMBIGUOUS`; pass `--app`. You can pass values straight into a deploy: #### bun ```bash bunx @prisma/cli@latest app deploy --framework hono --entry src/index.ts --http-port 3000 bunx @prisma/cli@latest app deploy --env DATABASE_URL=postgresql://example ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --framework hono --entry src/index.ts --http-port 3000 pnpm dlx @prisma/cli@latest app deploy --env DATABASE_URL=postgresql://example ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --framework hono --entry src/index.ts --http-port 3000 yarn dlx @prisma/cli@latest app deploy --env DATABASE_URL=postgresql://example ``` #### npm ```bash npx @prisma/cli@latest app deploy --framework hono --entry src/index.ts --http-port 3000 npx @prisma/cli@latest app deploy --env DATABASE_URL=postgresql://example ``` `--env` is for one-off values at deploy time. For variables that should persist across deploys, set them on the project. To learn more, see the [Environment variables docs](/compute/environment-variables). Build locally [#build-locally] Check your app builds before you ship it: #### bun ```bash bunx @prisma/cli@latest app build ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app build ``` #### yarn ```bash yarn dlx @prisma/cli@latest app build ``` #### npm ```bash npx @prisma/cli@latest app build ``` `app build` supports the build types `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`. Deploy to production [#deploy-to-production] Your first deployment is promoted to production automatically. After that, every production deploy needs an explicit `--prod` flag, so you don't ship to production by accident: #### bun ```bash bunx @prisma/cli@latest app deploy --prod ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod ``` Without `--prod`, a deploy that resolves to the production branch and already has a live production deployment fails with `PROD_DEPLOY_REQUIRES_FLAG`. With `--prod`, the CLI shows the current live deployment and asks you to confirm before replacing it. For scripts and CI, pass both flags so nothing waits on a prompt: #### bun ```bash bunx @prisma/cli@latest app deploy --prod --yes ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod --yes ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod --yes ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod --yes ``` In non-interactive mode, a `--prod` deploy without `--yes` fails with `CONFIRMATION_REQUIRED`. Preview deploys never need `--prod` and never ask. Inspect deployments [#inspect-deployments] #### bun ```bash bunx @prisma/cli@latest app show --app web bunx @prisma/cli@latest app open --app web bunx @prisma/cli@latest app list-deploys --app web bunx @prisma/cli@latest app show-deploy dep_123 ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app show --app web pnpm dlx @prisma/cli@latest app open --app web pnpm dlx @prisma/cli@latest app list-deploys --app web pnpm dlx @prisma/cli@latest app show-deploy dep_123 ``` #### yarn ```bash yarn dlx @prisma/cli@latest app show --app web yarn dlx @prisma/cli@latest app open --app web yarn dlx @prisma/cli@latest app list-deploys --app web yarn dlx @prisma/cli@latest app show-deploy dep_123 ``` #### npm ```bash npx @prisma/cli@latest app show --app web npx @prisma/cli@latest app open --app web npx @prisma/cli@latest app list-deploys --app web npx @prisma/cli@latest app show-deploy dep_123 ``` `app show` describes the live app, `app open` opens its URL, `app list-deploys` lists the deployment history, and `app show-deploy` shows one deployment in detail. Logs [#logs] Stream logs for the live deployment, or for a specific one: #### bun ```bash bunx @prisma/cli@latest app logs --app web bunx @prisma/cli@latest app logs --app web --deployment dep_123 ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app logs --app web pnpm dlx @prisma/cli@latest app logs --app web --deployment dep_123 ``` #### yarn ```bash yarn dlx @prisma/cli@latest app logs --app web yarn dlx @prisma/cli@latest app logs --app web --deployment dep_123 ``` #### npm ```bash npx @prisma/cli@latest app logs --app web npx @prisma/cli@latest app logs --app web --deployment dep_123 ``` Your app's log lines go to stdout; the CLI's own status and errors go to stderr, so you can pipe them apart. If the log stream can't be served for the resolved deployment, the command fails with `DEPLOY_FAILED`. Promote and roll back [#promote-and-roll-back] Promote an earlier deployment to be the live one: #### bun ```bash bunx @prisma/cli@latest app promote dep_123 --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app promote dep_123 --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app promote dep_123 --app web ``` #### npm ```bash npx @prisma/cli@latest app promote dep_123 --app web ``` Promotion makes an existing deployment live behind the app's endpoint. If the deployment is stopped, it's started first and promoted once it's running. Nothing is rebuilt: environment variables are baked in when a deployment is created, so a promoted deployment keeps the config it was built with. To build a deployment without making it live, deploy with `--no-promote` and promote it later. Roll back to the previous deployment, or a specific one. Rollback works the same way — it reuses an existing build and just targets the previous deployment, so there is no rebuild step between you and a known-good state: #### bun ```bash bunx @prisma/cli@latest app rollback --app web bunx @prisma/cli@latest app rollback --app web --to dep_123 ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app rollback --app web pnpm dlx @prisma/cli@latest app rollback --app web --to dep_123 ``` #### yarn ```bash yarn dlx @prisma/cli@latest app rollback --app web yarn dlx @prisma/cli@latest app rollback --app web --to dep_123 ``` #### npm ```bash npx @prisma/cli@latest app rollback --app web npx @prisma/cli@latest app rollback --app web --to dep_123 ``` If there's nothing to roll back to, you get `NO_PREVIOUS_DEPLOYMENT`. Remove an app [#remove-an-app] #### bun ```bash bunx @prisma/cli@latest app remove --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app remove --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app remove --app web ``` #### npm ```bash npx @prisma/cli@latest app remove --app web ``` This removes the app from the current branch. Pass `--yes` to skip the confirmation prompt. Next steps [#next-steps] * [Environment variables](/compute/environment-variables): persist config across deploys. * [GitHub integration](/compute/github): deploy on push instead of manually. * [Domains](/compute/domains): point a custom domain at production. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Domains`](https://www.prisma.io/docs/compute/domains): Point a custom domain at a production app and the platform verifies DNS and provisions TLS for you. # Domains (/docs/compute/domains) Location: Compute > Domains Configure custom domains that point to your [production app](/compute/branching). You can't configure custom domains for preview apps. Before you start [#before-you-start] You'll need: * A [linked project](/compute/getting-started). * A production app with a [promoted, running deployment](/compute/deployments). * Access to edit DNS records within your DNS provider. Domain commands target the [production branch](/compute/branching). Pointing them at any other branch fails with [`BRANCH_NOT_DEPLOYABLE`](/compute/cli-reference#error-codes). Every domain subcommand also accepts `--project` and `--branch` flags. Add a custom domain [#add-a-custom-domain] 1. Add a domain [#1-add-a-domain] #### bun ```bash bunx @prisma/cli@latest app domain add shop.acme.com --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain add shop.acme.com --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain add shop.acme.com --app web ``` #### npm ```bash npx @prisma/cli@latest app domain add shop.acme.com --app web ``` Registration verifies DNS up front. If the **CNAME** record isn't visible yet, the command fails with [`DOMAIN_DNS_NOT_CONFIGURED`](/compute/cli-reference#error-codes) and prints the record name and value for you to create. Re-running `add` for a hostname that's already attached is safe: it shows the existing domain instead of failing. 2. Create CNAME Record [#2-create-cname-record] Add the printed DNS record, which points at `switchboard.{region}.prisma.build`. Example: | Type | Name | Value | TTL | | ----- | --------------- | ------------------------------ | --- | | CNAME | `shop.acme.com` | `switchboard.cdg.prisma.build` | 300 | The CLI prints the record name as the full hostname. If your DNS provider expects a relative name, enter just the label (`shop`). > [!NOTE] > What is switchboard? > > Switchboard is the routing layer that sits in front of your Compute app. Switchboard verifies the domain, provisions and terminates TLS, then forwards traffic to your app: one domain, one CNAME, one Compute app. 3. Re-run add, then wait for provisioning [#3-re-run-add-then-wait-for-provisioning] Once the CNAME record has propagated, re-run `app domain add`. This time registration succeeds and TLS provisioning starts. Track it with: #### bun ```bash bunx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### npm ```bash npx @prisma/cli@latest app domain wait shop.acme.com --app web ``` `wait` polls until the domain is active, up to 15 minutes. For a single status check, use `--timeout 0`: #### bun ```bash bunx @prisma/cli@latest app domain wait shop.acme.com --app web --timeout 0 --json ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain wait shop.acme.com --app web --timeout 0 --json ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain wait shop.acme.com --app web --timeout 0 --json ``` #### npm ```bash npx @prisma/cli@latest app domain wait shop.acme.com --app web --timeout 0 --json ``` A single check exits non-zero with `DOMAIN_VERIFICATION_TIMEOUT` while the domain is still provisioning, so automation should read the status event rather than the exit code. In `--json` mode, `wait` streams newline-delimited status events, so an agent can track provisioning as it progresses. Remove a domain [#remove-a-domain] #### bun ```bash bunx @prisma/cli@latest app domain remove shop.acme.com --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain remove shop.acme.com --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain remove shop.acme.com --app web ``` #### npm ```bash npx @prisma/cli@latest app domain remove shop.acme.com --app web ``` Removing detaches the domain from the app; pass `--yes` to skip the confirmation prompt. Prisma can't touch your DNS, so the CNAME record stays behind: delete it at your provider once you no longer need it. States [#states] A domain moves through these states: | Status | Meaning | | ------------------ | --------------------------------------------------------------- | | `pending_dns` | The domain is registered; TLS provisioning hasn't started yet | | `provisioning_tls` | The TLS certificate is being issued | | `active` | The domain is fully provisioned and routing traffic to your app | | `failed` | Registration or provisioning failed; see the failure reason | Limits [#limits] * Custom domains are only available on production apps. * DNS uses CNAME records only. Apex domains need a DNS provider that supports CNAME-like records (ALIAS, ANAME, or CNAME flattening) at the apex. * Wildcard hostnames such as `*.acme.com` are rejected. * Up to 3 custom domains per app; more returns `DOMAIN_QUOTA_EXCEEDED`. * There's no workspace-wide domain list in the CLI. Troubleshooting [#troubleshooting] #### bun ```bash bunx @prisma/cli@latest app domain show shop.acme.com --app web bunx @prisma/cli@latest app domain retry shop.acme.com --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain show shop.acme.com --app web pnpm dlx @prisma/cli@latest app domain retry shop.acme.com --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain show shop.acme.com --app web yarn dlx @prisma/cli@latest app domain retry shop.acme.com --app web ``` #### npm ```bash npx @prisma/cli@latest app domain show shop.acme.com --app web npx @prisma/cli@latest app domain retry shop.acme.com --app web ``` `show` gives you the exact state, certificate details, and any DNS hints. `retry` restarts stuck provisioning; if a domain isn't in a retryable state, it returns `DOMAIN_RETRY_NOT_ELIGIBLE`. Next steps [#next-steps] * [Deployments](/compute/deployments): promote a deployment to production first. * [Known limitations](/compute/limitations): what the beta can and can't do. * [`app domain` reference](/compute/cli-reference#app-domain): every domain subcommand and flag. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # Environment variables (/docs/compute/environment-variables) Location: Compute > Environment variables Environment variables are project configuration that gets injected into your deployments. You scope each one to production, to preview, or to a single preview branch. This is also how you connect your app to a database: set its connection string as a variable like `DATABASE_URL`. How it works [#how-it-works] There are three layers: 1. **Production variables**: used by production deploys. 2. **Preview variables**: used by every preview deploy. 3. **Branch overrides**: replace a preview value for one specific branch. A preview deploy gets the preview variables, with any branch overrides layered on top. Overrides help when one branch needs a different API key, database URL, or feature flag than the rest. Values are resolved at deploy time and baked into the deployment. Changing a variable doesn't touch deployments that already exist and doesn't trigger a redeploy; the new value applies the next time you deploy. Set a variable [#set-a-variable] Pass `KEY=value` and a role or branch: #### bun ```bash bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://example --role production bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://preview --role preview bunx @prisma/cli@latest project env add FEATURE_FLAG=enabled --branch feature/search ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project env add DATABASE_URL=postgresql://example --role production pnpm dlx @prisma/cli@latest project env add DATABASE_URL=postgresql://preview --role preview pnpm dlx @prisma/cli@latest project env add FEATURE_FLAG=enabled --branch feature/search ``` #### yarn ```bash yarn dlx @prisma/cli@latest project env add DATABASE_URL=postgresql://example --role production yarn dlx @prisma/cli@latest project env add DATABASE_URL=postgresql://preview --role preview yarn dlx @prisma/cli@latest project env add FEATURE_FLAG=enabled --branch feature/search ``` #### npm ```bash npx @prisma/cli@latest project env add DATABASE_URL=postgresql://example --role production npx @prisma/cli@latest project env add DATABASE_URL=postgresql://preview --role preview npx @prisma/cli@latest project env add FEATURE_FLAG=enabled --branch feature/search ``` To keep a secret out of your shell history, pass just the key and let the CLI read it from your environment: ```bash DATABASE_URL=postgresql://example npx @prisma/cli@latest project env add DATABASE_URL --role production ``` To import many variables at once, pass a dotenv file with `--file` instead of a `KEY=value` argument (one or the other, not both). It works for `add` and `update`: #### bun ```bash bunx @prisma/cli@latest project env add --file .env.production --role production ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project env add --file .env.production --role production ``` #### yarn ```bash yarn dlx @prisma/cli@latest project env add --file .env.production --role production ``` #### npm ```bash npx @prisma/cli@latest project env add --file .env.production --role production ``` Connect a database [#connect-a-database] To give your app a database, set its connection string per scope, then redeploy. Use a different database per scope if you want preview deployments isolated from production data. > [!NOTE] > Don't assume production data is copied into preview branches, and don't assume migrations run automatically on deploy. Run migrations yourself against the right database. List, update, remove [#list-update-remove] #### bun ```bash bunx @prisma/cli@latest project env list --role production bunx @prisma/cli@latest project env list --branch feature/search bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production bunx @prisma/cli@latest project env remove DATABASE_URL --role preview ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project env list --role production pnpm dlx @prisma/cli@latest project env list --branch feature/search pnpm dlx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production pnpm dlx @prisma/cli@latest project env remove DATABASE_URL --role preview ``` #### yarn ```bash yarn dlx @prisma/cli@latest project env list --role production yarn dlx @prisma/cli@latest project env list --branch feature/search yarn dlx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production yarn dlx @prisma/cli@latest project env remove DATABASE_URL --role preview ``` #### npm ```bash npx @prisma/cli@latest project env list --role production npx @prisma/cli@latest project env list --branch feature/search npx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production npx @prisma/cli@latest project env remove DATABASE_URL --role preview ``` `list --role` shows names and metadata, never values. `list --branch` shows the resolved view for one branch. `rm` works as an alias for `remove`. `add` never overwrites: it fails if the key already exists in that scope, so use `update` to change a value. Every `project env` subcommand also accepts `--project ` to target a project other than the linked one. Values are write-only [#values-are-write-only] Once you save a variable, the platform never gives it back. Values are encrypted at rest and never returned: not by the CLI, the API, or the Console. In practice: * `project env list` shows keys and metadata, not values. * There's no command to pull values into a local `.env`. * To rotate a secret, `project env update` it and redeploy. * To confirm an app sees a value, redeploy and check its behavior or logs. Keep your own copy of every value in a secret manager. Treat Prisma as the place values are *injected*, not a store you read back from. Rules [#rules] * Keys must match `[A-Z_][A-Z0-9_]*`, up to 256 characters. * Values must be non-empty, up to 8 KB. * Production variables can't be branch-scoped: use `--role production` for production, and `--branch ` only for preview overrides. In CI and agents [#in-ci-and-agents] Add `--json` so the output is machine-readable, and `--no-interactive` so the CLI fails with an error code instead of waiting on a prompt nothing will answer: #### bun ```bash bunx @prisma/cli@latest project env list --role preview --json --no-interactive ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project env list --role preview --json --no-interactive ``` #### yarn ```bash yarn dlx @prisma/cli@latest project env list --role preview --json --no-interactive ``` #### npm ```bash npx @prisma/cli@latest project env list --role preview --json --no-interactive ``` Don't build anything that depends on reading a value back. Pass the source value in from your own secret store, and let Prisma handle injection at deploy time. Next steps [#next-steps] * [Deployments](/compute/deployments): redeploy to apply new values. * [Branching](/compute/branching): how preview branches work. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # FAQ (/docs/compute/faq) Location: Compute > FAQ Which package do I install? [#which-package-do-i-install] You install [`@prisma/cli`](/compute/getting-started), which provides an executable called `prisma-cli`. The quickest way to run it without installing anything is: #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` Why prisma-cli and not prisma? [#why-prisma-cli-and-not-prisma] It avoids shadowing the `prisma` binary from [Prisma ORM](/orm), which many projects already have installed. To set up a shorter command, add your own package script; see [A shorter command](/compute/getting-started#a-shorter-command) in the getting started guide. What's the difference between a project and an app? [#whats-the-difference-between-a-project-and-an-app] A project groups the resources for one product or codebase. An app is a single HTTP service inside a project's branch. The full hierarchy: What's a branch? [#whats-a-branch] A branch is an isolated environment for one line of work. It usually matches a Git branch name, but in Prisma it is a real resource that owns its own apps and databases. To learn more, see the [Branching docs](/compute/branching). Does git connect deploy my app? [#does-git-connect-deploy-my-app] No, it links a project to a GitHub repository and turns on automation for future branch and push events. It does not deploy anything by itself, so if you want to ship right now, run `app deploy`. To set the connection up, see the [GitHub integration docs](/compute/github). What does a GitHub push do? [#what-does-a-github-push-do] When a project is connected to GitHub, each push creates or resolves the matching branch and builds the pushed commit. Why can't I read my environment variable values back? [#why-cant-i-read-my-environment-variable-values-back] In beta, variable values are encrypted and never returned by any surface. `project env list` shows only the keys and their metadata, so keep your own copy of each value in a secret manager. To learn more, see [Values are write-only](/compute/environment-variables#values-are-write-only). How do I rotate a secret? [#how-do-i-rotate-a-secret] Update it, then redeploy to production: #### bun ```bash bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production bunx @prisma/cli@latest app deploy --prod --yes ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production pnpm dlx @prisma/cli@latest app deploy --prod --yes ``` #### yarn ```bash yarn dlx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production yarn dlx @prisma/cli@latest app deploy --prod --yes ``` #### npm ```bash npx @prisma/cli@latest project env update DATABASE_URL=postgresql://new --role production npx @prisma/cli@latest app deploy --prod --yes ``` `--prod` signals intent to deploy to production, and `--yes` accepts the confirmation up front. Does changing a variable redeploy my app? [#does-changing-a-variable-redeploy-my-app] No. Variables resolve at deploy time, so you need to redeploy for the app to pick up a new value. How do I deploy from CI? [#how-do-i-deploy-from-ci] Use a service token and explicit targets: ```bash PRISMA_SERVICE_TOKEN=... npx @prisma/cli@latest app deploy \ --project my-app \ --app web \ --branch "$GITHUB_HEAD_REF" \ --json \ --no-interactive ``` Passing every target explicitly keeps the run self-contained; `--json` makes the result parseable, and `--no-interactive` turns any would-be prompt into a structured error. Why did my production deploy fail with PROD_DEPLOY_REQUIRES_FLAG? [#why-did-my-production-deploy-fail-with-prod_deploy_requires_flag] Your first deploy is promoted to production automatically. After that, deploying to the production branch needs an explicit `--prod` flag. Re-run with `npx @prisma/cli@latest app deploy --prod`, or deploy from a preview branch instead. Why did my production deploy fail with CONFIRMATION_REQUIRED? [#why-did-my-production-deploy-fail-with-confirmation_required] A `--prod` deploy asks you to confirm before replacing the live deployment, and that prompt can't run in non-interactive mode. Pass both flags, `--prod --yes`, to accept the confirmation up front. (`app remove` uses the same `--yes` confirmation.) Why PROJECT_SETUP_REQUIRED? [#why-project_setup_required] This means the CLI couldn't work out which project to deploy to, because the current directory isn't linked to one yet. Create or link a project first with `project create` or `project link`, or name one directly on the command with `--project` or `--create-project`. Why APP_AMBIGUOUS? [#why-app_ambiguous] This means your project holds more than one app, so the CLI can't tell which one you meant. Tell it explicitly by passing `--app ` with the name of the app you want to deploy. How do I add a custom domain? [#how-do-i-add-a-custom-domain] Promote a production app, then: #### bun ```bash bunx @prisma/cli@latest app domain add shop.acme.com --app web bunx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app domain add shop.acme.com --app web pnpm dlx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app domain add shop.acme.com --app web yarn dlx @prisma/cli@latest app domain wait shop.acme.com --app web ``` #### npm ```bash npx @prisma/cli@latest app domain add shop.acme.com --app web npx @prisma/cli@latest app domain wait shop.acme.com --app web ``` Add the CNAME record the command returns at your DNS provider. To learn more, see the [Domains docs](/compute/domains). Can preview branches have custom domains? [#can-preview-branches-have-custom-domains] No. In beta, custom domains are production-only, so they cannot be attached to preview branches. Does Prisma clone my production database for previews? [#does-prisma-clone-my-production-database-for-previews] You should not assume it does. These docs cover app deployment and runtime configuration only, so pass database URLs through [environment variables](/compute/environment-variables) and manage data and migrations yourself. Do I need Prisma Postgres to use Compute? [#do-i-need-prisma-postgres-to-use-compute] No. Your app connects to a database through a connection string you set as an environment variable, such as `DATABASE_URL`. Compute and [Prisma Postgres](/postgres) are designed to work well together, and running both keeps your app next to your database. Can I use the Console instead? [#can-i-use-the-console-instead] Yes. Use it to inspect projects, branches, apps, deployments, integrations, env var names, and domain status. Is Prisma Compute free? [#is-prisma-compute-free] Yes, Compute is free during public beta. We've published the rates we expect to charge once we enable production billing, so you can estimate future usage now. See [Pricing](https://pris.ly/pricing-compute) for the rates, worked examples, and what is not billed separately. For how those rates compare to Vercel's for the same workload, see [Prisma Compute vs Vercel pricing](https://www.prisma.io/blog/prisma-compute-vs-vercel-pricing?utm_source=docs). What does Public Beta mean for Compute? [#what-does-public-beta-mean-for-compute] The core model and documented happy paths are stable enough for evaluation, staging, internal tools, and low-risk apps; details like limits, pricing, and some CLI, API, and Console behavior can still change before general availability. See [Public Beta](/console/more/feature-maturity#public-beta) on the feature maturity page. What are the current limits? [#what-are-the-current-limits] See [Known limitations](/compute/limitations) for what the beta can and can't do. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # @prisma/cli (/docs/compute/getting-started) Location: Compute > @prisma/cli Deploy an app to [Prisma Compute](/compute) in two commands: sign in, then `app deploy`. This guide takes you from your code to a live URL, then covers the variations you'll need next. For every command, flag, and error code, see the [CLI reference](/compute/cli-reference). Install nothing up front: run the [`@prisma/cli`](https://github.com/prisma/prisma-cli) beta package directly with `npx`. The package installs an executable called `prisma-cli`. Prerequisites [#prerequisites] * A JavaScript runtime. The commands below run with `npx` or `pnpm` on Node.js 22.12 or newer, or with `bunx` (Bun). * A [Prisma Data Platform account](https://pris.ly/pdp). * An app directory to deploy. Sign in [#sign-in] Deploys fail without a session, so authenticate first: #### bun ```bash bunx @prisma/cli@latest auth login ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest auth login ``` #### yarn ```bash yarn dlx @prisma/cli@latest auth login ``` #### npm ```bash npx @prisma/cli@latest auth login ``` This opens a browser to sign you in, then stores a session that every later command inherits, including any coding agent working in your directory. The browser step needs a human; in CI or other headless environments, use a [service token](#automation-and-ci) instead. To check who you're signed in as, run `auth whoami`. Deploy your app [#deploy-your-app] From your app directory, run: #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` Then the CLI sets up the project, builds your app, and deploys it. After it finishes, you get a live URL. To stream the app's logs: #### bun ```bash bunx @prisma/cli@latest app logs ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app logs ``` #### yarn ```bash yarn dlx @prisma/cli@latest app logs ``` #### npm ```bash npx @prisma/cli@latest app logs ``` To open the live URL in your browser: #### bun ```bash bunx @prisma/cli@latest app open ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app open ``` #### yarn ```bash yarn dlx @prisma/cli@latest app open ``` #### npm ```bash npx @prisma/cli@latest app open ``` That is the core deploy loop. The sections below cover variations on it. A shorter command [#a-shorter-command] The binary is `prisma-cli`, not `prisma`. That's deliberate: many projects already have the `prisma` binary from [Prisma ORM](/orm), and the beta package doesn't shadow it. To avoid typing `npx @prisma/cli@latest` each time, install the package and add your own script: #### bun ```bash bun add --dev @prisma/cli ``` #### pnpm ```bash pnpm add --save-dev @prisma/cli ``` #### yarn ```bash yarn add --dev @prisma/cli ``` #### npm ```bash npm install --save-dev @prisma/cli ``` ```json title="package.json" { "scripts": { "deploy": "prisma-cli app deploy" } } ``` Now `npm run deploy` does the same thing. Link an existing project [#link-an-existing-project] On your first deploy, the CLI creates a project for you. If your team already has one, link to it before you deploy instead: #### bun ```bash bunx @prisma/cli@latest project link my-app ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project link my-app ``` #### yarn ```bash yarn dlx @prisma/cli@latest project link my-app ``` #### npm ```bash npx @prisma/cli@latest project link my-app ``` Either path writes `.prisma/local.json`, a gitignored file that pins this directory to a project. It's a local cache, not committed config. Two commands to check your wiring: #### bun ```bash bunx @prisma/cli@latest project show bunx @prisma/cli@latest project list ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest project show pnpm dlx @prisma/cli@latest project list ``` #### yarn ```bash yarn dlx @prisma/cli@latest project show yarn dlx @prisma/cli@latest project list ``` #### npm ```bash npx @prisma/cli@latest project show npx @prisma/cli@latest project list ``` `project show` tells you what this directory is linked to; `project list` shows the projects you can see. Pick a framework [#pick-a-framework] The CLI detects your framework automatically. Today there is first-class support for **Next.js**, **Nuxt**, **Astro**, **Hono**, **NestJS**, and **TanStack Start**: #### bun ```bash bunx @prisma/cli@latest app deploy --framework nextjs bunx @prisma/cli@latest app deploy --framework hono --entry src/index.ts bunx @prisma/cli@latest app deploy --framework tanstack-start ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --framework nextjs pnpm dlx @prisma/cli@latest app deploy --framework hono --entry src/index.ts pnpm dlx @prisma/cli@latest app deploy --framework tanstack-start ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --framework nextjs yarn dlx @prisma/cli@latest app deploy --framework hono --entry src/index.ts yarn dlx @prisma/cli@latest app deploy --framework tanstack-start ``` #### npm ```bash npx @prisma/cli@latest app deploy --framework nextjs npx @prisma/cli@latest app deploy --framework hono --entry src/index.ts npx @prisma/cli@latest app deploy --framework tanstack-start ``` Deploy a plain Bun server by pointing `--entry` at your server file: #### bun ```bash bunx @prisma/cli@latest app deploy --framework bun --entry src/server.ts ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --framework bun --entry src/server.ts ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --framework bun --entry src/server.ts ``` #### npm ```bash npx @prisma/cli@latest app deploy --framework bun --entry src/server.ts ``` > [!NOTE] > Next.js apps should set `output: "standalone"` in their Next.js config. > > ```ts title="next.config.ts" > export default { output: "standalone" }; > ``` Check it builds locally [#check-it-builds-locally] Before you deploy, you can build the app on your machine: #### bun ```bash bunx @prisma/cli@latest app build ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app build ``` #### yarn ```bash yarn dlx @prisma/cli@latest app build ``` #### npm ```bash npx @prisma/cli@latest app build ``` Deploy to production [#deploy-to-production] Your first deployment is promoted to production automatically. After that, every production deploy needs an explicit `--prod` flag, so you don't ship to production by accident: #### bun ```bash bunx @prisma/cli@latest app deploy --prod ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod ``` Without `--prod`, a deploy that resolves to the production branch and already has a live production deployment fails with the error code `PROD_DEPLOY_REQUIRES_FLAG`. With `--prod`, the CLI shows the current live deployment and asks you to confirm before replacing it. For scripts and CI, pass both `--prod` and `-y` / `--yes` to accept the confirmation up front: #### bun ```bash bunx @prisma/cli@latest app deploy --prod --yes ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod --yes ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod --yes ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod --yes ``` In non-interactive mode, a `--prod` deploy without `--yes` can't prompt, so it fails with `CONFIRMATION_REQUIRED`; re-run with `--prod --yes`. Preview deploys never need `--prod` and never ask for confirmation. To build a new deployment without making it live, pass `--no-promote` and promote it later with `app promote `. To learn about promotion and rollback, see the [Deployments docs](/compute/deployments). Automation and CI [#automation-and-ci] The CLI is built for agents and CI, not just terminals. If you've already signed in with `auth login`, anything running in that environment inherits your session, including an agent working in your directory. Check the session: #### bun ```bash bunx @prisma/cli@latest auth whoami ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest auth whoami ``` #### yarn ```bash yarn dlx @prisma/cli@latest auth whoami ``` #### npm ```bash npx @prisma/cli@latest auth whoami ``` For CI, or any environment where the browser sign-in isn't an option, authenticate with a **service token** instead. Set `PRISMA_SERVICE_TOKEN` and the CLI uses it before any stored session: ```bash PRISMA_SERVICE_TOKEN=... npx @prisma/cli@latest app deploy \ --project my-app \ --app web \ --branch feature/search \ --json \ --no-interactive ``` Pass targets explicitly so nothing depends on a prompt. `--json` gives you structured output to parse; `--no-interactive` makes the CLI fail instead of asking. In non-interactive mode the CLI won't set up a project for you, so create it inline when you need a self-contained run: #### bun ```bash bunx @prisma/cli@latest app deploy --create-project my-app --app web ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --create-project my-app --app web ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --create-project my-app --app web ``` #### npm ```bash npx @prisma/cli@latest app deploy --create-project my-app --app web ``` Agent skills [#agent-skills] If a coding agent does your deploying, install the Prisma Compute agent skill into your repo: #### bun ```bash bunx skills add prisma/skills --skill prisma-compute ``` #### pnpm ```bash pnpm dlx skills add prisma/skills --skill prisma-compute ``` #### yarn ```bash yarn dlx skills add prisma/skills --skill prisma-compute ``` #### npm ```bash npx skills add prisma/skills --skill prisma-compute ``` The `prisma-compute` skill teaches your agent the Compute deploy workflow (auth, framework detection, deploys, logs, and domains), so it follows the right steps. Supported agents pick it up automatically from `.agents/skills/`. To install every Prisma skill (ORM CLI, Postgres, and more) at once, run `npx skills add prisma/skills`. Structured output [#structured-output] In `--json` mode, every result is an envelope with an `ok` flag. On failure, `error.code` identifies the problem, `error.fix` says what to do about it, and `nextSteps` lists the exact commands to run next. Branch on the error code rather than the message: codes are a stable contract, while message wording can change between releases. The common ones: | Code | Meaning | | --------------------------- | ------------------------------------------------------------------------------------ | | `PROJECT_SETUP_REQUIRED` | No project resolved. Pass `--project` or `--create-project`. | | `APP_AMBIGUOUS` | More than one app matched. Pass `--app `. | | `PROD_DEPLOY_REQUIRES_FLAG` | A production deploy is missing explicit intent. Re-run with `--prod`. | | `CONFIRMATION_REQUIRED` | A `--prod` deploy can't prompt for confirmation here. Pass `--prod --yes`. | | `FEATURE_UNAVAILABLE` | The platform can't serve this yet (e.g. the app has no live URL yet for `app open`). | For the full list, see the [error codes reference](/compute/cli-reference#error-codes). Console [#console] To view your resources instead of running commands, use the [Console](https://pris.ly/pdp) for projects, branches, apps, deployments, integrations, and domains. It shows them in a visual way and lets you manage them with buttons instead of commands. Next steps [#next-steps] * [CLI reference](/compute/cli-reference): every command, flag, and error code. * [Deployments](/compute/deployments): inspect, promote, roll back, remove. * [Environment variables](/compute/environment-variables): give your app a database connection string and other config. * [Branching](/compute/branching): how branches isolate work and map to Git. * [GitHub integration](/compute/github): deploy on push. ## Related pages - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. - [`Domains`](https://www.prisma.io/docs/compute/domains): Point a custom domain at a production app and the platform verifies DNS and provisions TLS for you. # GitHub (/docs/compute/github) Location: Compute > GitHub Connect a GitHub repository to a project and Prisma deploys on every push. Branch and push events map to platform branches automatically, so your previews track your Git branches. How it works [#how-it-works] The connection has two levels: The workspace owns the GitHub App installation; each project points at a single repository. Once connected, Prisma listens for that repo's branch events and keeps the matching platform branches in sync. In beta, a project connects to one repository. Connect a repo [#connect-a-repo] From a linked project directory, connect your Git origin: #### bun ```bash bunx @prisma/cli@latest git connect ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest git connect ``` #### yarn ```bash yarn dlx @prisma/cli@latest git connect ``` #### npm ```bash npx @prisma/cli@latest git connect ``` To name the repository explicitly: #### bun ```bash bunx @prisma/cli@latest git connect https://github.com/acme/shop ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest git connect https://github.com/acme/shop ``` #### yarn ```bash yarn dlx @prisma/cli@latest git connect https://github.com/acme/shop ``` #### npm ```bash npx @prisma/cli@latest git connect https://github.com/acme/shop ``` If the GitHub App isn't installed yet, the CLI starts the install flow. In `--json` / `--no-interactive` mode it doesn't block: it gives you the install URL to finish in the browser, so automation can hand the install off: #### bun ```bash bunx @prisma/cli@latest git connect https://github.com/acme/shop --json --no-interactive ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest git connect https://github.com/acme/shop --json --no-interactive ``` #### yarn ```bash yarn dlx @prisma/cli@latest git connect https://github.com/acme/shop --json --no-interactive ``` #### npm ```bash npx @prisma/cli@latest git connect https://github.com/acme/shop --json --no-interactive ``` Disconnect when you're done: #### bun ```bash bunx @prisma/cli@latest git disconnect ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest git disconnect ``` #### yarn ```bash yarn dlx @prisma/cli@latest git disconnect ``` #### npm ```bash npx @prisma/cli@latest git disconnect ``` Disconnecting stops future automation. It doesn't delete the project or tear down existing branches. What events do [#what-events-do] Once a project is connected: * **Branch created** → creates the matching platform branch. * **Push** → creates or resolves the matching branch and builds the pushed commit. * **Branch deleted** → tears down the matching branch, unless it's the production or default branch. Connecting doesn't deploy anything on its own; it wires up automation for *future* events. To deploy right now, run `app deploy` yourself. CI and monorepos [#ci-and-monorepos] Auto-deploy handles monorepos that declare their apps in `prisma.compute.ts`: one pushed commit fans out into a targeted build per app. For custom pipelines, or anywhere you want full control, run the CLI directly with a service token and explicit targets: ```bash PRISMA_SERVICE_TOKEN=... npx @prisma/cli@latest app deploy \ --project my-app \ --app web \ --branch "$GITHUB_HEAD_REF" \ --json \ --no-interactive ``` This keeps deploys deterministic and gives agents a structured result to read. What's not in beta [#whats-not-in-beta] GitHub is the only supported provider; others return `REPO_PROVIDER_UNSUPPORTED`. The webhook path is branch- and push-driven. Each webhook deployment posts a "Prisma Compute Deploy" check run on the commit — success or failure, with the deploy URL — on a best-effort basis. Pull-request comments and preview comments aren't part of the beta surface. Next steps [#next-steps] * [Branching](/compute/branching): how platform branches map to Git. * [Deployments](/compute/deployments): what happens after a push builds. * [Environment variables](/compute/environment-variables): per-branch config for previews. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # Image Transformations (/docs/compute/image-transformations) Location: Compute > Image Transformations [Prisma Compute](/compute) apps run on Bun, and Bun ships [`Bun.Image`](https://bun.com/docs/runtime/image): a native pipeline for decoding, resizing, rotating, flipping, adjusting, and re-encoding images. So you build image transformations as part of your app, not as a separate image service. A transformation route is an ordinary [Compute deployment](/compute/deployments). It handles a request, uses CPU and memory, and returns bytes, and it is billed and operated like every other route in your app. What Bun handles natively [#what-bun-handles-natively] `Bun.Image` supports the common image optimization path: | Need | Bun API | | ----------------------------------- | -------------------------------------------------------------------- | | Read image dimensions and format | `metadata()` | | Resize by width or width and height | `resize(width)` or `resize(width, height)` | | Preserve aspect ratio inside a box | `resize(width, height, { fit: "inside" })` | | Prevent upscaling | `resize(width, height, { withoutEnlargement: true })` | | Choose resize filter | `filter: "lanczos3"`, `"mitchell"`, `"box"`, `"nearest"`, and others | | Rotate | `rotate(90)`, `rotate(180)`, `rotate(270)` | | Flip | `flip()` for vertical, `flop()` for horizontal | | Adjust brightness and saturation | `modulate({ brightness, saturation })` | | Encode JPEG | `jpeg({ quality, progressive })` | | Encode PNG | `png({ compressionLevel })` or `png({ palette, colors, dither })` | | Encode WebP | `webp({ quality })` or `webp({ lossless: true })` | | Generate a placeholder | `placeholder()` | | Return HTTP response body | `blob()`, `bytes()`, or `buffer()` | | Write a transformed file | `write(path)`, `write(Bun.file(...))`, or `write(Bun.s3(...))` | Stick to JPEG, PNG, and WebP for portable Compute routes. Bun's HEIC and AVIF support depends on operating-system image backends, so treat those formats as unavailable unless you add and test your own encoder path. Minimal service [#minimal-service] Build the route in a Hono or plain Bun HTTP app. The example below uses Hono to match the other [Compute examples](/compute/getting-started); the `Bun.Image` code is identical in any framework. ```bash title="Install Hono" bun add hono ``` ```ts title="src/index.ts" import { Hono } from "hono"; const app = new Hono(); const IMAGE_ORIGIN = "https://assets.example.com/"; const MAX_DIMENSION = 2400; const MAX_PIXELS = 4096 * 4096; function parseDimension(value: string | undefined) { if (!value) return undefined; const parsed = Number.parseInt(value, 10); if (!Number.isFinite(parsed) || parsed <= 0) return undefined; return Math.min(parsed, MAX_DIMENSION); } function parseQuality(value: string | undefined) { if (!value) return 80; const parsed = Number.parseInt(value, 10); if (!Number.isFinite(parsed)) return 80; return Math.min(Math.max(parsed, 1), 100); } function negotiateFormat(request: Request, requested: string | undefined) { if (requested === "jpeg" || requested === "png" || requested === "webp") { return requested; } const accept = request.headers.get("accept") ?? ""; return accept.includes("image/webp") ? "webp" : "jpeg"; } async function applyResize(image: Bun.Image, width?: number, height?: number, fit: "fill" | "inside" = "inside") { const options = { fit, withoutEnlargement: true, filter: "lanczos3" as const, }; if (width && height) return image.resize(width, height, options); if (width) return image.resize(width, undefined, options); if (height) { const metadata = await image.metadata(); const computedWidth = Math.max(1, Math.round((metadata.width * height) / metadata.height)); return image.resize(computedWidth, height, options); } return image; } function assertImagePath(path: string) { if (!/^[a-zA-Z0-9/_ .-]+\.(jpe?g|png|webp)$/i.test(path)) { throw new Error("Invalid image path"); } } app.get("/images/*", async (c) => { const path = c.req.path.replace(/^\/images\//, ""); try { assertImagePath(path); } catch { return c.text("Invalid image path", 400); } const sourceUrl = new URL(path, IMAGE_ORIGIN); const source = await fetch(sourceUrl); if (!source.ok) { return c.text("Source image not found", 404); } const input = await source.arrayBuffer(); const width = parseDimension(c.req.query("w")); const height = parseDimension(c.req.query("h")); const quality = parseQuality(c.req.query("q")); const fit = c.req.query("fit") === "fill" ? "fill" : "inside"; const format = negotiateFormat(c.req.raw, c.req.query("format")); let image = new Bun.Image(input, { maxPixels: MAX_PIXELS, autoOrient: true, }); image = await applyResize(image, width, height, fit); if (format === "webp") { image = image.webp({ quality }); } else if (format === "png") { image = image.png({ compressionLevel: 6 }); } else { image = image.jpeg({ quality, progressive: true }); } const body = await image.blob(); return new Response(body, { headers: { "Cache-Control": "public, max-age=31536000, immutable", "Content-Type": body.type, "Vary": "Accept", }, }); }); export default app; ``` Deploy it: ```bash title="Deploy" bunx @prisma/cli@latest app deploy --framework hono --entry src/index.ts ``` Request variants: ```text title="Requests" /images/products/chair.jpg?w=640&q=75 /images/products/chair.jpg?w=1280&format=webp /images/products/chair.jpg?w=512&h=512&fit=inside ``` This example sends `Cache-Control: immutable`, which is only safe when the source path is versioned (a content hash or version segment). If `chair.jpg` can change in place, drop `immutable` and use a shorter `max-age` with an `ETag`. See [Caching](#caching) for the full rules. Source images [#source-images] `Bun.Image` accepts a path, bytes, or a `Blob`. On Compute, prefer bytes or trusted storage handles over raw user-controlled paths. Remote source [#remote-source] ```ts title="Remote source" const response = await fetch(sourceUrl); if (!response.ok) throw new Error("Image not found"); const image = new Bun.Image(await response.arrayBuffer(), { maxPixels: 4096 * 4096, autoOrient: true, }); ``` Validate remote sources before fetching them: * Allow only trusted hostnames or storage prefixes. * Reject private network addresses if users can submit URLs. * Cap redirects or disable them when you do not need them. * Set a maximum decoded pixel count with `maxPixels`. * Cap requested dimensions and quality. Local file [#local-file] ```ts title="Local file" const image = Bun.file("public/avatars/alice.png").image(); ``` Do not pass a user-controlled string directly to `new Bun.Image(path)`. If the source is user-selected, resolve it through your own database or object store first, then read the trusted object. S3-compatible object [#s3-compatible-object] ```ts title="S3 source" const image = Bun.s3("uploads/photo.jpg").image(); ``` You can also write generated variants back to S3: ```ts title="Write variant" await Bun.s3("uploads/photo.jpg") .image() .resize(640, undefined, { withoutEnlargement: true }) .webp({ quality: 80 }) .write(Bun.s3("variants/photo-640.webp")); ``` Transform options [#transform-options] Resize [#resize] ```ts title="Resize" image.resize(800); image.resize(800, 600); image.resize(800, 600, { fit: "inside" }); image.resize(800, 600, { withoutEnlargement: true }); image.resize(800, 600, { filter: "mitchell" }); ``` Use `fit: "inside"` for the common thumbnail behavior: preserve aspect ratio and fit within a box. Without `fit: "inside"`, width and height produce an exact output size, which can stretch the image. Use `withoutEnlargement: true` when handling user uploads or product assets so small source images are not upscaled. Rotate and flip [#rotate-and-flip] ```ts title="Rotate and flip" image.rotate(90); image.flip(); image.flop(); ``` `rotate()` accepts multiples of 90 degrees. Brightness, saturation, and grayscale [#brightness-saturation-and-grayscale] ```ts title="Adjust color" image.modulate({ brightness: 1.1, saturation: 0, }); ``` `saturation: 0` creates a grayscale output. Output formats [#output-formats] ```ts title="Output formats" image.jpeg({ quality: 82, progressive: true }); image.png({ compressionLevel: 6 }); image.png({ palette: true, colors: 64, dither: true }); image.webp({ quality: 80 }); image.webp({ lossless: true }); ``` If you do not choose an output format, Bun reuses the source format. Placeholders [#placeholders] ```ts title="Placeholder" const placeholder = await Bun.file("hero.jpg").image().placeholder(); ``` Inline the result as a low-quality placeholder in HTML or React components while the full image loads. Content negotiation [#content-negotiation] To implement `format=auto`, inspect the `Accept` header. ```ts title="Format negotiation" function autoFormat(request: Request) { const accept = request.headers.get("accept") ?? ""; if (accept.includes("image/webp")) return "webp"; return "jpeg"; } ``` Return `Vary: Accept` when the same URL can produce different formats: ```ts title="Response headers" return new Response(body, { headers: { "Content-Type": body.type, "Vary": "Accept", }, }); ``` Caching [#caching] Every unique URL should map to one deterministic output. Keep query parameters normalized and bounded. Recommended cache rules: * Include all transformation parameters in the URL or path. * Sort query parameters when generating URLs from code. * Use immutable cache headers for versioned source paths. * Use shorter cache headers or ETags when the source can change in place. * Return `Vary: Accept` when format negotiation depends on request headers. * Add a source version, hash, or updated timestamp to the URL when invalidating. Example: ```ts title="Cache headers" headers.set("Cache-Control", "public, max-age=31536000, immutable"); headers.set("Vary", "Accept"); ``` Vercel Image Optimization equivalents [#vercel-image-optimization-equivalents] Vercel Image Optimization supports framework image components, width and quality parameters, automatic format selection, source allowlists, caching, and fixed source limits. On Prisma Compute, implement those pieces in the app route. | Vercel behavior | Prisma Compute approach | | ------------------------------------- | ---------------------------------------------------------------------------------------------- | | `url` source parameter | Resolve a trusted object key or allowlisted source URL. Do not fetch arbitrary user URLs. | | `w` width parameter | Parse and cap `w`, then call `resize(w, ...)`. | | `q` quality parameter | Parse and cap `q`, then pass it to `jpeg()` or `webp()`. | | Automatic WebP or AVIF | Inspect `Accept`. Use WebP natively. Add and test a separate AVIF encoder if you require AVIF. | | Local and remote source patterns | Keep allowlists in code or config. Reject anything else before fetching. | | Cache optimized variants | Make the URL the cache key and return appropriate `Cache-Control` and `Vary` headers. | | Framework image component integration | Point your framework loader or image component at your Compute image route. | | Source size limits | Use `maxPixels`, cap response body size, and reject dimensions above your product limit. | Cloudflare Images equivalents [#cloudflare-images-equivalents] Cloudflare Images exposes many URL and Worker options. The table below maps each option to the Compute implementation path. | Cloudflare option | Prisma Compute approach | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `anim` | Bun's native output path is best for static variants. Preserve animated originals separately, or use an animation-aware library when you need animated output. | | `background` | Use CSS for display backgrounds, or add an image library that supports canvas extension/padding. | | `blur` | Add an image library with blur support. Do not rely on URL blur for access control. | | `border` | Prefer CSS borders for display. Use an image library if the border must be encoded into the asset. | | `brightness` | Use `modulate({ brightness })`. | | `compression` | Choose faster formats/settings in your route, usually JPEG or WebP with a lower quality, and cache the result. | | `contrast` | Add an image library with contrast adjustment. | | `dpr` | Multiply requested width and height by the DPR value before resizing, and cap the result. | | `fit=scale-down` | Use `fit: "inside"` with `withoutEnlargement: true`. | | `fit=contain` | Use `fit: "inside"`; omit `withoutEnlargement` if you allow upscaling. | | `fit=cover`, `fit=crop`, `fit=aspect-crop` | Add a library with crop/extract support, or pre-generate cropped variants. Current `Bun.Image` does not expose crop coordinates. | | `fit=pad` | Use CSS object-fit where possible, or add a library that can extend the canvas with a background color. | | `fit=squeeze` | Use `resize(width, height)` without `fit: "inside"` when distortion is acceptable. | | `fit=scale-up` | Use `fit: "inside"` and allow upscaling; cap dimensions. | | `flip` | Use `flip()` for vertical or `flop()` for horizontal. | | `format` / `f` | Choose `.jpeg()`, `.png()`, or `.webp()`. Implement `auto` with the `Accept` header. | | `gamma` | Add an image library with gamma adjustment. | | `gravity` / `g` | For fixed focal points, store focal metadata and use a crop-capable library. For `auto` or `face`, use a vision model or external service to choose the crop. | | `height` / `h` | Parse and cap `h`, then pass it to `resize()`. | | `metadata` | Bun can apply EXIF orientation with `autoOrient`. Use an additional library if you need explicit EXIF preservation or removal policy. | | `onerror=redirect` | Catch transform errors and redirect to the original source when that is safe for your app. | | `quality` / `q` | Pass a capped quality to `jpeg()` or `webp()`. For PNG, use `compressionLevel` or palette output. | | `rotate` | Use `rotate(90)`, `rotate(180)`, or `rotate(270)`. | | `saturation` | Use `modulate({ saturation })`; `0` creates grayscale. | | `segment` | Use a background-removal model or API, then composite the result with an image library. | | `sharpen` | Add an image library with sharpen support. | | `slow-connection-quality` / `scq` | Read client hints such as `Save-Data`, `RTT`, `ECT`, or `Downlink`, then lower quality in route logic. | | `trim` | Add a library that supports edge trimming or explicit crop/extract. | | `upscale` | Use native resize for interpolation. Use a super-resolution model or API for AI upscaling. | | `width` / `w` | Parse and cap `w`, then pass it to `resize()`. | | `width=auto` | Choose a breakpoint from client hints, user agent, or your own layout metadata. | | `zoom` / `face-zoom` | Use face detection plus a crop-capable library. | Adding advanced image libraries [#adding-advanced-image-libraries] If you need operations that `Bun.Image` does not expose, add a library and keep the same route shape: 1. Validate source, dimensions, format, and quality. 2. Fetch or read the trusted source. 3. Run native Bun transformations for the common path when possible. 4. Route advanced presets through the library. 5. Return the same cache headers and error behavior. Keep advanced transformations behind named presets instead of exposing every option directly. For example: ```text title="Preset URLs" /images/products/chair.jpg?p=thumb /images/products/chair.jpg?p=hero /images/products/chair.jpg?p=square ``` Presets make cache keys stable and prevent users from creating unbounded transformation combinations. Security checklist [#security-checklist] * Do not pass user-controlled filesystem paths to `new Bun.Image(path)`. * Allowlist remote origins before fetching. * Reject private IP ranges for user-submitted URLs. * Cap width, height, quality, DPR, and decoded pixels. * Prefer named presets for public image URLs. * Return clear `400` responses for invalid parameters. * Return `404` for missing source images. * Set `Vary: Accept` when negotiating formats. * Use `maxPixels` to reject decompression bombs before pixel allocation. * Do not use reversible transformations such as blur as an access-control mechanism. What to read next [#what-to-read-next] * [Deploy your first app](/prisma-compute/deploy): take a route like this one to a live URL. * [Deployments](/compute/deployments): build, deploy, logs, promote, and roll back. * [Configuration](/compute/configuration): pin the framework, entry, and port in `prisma.compute.ts`. * [Environment variables](/compute/environment-variables): point a preview at a staging bucket and production at a production one. * [Branching](/compute/branching): give every image route its own isolated preview. * [Pricing](/compute/pricing): how request, CPU, memory, and bandwidth metering works. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # Prisma Compute (/docs/compute) Location: Prisma Compute Prisma Compute is TypeScript app hosting built to run alongside [Prisma Postgres](/postgres). You model your data with [Prisma ORM](/orm), store it in Prisma Postgres, and deploy your app with Prisma Compute, so your schema, database, hosting, and branch previews work together in one Prisma project. > [!NOTE] > Public Beta > > Prisma Compute is in [Public Beta](/console/more/feature-maturity#public-beta) and is CLI-first: you deploy and manage apps with the [`@prisma/cli`](/compute/getting-started) beta package. Use the [Console](https://pris.ly/pdp) if you prefer to view your resources instead of running a command. Get started [#get-started] The best way to understand Compute is to deploy an app. The quickstart takes a TypeScript app to a live URL in a few minutes, then connects GitHub so every push can deploy automatically. - [Deploy your first app](/prisma-compute/deploy): The quickstart: sign in, deploy, verify, and connect GitHub. To learn how Compute works, [the model](#the-model) below shows how each branch gets isolated app and database resources, so preview work never touches production. The model [#the-model] Compute organizes everything into a few resources: * A **project** groups one product or codebase. * A **branch** maps to a Git branch in the linked repository, and gets its own isolated app, environment variables, and deployments. * An **app** is an HTTP service, such as a frontend or backend, and can have multiple **deployments**. The branch is the concept that ties Compute together. Each branch owns its own app, URL, and environment variables, and can have its own database. When you deploy to a new branch, Compute provisions isolated resources for that branch, so you can test changes in preview without affecting production. * **Production**: the default Git branch (e.g., `main`) is your production branch, with its own resources and environment variables. * **Preview**: every other branch is a preview branch, with its own isolated resources and environment variables scoped to **preview**. After you [connect a GitHub repository](/compute/github), pushing to a Git branch builds and deploys its preview automatically. The animation below shows how a project, its branches, and their infrastructure fit together, and how each branch's variables resolve by scope. Step through it, or let it play: For the full picture, see [Branching](/compute/branching). CLI and Console [#cli-and-console] Use the **CLI** for anything you want to repeat: local development, CI, and agent workflows. Every command supports a `--json` flag that switches its output to machine-readable JSON, so scripts and agents can parse results instead of scraping terminal text. Use the **[Console](https://pris.ly/pdp)** if you prefer to view your resources instead of running a command. The Console shows your projects, branches, apps, and deployments in a visual way, and lets you manage them with buttons instead of commands. What to read next [#what-to-read-next] * [Get started with `@prisma/cli`](/compute/getting-started): the full CLI guide for frameworks, project linking, production, and CI. * [Branching](/compute/branching): how branches isolate work and map to Git. * [Deployments](/compute/deployments): build, deploy, logs, promote, roll back. * [Image Transformations](/compute/image-transformations): resize, encode, cache, and serve images from a Compute app with Bun. * [Environment variables](/compute/environment-variables): production, preview, and per-branch overrides. * [GitHub integration](/compute/github): connect a repo and deploy on push. * [CLI reference](/compute/cli-reference): every command, flag, and error code. * [Domains](/compute/domains): point a custom domain at production. * [Known limitations](/compute/limitations): what the beta can and can't do. * [FAQ](/compute/faq): quick answers to common questions. ## 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 # Keeping instances awake (/docs/compute/keeping-instances-awake) Location: Compute > Keeping instances awake By default, Prisma Compute [scales idle instances to zero](/compute/pricing) to save cost: idle instances sleep with a memory snapshot, then resume with memory intact in milliseconds. Some bounded background work needs the instance to keep running after a request ends or while no request is in flight. `@prisma/compute` provides two primitives for these cases: * `waitUntil`: keeps the current instance awake until a background promise settles. * `KeepAwakeGuard`: keeps the current instance awake until you release the guard. > [!WARNING] > These primitives are for best-effort background work. They only prevent the current instance from scaling to zero; they do not make work durable, retry failures, guarantee that work continues through restarts or deployments, or change connection-lifetime limits. Persist progress and design work so it can safely restart. > > WebSocket servers are not currently a supported Public Beta capability. When to keep instances awake [#when-to-keep-instances-awake] Reach for `waitUntil` or `KeepAwakeGuard` for bounded, best-effort work between requests, for example: * A bounded job that outlives the request that started it. * Background processing you kick off after returning a response. If your work always finishes inside a single request, you do not need either primitive. Let the instance sleep as usual. Use waitUntil for background promises [#use-waituntil-for-background-promises] Use `waitUntil` when you have a promise for background work that should keep the instance awake. This is the most direct API for work you start during a request but do not await before returning a response: ```ts title="src/index.ts" import { waitUntil } from "@prisma/compute"; export default { fetch(req: Request) { waitUntil(processInBackground(req), { // Optional. Prevents a hanging promise from keeping the instance awake indefinitely. signal: AbortSignal.timeout(30_000), }); return new Response("Accepted"); }, }; ``` `waitUntil` follows the same pattern as [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil) and the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil): the instance stays awake until the promise settles. Prisma Compute adds an optional caller-owned `signal` value so you can stop the keep-awake effect if a promise hangs or never settles. The signal does not cancel the promise or the work it started. Use KeepAwakeGuard for block-scoped or manual lifetimes [#use-keepawakeguard-for-block-scoped-or-manual-lifetimes] Use `KeepAwakeGuard` when the keep-awake lifetime does not map cleanly to one promise, or when a block scope should control when the instance can resume normal scaling. `KeepAwakeGuard` implements the JavaScript [`Disposable` interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Resource_management), so you can use the `using` keyword to release it automatically at the end of the scope: ```ts title="src/index.ts" import { KeepAwakeGuard } from "@prisma/compute"; async function processBatch() { using guard = new KeepAwakeGuard(); await fetchAllRecords(); await transformData(); await writeResults(); } ``` While the guard is active, the instance does not sleep. When the scope exits, `using` disposes the guard and normal scaling resumes. If `using` is not available in your runtime or build setup, or if you need more granular control, release the guard in a `finally` block. This prevents a thrown error from leaving the guard active longer than intended: ```ts title="src/index.ts" import { KeepAwakeGuard } from "@prisma/compute"; async function processBatch() { const guard = new KeepAwakeGuard(); try { await fetchAllRecords(); await transformData(); await writeResults(); } finally { guard.release(); } } ``` Calling `guard.release()` signals that the work is done and the instance can resume normal scaling behavior. Always release manually created guards, preferably from `finally`, unless `using` owns the lifetime for you. The signal option [#the-signal-option] `KeepAwakeGuard` accepts a caller-owned `signal` option. Use it as a safety fallback to release the guard if your code does not reach `release()`. The signal releases the keep-awake guard; it does not cancel the work protected by the guard. ```ts title="src/index.ts" import { KeepAwakeGuard } from "@prisma/compute"; const guard = new KeepAwakeGuard({ // Optional. Prevents a leaked guard from keeping the instance awake indefinitely. signal: AbortSignal.timeout(30_000), }); ``` > [!WARNING] > The `signal` option is a fallback, not the primary way to control your work. Prefer `using` or `try`/`finally` for normal guard lifetimes. Use `signal` to cap the maximum keep-awake lifetime and avoid dangling guards. For example, combine `AbortSignal.timeout()` with `try`/`finally` when a job should keep the instance awake, but never for longer than a fixed duration: ```ts title="src/index.ts" import { KeepAwakeGuard } from "@prisma/compute"; async function processBatch() { const guard = new KeepAwakeGuard({ // Optional. Prevents a leaked guard from keeping the instance awake indefinitely. signal: AbortSignal.timeout(30_000), }); try { await fetchAllRecords(); await transformData(); await writeResults(); } finally { guard.release(); } } ``` The `signal` follows the standard `AbortSignal` pattern, so you can pass any signal you control. API reference [#api-reference] waitUntil [#waituntil] ```ts title="@prisma/compute" waitUntil(promise: PromiseLike, options?: { signal?: AbortSignal }): void; ``` Keeps the instance awake until `promise` settles. Pass `options.signal` as a caller-owned fallback to stop keeping the instance awake if the promise hangs or never settles. The signal does not cancel the promise. KeepAwakeGuard [#keepawakeguard] ```ts title="@prisma/compute" new KeepAwakeGuard(options?: { signal?: AbortSignal }); ``` Creates a guard that keeps the instance awake until the guard is disposed, released, or its optional caller-owned `signal` aborts. The signal releases the guard; it does not cancel the work protected by the guard. | Member | Type | Description | | ------------ | ---------------- | ---------------------------------------------------------------------------- | | `release()` | `() => void` | Releases the guard, allowing the instance to resume normal scaling behavior. | | `Disposable` | `Symbol.dispose` | Enables automatic release with `using`. | Next steps [#next-steps] * [Get started with Prisma Compute](/compute/getting-started): deploy your first app. * [Pricing](/compute/pricing): how scale-to-zero billing works. * [Deployments](/compute/deployments): build, deploy, logs, promote, and roll back. * [Environment variables](/compute/environment-variables): scoped configuration and secrets. * [Configuration](/compute/configuration): the `prisma.compute.ts` file reference. * [Known limitations](/compute/limitations): what the beta can and can't do. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # Known limitations (/docs/compute/limitations) Location: Compute > Known limitations Prisma Compute is in [Public Beta](/console/more/feature-maturity#public-beta). This page lists what the beta can and can't do. CLI [#cli] * The package is `@prisma/cli`; the executable is `prisma-cli`. The quickest way to run it is `npx @prisma/cli@latest ` (or `bunx`/`pnpm dlx`), with Node.js 22.12 or newer for `npx` and `pnpm`. * The command groups are `version`, `init`, `agent`, `auth`, `project` (including `project env`), `git`, `branch`, `build`, `database`, and `app`. There is no `schema` or `migrate` command, and no product-branded `compute` namespace. * Committed configuration lives in [`prisma.compute.ts`](/compute/configuration) (or `prisma.compute.json`). `.prisma/local.json` is a gitignored local pin of the workspace and project, and `PRISMA_PROJECT_ID` / `PRISMA_APP_ID` override it for CI. Projects and branches [#projects-and-branches] * Project setup is explicit: `--yes` won't create or choose a project for you. * The first branch in a project is production; the rest are preview by default. * `branch list` inspects branches; it doesn't create remote state. * Deleting a branch on GitHub can tear down the matching platform branch, but production and default branches are always left alone. Frameworks and runtimes [#frameworks-and-runtimes] * `app deploy --framework` accepts `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, and `bun`. * `app build --build-type` accepts `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`. * Use `--entry` for Bun, or whenever detection needs a hand. Environment variables [#environment-variables] * Values are write-only: once saved, they are never returned by any surface, and there is no command to pull them into a local `.env`. * `project env list` returns keys and metadata only. * Values resolve at deploy time; changing one doesn't mutate existing deployments or trigger a redeploy. * Production variables can't be branch-scoped. * Keys must match `[A-Z_][A-Z0-9_]*`; values are non-empty, up to 8 KB. GitHub [#github] * GitHub is the only supported provider, and a project connects to one repository. * Auto-deploy supports multiple apps declared in `prisma.compute.ts`: one push build fans out into a targeted build per app. CI with a service token remains available when you need full control. * The webhook path is branch- and push-driven. There are no PR comments or PR status automation. Domains [#domains] * Custom domains are production-only and CNAME-based: they attach to the default (production) branch, and the app needs a promoted deployment first. * Up to 3 custom domains per app. * There is no workspace-wide domain list in the CLI. Logs [#logs] * `app logs` streams the live deployment or a specific one. * It returns `FEATURE_UNAVAILABLE` when the platform can't serve logs for the resolved deployment. * Logs stream in time-bounded segments, so direct API clients should expect to reconnect. Runtime [#runtime] * This release focuses on HTTP apps. Background work between requests is supported through the `@prisma/compute` keep-awake primitives; see [Keeping instances awake](/compute/keeping-instances-awake). Cron scheduling, a persistent filesystem, and edge runtimes are not part of it. * WebSocket servers are not currently a supported Public Beta capability. `waitUntil` and `KeepAwakeGuard` only prevent an instance from scaling to zero; they do not change connection-lifetime limits or guarantee continuity through restarts or deployments. * No multi-region deployments. Each app lives in one region, chosen at creation with `app deploy --region`: `us-east-1` (the default), `us-west-1`, `eu-west-3`, `eu-central-1`, `ap-northeast-1`, or `ap-southeast-1`. * Not yet recommended for mission-critical or heavy production workloads. * Exact limits, pricing, retention policies, and runtime guardrails can still change before general availability. Databases and migrations [#databases-and-migrations] * These docs cover app deploy and runtime config only: not database creation, schema migrations, or data cloning. * Don't assume production data is copied into preview branches. * Don't assume production migrations run automatically on deploy. * Pass database URLs and other runtime config through [environment variables](/compute/environment-variables). Next steps [#next-steps] * [FAQ](/compute/faq): quick answers to common questions. * [Get started with `@prisma/cli`](/compute/getting-started): your first deploy. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # Pricing (/docs/compute/pricing) Location: Compute > Pricing Compute is free during public beta. The rates below are what we expect to charge once we enable production billing. We are publishing them now so you can understand the model, estimate future usage, and tell us where real workloads don't fit. > [!NOTE] > Public Beta > > Prisma Compute is in [Public Beta](/console/more/feature-maturity#public-beta), so rates, limits, and included usage may change before billing begins. If something has to change, we will change it and say so clearly. > > This pricing isn't final, and your feedback shapes it. If a rate or meter doesn't fit how your app runs, tell us in the `prisma-compute` channel on our [Discord](https://pris.ly/discord). Expected usage rates [#expected-usage-rates] Each meter measures a different resource: how often your app runs (requests), how much memory it holds and CPU it uses while running (provisioned memory and active CPU), and how much data it sends back (outbound bandwidth). | Meter | Price | What it means | | ------------------ | --------------------- | ------------------------------------------------------------------------------------- | | Requests | `$1.00 / 1M requests` | Every inbound request your app handles. | | Provisioned memory | `$0.006 / GB-hour` | Memory allocated while your app is running or intentionally kept awake. | | Active CPU | `$0.064 / vCPU-hour` | CPU time your app actually consumes. | | Outbound bandwidth | `$0.025 / GB` | Data your app sends out to the internet. Incoming requests do not count as bandwidth. | Example costs by workload [#example-costs-by-workload] The three examples below show how the same rates add up for different kinds of apps, from a short-lived preview to a bandwidth-heavy service. These examples are estimates, not benchmarks. The inputs are round numbers so the math is easy to follow. Each total is what the usage would cost under the expected rates, once billing starts. Preview workflow [#preview-workflow] A pull request might deploy a preview several times as an agent fixes and tests a change. Assume the preview gets `10,000` requests, stays running for `3,000s` at `1 GB`, uses `600 vCPU-seconds` of active CPU, and sends `0.25 GB` of data out. | Meter | Estimate | | ------------------ | -------------------------------------------------------- | | Requests | `10,000 * $1.00 / 1M = $0.0100` | | Provisioned memory | `3,000s at 1 GB = 0.833 GB-hours * $0.006 = $0.0050` | | Active CPU | `600 vCPU-seconds = 0.167 vCPU-hours * $0.064 = $0.0107` | | Outbound bandwidth | `0.25 GB * $0.025 = $0.0063` | | Total | `$0.0320`, about `$0.03` | The usage is the bill, not the deploys or the [preview branch](/compute/branching). Agent workflow [#agent-workflow] Agent work often spends more time waiting on other services than running on the CPU. Assume an app runs `10,000` agent tasks in a month. Each task takes `30s` wall-clock time, mostly waiting on a model API or another service. Together, the tasks stay running for `300,000s` at `1 GB`, use `30,000 vCPU-seconds` of active CPU, and send `5 GB` of data out. | Meter | Estimate | | ------------------ | ---------------------------------------------------------- | | Requests | `10,000 * $1.00 / 1M = $0.0100` | | Provisioned memory | `300,000s at 1 GB = 83.33 GB-hours * $0.006 = $0.5000` | | Active CPU | `30,000 vCPU-seconds = 8.33 vCPU-hours * $0.064 = $0.5333` | | Outbound bandwidth | `5 GB * $0.025 = $0.1250` | | Total | `$1.1683`, about `$1.17` | While a task waits it uses almost no CPU, so active CPU stays low. But the app keeps running the whole time, so it holds its memory and you pay for that. This is why Compute bills provisioned memory separately from active CPU. High-transfer workflow [#high-transfer-workflow] If your app streams responses, returns large results, or serves file downloads, bandwidth can make up most of the bill instead of compute. It is worth estimating this before you ship. Assume an app serves `50,000` requests in a month, stays running for `15,000s` at `1 GB`, uses `1,500 vCPU-seconds` of active CPU, and sends `200 GB` of data out. | Meter | Estimate | | ------------------ | ---------------------------------------------------------- | | Requests | `50,000 * $1.00 / 1M = $0.0500` | | Provisioned memory | `15,000s at 1 GB = 4.167 GB-hours * $0.006 = $0.0250` | | Active CPU | `1,500 vCPU-seconds = 0.417 vCPU-hours * $0.064 = $0.0267` | | Outbound bandwidth | `200 GB * $0.025 = $5.0000` | | Total | `$5.1017`, about `$5.10` | Here compute is almost free and bandwidth is nearly the whole bill. If your app moves a lot of data, estimate bandwidth first. Formula to estimate your bill [#formula-to-estimate-your-bill] To estimate any month yourself, add up the four meters at their rates: ```text bill = requests * 1.00 / 1_000_000 + provisioned_memory_gb_hours * 0.006 + active_vcpu_hours * 0.064 + outbound_bandwidth_gb * 0.025 ``` What is not billed separately [#what-is-not-billed-separately] You pay for the work your app does, not for resources sitting idle. These are not billed on their own: * Deployments * Preview branch creation * Inactive apps * Apps that have scaled to zero * A Prisma-specific compute unit A preview branch only costs money when it does work, such as serving traffic or running a background task. Creating one is free. Usage data for humans and agents [#usage-data-for-humans-and-agents] Database usage is available from the [CLI](/compute/cli-reference) (`database usage`) and API, including as JSON, and an agent can read it to estimate a cost, explain a change, or suggest a fix. Equivalent Compute usage surfaces are still taking shape during the beta. Beta and bandwidth [#beta-and-bandwidth] Compute is free during public beta. The rates above are estimates and may change as we learn from real usage. If anything changes before we enable production billing, we will say so clearly. Outbound bandwidth is the data your app sends from Compute to the public internet; inbound requests don't count. Small JSON or API responses use little of it, while streaming, file downloads, and media use much more. During beta we are measuring real traffic to confirm the rate, included usage, and edge cases before billing starts. Share your pricing feedback [#share-your-pricing-feedback] This pricing is still taking shape during the beta, and your input shapes where it lands. If a rate, meter, or included amount doesn't match how your app actually runs, tell us in the `prisma-compute` channel on our [Discord](https://pris.ly/discord). That feedback is exactly what we are measuring against before billing turns on. What to read next [#what-to-read-next] * [Prisma Compute vs Vercel pricing](https://www.prisma.io/blog/prisma-compute-vs-vercel-pricing?utm_source=docs): the same monthly workload priced line by line on both platforms. * [Get started](/compute/getting-started): the quickstart, deploy your first app to a live URL in two commands. * [Known limitations](/compute/limitations): what the beta can and can't do. * [FAQ](/compute/faq): quick answers to common questions. * [Branching](/compute/branching): how preview branches isolate work and when they cost money. ## Related pages - [`@prisma/cli`](https://www.prisma.io/docs/compute/getting-started): Deploy your first app to Prisma Compute with the @prisma/cli beta package, then learn the variations you'll need next. - [`Branching`](https://www.prisma.io/docs/compute/branching): Branches are isolated environments that map to your Git branches, so preview work never touches production. - [`CLI reference`](https://www.prisma.io/docs/compute/cli-reference): Every @prisma/cli command, flag, environment variable, and error code for Prisma Compute. - [`Configuration`](https://www.prisma.io/docs/compute/configuration): Declare your deployable app in a typed prisma.compute.ts file so deploys are reproducible and monorepos work, without re-passing flags every time. - [`Deployments`](https://www.prisma.io/docs/compute/deployments): Build, deploy, inspect, promote, and roll back app deployments on Prisma Compute. # 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. > [!NOTE] > Try Prisma Next > > Prisma Next is the next major version of Prisma ORM, available now in Early Access. Start with the [Prisma Next getting started guide](/next) and share feedback in [Discord](https://pris.ly/discord?utm_source=docs\&utm_medium=inline_text). 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: #### bun ```bash bunx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### npm ```bash npx prisma migrate dev ``` Or [introspect](/orm/prisma-schema/introspection) an existing database: #### bun ```bash bunx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### npm ```bash npx prisma db pull ``` 4. Query with Prisma Client [#4-query-with-prisma-client] Generate and use the type-safe client: #### bun ```bash bun add @prisma/client bunx prisma generate ``` #### pnpm ```bash pnpm add @prisma/client pnpm dlx prisma generate ``` #### yarn ```bash yarn add @prisma/client yarn dlx prisma generate ``` #### npm ```bash npm install @prisma/client npx 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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] #### bun ```bash bun create prisma@latest ``` #### pnpm ```bash pnpm create prisma@latest ``` #### yarn ```bash yarn create prisma@latest ``` #### npm ```bash npm 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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: #### bun ```bash bunx create-db@latest ``` #### pnpm ```bash pnpm dlx create-db@latest ``` #### yarn ```bash yarn dlx create-db@latest ``` #### npm ```bash npx 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. * By default, `create-db` detects your approximate location and provisions the database in the closest available region, falling back to `us-east-1` if detection fails. To choose a region yourself, use 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: #### bun ```bash bunx create-db@latest --interactive ``` #### pnpm ```bash pnpm dlx create-db@latest --interactive ``` #### yarn ```bash yarn dlx create-db@latest --interactive ``` #### npm ```bash npx 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`: #### bun ```bash bunx create-db@latest -i ``` #### pnpm ```bash pnpm dlx create-db@latest -i ``` #### yarn ```bash yarn dlx create-db@latest -i ``` #### npm ```bash npx create-db@latest -i ``` To view all options and regions: #### bun ```bash bunx create-db@latest --help ``` #### pnpm ```bash pnpm dlx create-db@latest --help ``` #### yarn ```bash yarn dlx create-db@latest --help ``` #### npm ```bash npx 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: #### bun ```bash bunx create-db@latest --help ``` #### pnpm ```bash pnpm dlx create-db@latest --help ``` #### yarn ```bash yarn dlx create-db@latest --help ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun prisma init --db ``` #### pnpm ```bash pnpm dlx prisma init --db ``` #### yarn ```bash yarn dlx prisma init --db ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun prisma@latest init --db ``` #### pnpm ```bash pnpm dlx prisma@latest init --db ``` #### yarn ```bash yarn dlx prisma@latest init --db ``` #### npm ```bash npx 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: #### bun ```bash bunx --bun prisma@latest init --db ``` #### pnpm ```bash pnpm dlx prisma@latest init --db ``` #### yarn ```bash yarn dlx prisma@latest init --db ``` #### npm ```bash npx 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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: #### bun ```bash bun add --global prisma ``` #### pnpm ```bash pnpm add -g prisma ``` #### yarn ```bash yarn global add prisma ``` #### npm ```bash npm install -g 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: #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### npm ```bash npx 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: #### bun ```bash bunx 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" ``` #### npm ```bash npx prisma studio --url="postgresql://user:password@localhost:5432/yourdb" ``` This is also how you launch Studio for a [Prisma Next](/orm/next) project, which has no `schema.prisma` to read. See [Studio with Prisma Next](/studio/prisma-next). 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] * Use Studio with a [Prisma Next project](/studio/prisma-next) to read your applied migration history in the Migrations view * Learn how to [embed Studio in your application](/studio/integrations/embedding) * Discover [VS Code integration](/studio/integrations/vscode-integration) features ## Related pages - [`Studio with Prisma Next`](https://www.prisma.io/docs/studio/prisma-next): Apply migrations to Prisma Postgres with Prisma Next, then inspect the migration history, schema changes, executed SQL, and data in Prisma Studio. # 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 * Reading the applied migration history of a [Prisma Next](/orm/next) database * 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] #### bun ```bash # With Prisma project bunx prisma studio # With direct database connection bunx 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" ``` #### npm ```bash # With Prisma project npx prisma studio # With direct database connection npx 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 * [Studio with Prisma Next](/studio/prisma-next) - Apply migrations to Prisma Postgres and read your migration history in the Migrations view * [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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 # Studio with Prisma Next (/docs/studio/prisma-next) Location: Studio > Studio with Prisma Next Prisma Studio shows the migration history of your [Prisma Next](/orm/next) database as a visual timeline. Select any applied migration to see the models it changed, the SQL it executed, and a diff of the schema before and after. This guide takes you from an empty directory to inspecting your own migration history. For browsing, editing, and filtering data in general, see [Getting Started](/studio/getting-started). The Migrations view requires `@prisma/studio-core` 0.32.0 or later, currently available in the Prisma CLI's `dev` release: run Studio with `npx prisma@dev studio`. Prisma Next is in [early access](/orm/next). Prerequisites [#prerequisites] * [Node.js](https://nodejs.org) installed * A Prisma Next project on PostgreSQL Create the project and provision a [Prisma Postgres](/postgres) database in one step: ```bash npm create prisma@next ``` To skip the prompts: ```bash npm create prisma@next -- my-app --yes --provider postgres --authoring psl \ --template minimal --prisma-postgres --install --emit ``` This writes your `DATABASE_URL` into `.env` and scaffolds a [data model](/orm/next/data-modeling) at `src/prisma/contract.prisma`, authored in [PSL](/orm/next/contract-authoring/psl-syntax). The database expires after 24 hours unless you claim it; open the `CLAIM_URL` in `.env` to keep it and attach it to your Prisma Console account. Apply the first migration [#apply-the-first-migration] The scaffolded [contract](/orm/next/contract-authoring/the-data-contract) defines a `User` and a `Post` model. Compile it, [plan a migration](/orm/next/migrations/generating-a-migration), and [apply it](/orm/next/migrations/applying-a-migration): ```bash npx prisma-next contract emit npx prisma-next migration plan --name init_users_posts npx prisma-next migrate --advance-ref db ``` The CLI confirms the apply: ```text Applied 1 migration(s) (6 operation(s)) across 1 contract space(s) ``` `--advance-ref db` records where your database is by advancing a [ref](/orm/next/migrations/the-migration-graph#name-important-states-with-refs), so the next plan produces a delta instead of recreating everything. Update the data model [#update-the-data-model] Add an enum and two fields to `src/prisma/contract.prisma`: ```prisma title="src/prisma/contract.prisma" enum Role { USER EDITOR ADMIN } model User { id Int @id @default(autoincrement()) email String @unique username String? name String? bio String? role Role @default(USER) posts Post[] createdAt DateTime @default(now()) updatedAt temporal.updatedAt() } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int createdAt DateTime @default(now()) updatedAt temporal.updatedAt() } ``` Create and apply another migration [#create-and-apply-another-migration] Compile the updated contract, plan, and apply: ```bash npx prisma-next contract emit npx prisma-next migration plan --name add_roles_and_publishing npx prisma-next migrate --advance-ref db ``` Because the `db` ref was advanced in the previous step, the planner produces a delta: four `ALTER TABLE` operations that add the new columns and the enum's check constraint. To edit a planned migration before it runs, for example to add a backfill, see [Editing a migration](/orm/next/migrations/editing-a-migration). > [!WARNING] > Plans start from empty without a starting point > > Without a `db` ref and without `--from`, `migration plan` compares against an empty database and recreates every table. If that happens, delete the planned migration directory and re-plan with `--from `, for example `--from 20260716T1155_init_users_posts`. See [The db ref](/orm/next/migrations/generating-a-migration#the-db-ref-skipping---from). Seed the database [#seed-the-database] Migration history is easier to read next to real rows: ```bash npm run db:seed ``` The CLI confirms with `Seeded 3 users.` The seed script writes through the Prisma Next ORM client; see [Writing data](/orm/next/fundamentals/writing-data) for the API it uses. > [!NOTE] > Namespaced ORM access > > `db.orm` is keyed by namespace first: reach models as `db.orm.public.User`, not `db.orm.User`. If the scaffolded `seed.ts` uses the shorter form, it fails with `TypeError: Cannot read properties of undefined (reading 'where')`. Add the namespace to fix it. Open Prisma Studio [#open-prisma-studio] A Prisma Next project has no `schema.prisma`, so pass the [connection string](/postgres/database/connecting-to-your-database) with `--url`. Load it from `.env` first: ```bash set -a && . ./.env && set +a npx prisma@dev studio --url "$DATABASE_URL" ``` Studio opens at `http://localhost:5555`. Once the database has at least one applied migration, a **Migrations** item appears in the left navigation. > [!NOTE] > History lives in your database > > Studio reads migration history from the connected database, not from your local `migrations/` directory. Migrations applied from CI or another machine appear automatically. Inspect migration history [#inspect-migration-history] Open **Migrations**. The timeline lists every applied migration, newest first, with its name, apply time, operation count, and chips summarizing the change: `+1 model`, `~2 models`, `+3 fields`, `+1 enum`, `−1 field`. A ⚠️ marker flags migrations that contain a destructive change, so a dropped column is visible before you select anything. If a destructive migration needs undoing, see [Rollbacks and recovery](/orm/next/migrations/rollbacks-and-recovery). The Prisma Studio Migrations view showing a timeline of six applied migrations and a visual diff canvas of the selected migration. The selected migration is part of the URL, so you can link a teammate straight to it: ``` http://localhost:5555/#view=migrations&migration=3 ``` Review schema changes [#review-schema-changes] Select a migration to see the schema as that migration changed it: * **NEW** (green): a model the migration added. * **UPDATED** (amber): a model whose table changed, with `+`, `−`, and `~` glyphs on the affected fields and `before → after` pills for changed types, nullability, or defaults. * **UNCHANGED** (dimmed): neighboring models drawn for context. * Enum cards, and [relation](/orm/next/fundamentals/relations-and-joins) edges between visible models. Amber always means the migration changed that model's table. A model that only gained a back-relation, where the foreign key lives on the other table, stays dimmed, and the new relation edge is emphasized instead. The diff canvas for a migration that added a Category model and a relation, showing Category as NEW, Post as UPDATED, and User dimmed as UNCHANGED. By default the view shows only the models the migration touched plus their direct neighbors. Toggle **All models** to see the entire schema as it stood at that point in history, including unchanged enums. The Migrations view with the All models toggle enabled, showing every model and enum in the schema at that migration. Review executed SQL [#review-executed-sql] Open the **SQL** panel to see the operations exactly as they ran, each labelled `additive` or `destructive`. This is the same SQL the migration runner executed; [How migrations work](/orm/next/migrations/how-migrations-work) explains how those operations are planned and checked. The SQL panel showing the ALTER TABLE statements and check constraint executed by a migration, each labelled with its operation class. Compare schema versions [#compare-schema-versions] Open the **Schema** panel to see a Prisma-schema diff between the migration's before and after state. Long unchanged runs collapse into folds you can click to expand. The Schema panel showing a color-coded diff of the Prisma schema before and after a migration, with collapsed unchanged sections. The diff is a projection built for stable comparison, not a copy of your source file. It uses a fixed field order and renders some attributes in expanded form, such as `@default(dbgenerated("autoincrement()"))`. Browse the resulting data [#browse-the-resulting-data] Your tables are in the same Studio session under **Tables**. Move between what a migration changed and the rows it produced without leaving the app. [Getting Started](/studio/getting-started) covers editing, filtering, and exporting. The Prisma Studio table view showing rows in the post table, including the published column added by a migration. How migration history works [#how-migration-history-works] Prisma Next records every apply in two tables in your database: * `prisma_contract.ledger`: one row per applied migration, with its name, apply time, executed operations, and the schema versions it moved between. * `prisma_contract.contract`: each schema version, stored once and keyed by hash. Studio joins the two to build the timeline and the diffs. Nothing is read from disk and nothing is reconstructed, which is why the history of any database you connect to is complete, including migrations you never ran yourself. These table names are also where to look if you inspect the history over SQL. The hashes are the same ones that make Prisma Next migrations [a graph rather than a numbered list](/orm/next/migrations/the-migration-graph); the design story is in [Rethinking Database Migrations](https://www.prisma.io/blog/rethinking-database-migrations). Availability [#availability] | Surface | Available | | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | Local Studio (`npx prisma@dev studio`) | Yes, with `@prisma/studio-core` 0.32.0 or later | | [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=studio) (embedded Studio) | Yes, for databases with an applied Prisma Next migration history | | Prisma ORM projects using `prisma migrate` | No | In Prisma Console, open your database's Studio tab and select **Migrations**. The view is the same as local Studio, the selected migration is part of the Console URL, and no local setup is required. The stable Prisma CLI (`prisma@latest`) currently bundles an older Studio without the Migrations view. Use `npx prisma@dev studio` until it lands in a stable release. Limitations [#limitations] * **Prisma Next on PostgreSQL only.** Prisma ORM projects using `prisma migrate` record history in a different format, and [Studio does not support MongoDB](/studio), where Prisma Next [stores its history differently](/orm/next/migrations/the-migration-graph#database-specific-details). * **Applied migrations only.** A planned but unapplied migration is not in the database, so it does not appear. * **An empty history hides the view.** The **Migrations** item appears only after the first applied migration. * **Older databases lose the diffs.** If the database was migrated by a Prisma Next version that predates schema snapshots, the timeline and SQL panel still work, and the diff canvas asks you to update Prisma Next. Migrations applied after the update render normally. ## Related pages - [`Getting Started`](https://www.prisma.io/docs/studio/getting-started): Learn how to set up and use Prisma Studio to manage your database # Choose a setup path (/docs/next/getting-started) Location: Next > Choose a setup path Start with a quickstart if you want Prisma Next to create the app. Use the existing-project path if you already have an app and database. Start a new project [#start-a-new-project] #### bun ```bash bunx create-prisma@next ``` #### pnpm ```bash pnpm dlx create-prisma@next ``` #### yarn ```bash yarn dlx create-prisma@next ``` #### npm ```bash npx create-prisma@next ``` - [Quickstart with PostgreSQL](/next/quickstart/postgresql): Create the app, choose PostgreSQL, initialize the database, seed data, and run the first query. - [Quickstart with MongoDB](/next/quickstart/mongodb): Create the app, choose MongoDB, start or connect to MongoDB, seed data, and run the first query. Use Prisma Postgres [#use-prisma-postgres] #### bun ```bash bunx create-prisma@next ``` #### pnpm ```bash pnpm dlx create-prisma@next ``` #### yarn ```bash yarn dlx create-prisma@next ``` #### npm ```bash npx create-prisma@next ``` - [Quickstart with Prisma Postgres](/prisma-postgres/quickstart/prisma-next): Create a Prisma Next app and let setup provision Prisma Postgres for the first run. - [From the CLI](/next/prisma-postgres/from-the-cli): Start from the command line when you want the Prisma Postgres path without browsing Console first. Add to an existing project [#add-to-an-existing-project] #### bun ```bash bunx prisma-next init ``` #### pnpm ```bash pnpm dlx prisma-next init ``` #### yarn ```bash yarn dlx prisma-next init ``` #### npm ```bash npx prisma-next init ``` - [Add to PostgreSQL](/next/add-to-existing-project/postgresql): Add Prisma Next to an existing PostgreSQL app and infer a starter contract from the live schema. - [Add to MongoDB](/next/add-to-existing-project/mongodb): Add Prisma Next to an existing MongoDB app and model the collections you want to query first. After setup [#after-setup] * Use the generated app scripts for the first run. * Open `prisma-next.md` or the installed Prisma Next skills when you want agent-ready guidance inside the project. * Change the starter contract when you are ready to model your own data. * Open the [Prisma Next overview](/orm/next) when you want the concepts behind the setup. # Introduction to Prisma Next (/docs/next) Location: Introduction to Prisma Next Prisma Next is a ground-up rebuild of Prisma ORM, covering the runtime, query APIs, migration flow, and project setup. > [!NOTE] > Prisma Next is in Early Access > > Prisma Next is the next major version of Prisma ORM, available now in Early Access. It’s the cutting-edge version of Prisma ORM and will become the future of Prisma, so we’d love for you to try it, explore what’s new, and [share your feedback in Discord](https://pris.ly/discord). > > If you want to stay on the current generally available version of Prisma ORM, you can continue with [Prisma 7](/getting-started). Use Prisma Next when you want to try the new developer experience before it becomes the default Prisma ORM path. #### bun ```bash bunx create-prisma@next ``` #### pnpm ```bash pnpm dlx create-prisma@next ``` #### yarn ```bash yarn dlx create-prisma@next ``` #### npm ```bash npx create-prisma@next ``` Start with the setup page when you want a guided first run. - [Choose a setup path](/next/getting-started): Pick a new-project quickstart or add Prisma Next to an existing app. What you can try [#what-you-can-try] - [Quickstart with PostgreSQL](/next/quickstart/postgresql): Create a Prisma Next app, initialize the database, seed data, and run the first query. - [Quickstart with MongoDB](/next/quickstart/mongodb): Create a Prisma Next app with a local MongoDB replica set or your own MongoDB deployment. - [Add to PostgreSQL](/next/add-to-existing-project/postgresql): Add Prisma Next to an existing PostgreSQL app with `prisma-next init`. - [Add to MongoDB](/next/add-to-existing-project/mongodb): Add Prisma Next to an existing MongoDB app and model the collections you want to query first. - [Use Prisma Postgres](/prisma-postgres/quickstart/prisma-next): Create a Prisma Next app backed by Prisma Postgres. Learn the fundamentals [#learn-the-fundamentals] Once you are connected, the Fundamentals section teaches the everyday query patterns. - [Reading data](/orm/next/fundamentals/reading-data): Filter with where, project with select, sort, and paginate. - [Writing data](/orm/next/fundamentals/writing-data): Create, update, delete, upsert, and the bulk write variants. - [Relations and joins](/orm/next/fundamentals/relations-and-joins): Read related records with include on PostgreSQL and MongoDB. - [Transactions](/orm/next/fundamentals/transactions): Make several writes succeed or fail together. - [Advanced queries](/orm/next/fundamentals/advanced-queries): The SQL builder and the MongoDB pipeline builder for shapes the ORM can't express. Learn the concepts [#learn-the-concepts] - [Prisma Next overview](/orm/next): Learn the core ideas behind contracts, emitted artifacts, runtime clients, query styles, and migrations. ## 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, Prisma Postgres, or Prisma Compute in a new or existing TypeScript 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 # Deploy your first app (/docs/prisma-compute/deploy) Location: Prisma Compute > Deploy your first app [Prisma Compute](/compute) is serverless hosting for TypeScript apps. It runs your app right next to your Prisma Postgres database, so the trip from app to data stays short. This is a quickstart: sign in, then deploy. There are two ways in: * **To start fresh**, scaffold a new app and deploy it in one step with `create-prisma`. Follow [Option A](#option-a-scaffold-a-new-app-with-create-prisma). * **To deploy an app you already have**, run a deploy from its directory. Follow [Option B](#option-b-deploy-a-project-you-already-have). To learn more about how Compute works, see the [resource model](/compute#the-model) for a mental model. Prerequisites [#prerequisites] Before you start, make sure you have: * **A JavaScript runtime.** Node.js 22.12 or newer for `npx`/`pnpm dlx`, or Bun for `bunx`. * **A [Prisma Data Platform account](https://pris.ly/pdp).** Free to create, and it holds your workspace. * **An app, if you are bringing your own.** Compute deploys **Next.js**, **Nuxt**, **Astro**, **Hono**, **NestJS**, **TanStack Start**, and plain **Bun** servers today, including **Elysia** (which runs on Bun). Skip this if you are scaffolding a new app below. > [!NOTE] > Next.js apps should set `output: "standalone"` in their Next.js config. The `create-prisma` template already sets this for you. > > ```ts title="next.config.ts" > export default { output: "standalone" }; > ``` 1. Sign in [#1-sign-in] Sign in once. This is the only step that needs a human, because it opens your browser: #### bun ```bash bunx @prisma/cli@latest auth login ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest auth login ``` #### yarn ```bash yarn dlx @prisma/cli@latest auth login ``` #### npm ```bash npx @prisma/cli@latest auth login ``` It stores a session on your machine that every later command reads automatically, including a coding agent working in your directory. Confirm it any time with `auth whoami`. Two shortcuts from here: * In CI or a headless environment where no browser can open, use a [service token](/compute/getting-started#automation-and-ci) instead. * To let an agent do the deploying for you, jump to [Hand it to your agent](#hand-it-to-your-agent). 2. Deploy your app [#2-deploy-your-app] Both options finish in the same place: a live URL and a project you can deploy to again. Option A: Scaffold a new app with create-prisma [#option-a-scaffold-a-new-app-with-create-prisma] `create-prisma` builds a TypeScript app from a template, wires up Prisma, and can deploy it to Compute in the same run. Run it and answer the prompts: #### bun ```bash bunx create-prisma@latest ``` #### pnpm ```bash pnpm dlx create-prisma@latest ``` #### yarn ```bash yarn dlx create-prisma@latest ``` #### npm ```bash npx create-prisma@latest ``` It asks for a template, a database provider, and a few options, then asks **"Deploy to Prisma Compute now?"**. Say yes, and the deploy step: * signs you in, if you have not already * creates a Prisma project for the app * builds and deploys it, then prints the live URL * provisions a Prisma Postgres database and wires it in, when you pick PostgreSQL and don't bring your own connection string So your deployed app has a database from its first request. To skip the prompts, pass your choices as flags. Compute deploys are available for the `hono`, `elysia`, `next`, and `tanstack-start` templates: #### bun ```bash bunx create-prisma@latest --name my-api --template hono --provider postgresql --deploy ``` #### pnpm ```bash pnpm dlx create-prisma@latest --name my-api --template hono --provider postgresql --deploy ``` #### yarn ```bash yarn dlx create-prisma@latest --name my-api --template hono --provider postgresql --deploy ``` #### npm ```bash npx create-prisma@latest --name my-api --template hono --provider postgresql --deploy ``` When it finishes, it prints your live URL and adds a `compute:deploy` script so you can redeploy later. Then [verify the deployment](#3-verify-the-deployment). Option B: Deploy a project you already have [#option-b-deploy-a-project-you-already-have] From your app's directory, run: #### bun ```bash bunx @prisma/cli@latest app deploy ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy ``` #### npm ```bash npx @prisma/cli@latest app deploy ``` In one pass, the CLI: 1. **Detects your framework** from your project files, whether that is Next.js, Nuxt, Astro, Hono, NestJS, TanStack Start, or a plain Bun server. To choose it yourself, pass `--framework` (use `--framework bun` for a Bun or Elysia server). 2. **Sets up a project** the first time you deploy from this directory, then writes [`.prisma/local.json`](/compute/getting-started#link-an-existing-project) to pin the directory to that project. That file is a gitignored local cache, not committed config. If your team already has a project, [link it first](/compute/getting-started#link-an-existing-project). 3. **Resolves the target branch.** Inside a Git repository, the CLI uses your current Git branch name; otherwise it falls back to `main`. Pass `--branch ` to choose explicitly. Because each branch is its own isolated environment, this decides where the deploy lands. 4. **Builds and uploads your app**, provisions it, and prints a live URL. Your first deploy is promoted to production automatically, so the URL you get back is your production URL. Need a database too? Add `--db`, and the deploy provisions a Prisma Postgres database and wires its connection string into this deploy target: #### bun ```bash bunx @prisma/cli@latest app deploy --db ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --db ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --db ``` #### npm ```bash npx @prisma/cli@latest app deploy --db ``` 3. Verify the deployment [#3-verify-the-deployment] You have a URL. Confirm the app responds by opening it: #### bun ```bash bunx @prisma/cli@latest app open ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app open ``` #### yarn ```bash yarn dlx @prisma/cli@latest app open ``` #### npm ```bash npx @prisma/cli@latest app open ``` If it does not behave the way you expect, stream its logs: #### bun ```bash bunx @prisma/cli@latest app logs ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app logs ``` #### yarn ```bash yarn dlx @prisma/cli@latest app logs ``` #### npm ```bash npx @prisma/cli@latest app logs ``` `app logs` streams the running app's logs. Build failures surface in the deploy output itself, since the CLI builds on your machine; for builds triggered by a GitHub push or from the Console, stream them with `npx @prisma/cli@latest build logs `. You can also inspect everything you have deployed in the [Console](https://pris.ly/pdp) instead of the terminal: * projects, branches, and apps * deployments, integrations, and domains 4. Deploy again [#4-deploy-again] Run `app deploy` whenever you want to ship a change. After your first deploy, production is protected: deploying to your production branch again needs an explicit `--prod` flag, so you never ship to production by accident. #### bun ```bash bunx @prisma/cli@latest app deploy --prod ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod ``` Deploying from a Git feature branch behaves differently. Instead of touching production, the CLI: * resolves the branch name and creates a matching platform branch if one does not exist yet * gives you an isolated [preview deployment](/compute/branching) with its own app and URL One caveat: your project's very first deploy defines its production branch, whatever that Git branch is called. Run the first deploy from your default branch (e.g. `main`) so previews land where you expect. Preview deploys never ask for confirmation, so run them as often as you like. In scripts and CI, add `--yes` to accept the production confirmation up front: #### bun ```bash bunx @prisma/cli@latest app deploy --prod --yes ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest app deploy --prod --yes ``` #### yarn ```bash yarn dlx @prisma/cli@latest app deploy --prod --yes ``` #### npm ```bash npx @prisma/cli@latest app deploy --prod --yes ``` 5. Set up deploy on push (optional) [#5-set-up-deploy-on-push-optional] Connect your project to a GitHub repository once, and Prisma deploys every push for you: * every commit you push is built and deployed on its own * each branch gets its own preview, with its own URL * you stop running `app deploy` by hand Make sure your project directory is a Git repository with a GitHub remote, then connect it: #### bun ```bash bunx @prisma/cli@latest git connect ``` #### pnpm ```bash pnpm dlx @prisma/cli@latest git connect ``` #### yarn ```bash yarn dlx @prisma/cli@latest git connect ``` #### npm ```bash npx @prisma/cli@latest git connect ``` `git connect` wires up the project this directory is linked to, which exists once you have deployed at least once. For monorepos and CI, see the [GitHub integration docs](/compute/github). Hand it to your agent [#hand-it-to-your-agent] You can let a coding agent do the deploying. Sign in once yourself ([step 1](#1-sign-in)), because the browser step needs a human. After that, anything running in your environment inherits the session, including your agent. Paste this into your agent and fill in the blanks: ```text Build [what you want] in [framework] and deploy it to Prisma Compute using `npx @prisma/cli@latest`. ``` For example: ```text Build a Hono API with a /todos endpoint backed by an in-memory list. Deploy it to Prisma Compute using `npx @prisma/cli@latest`. ``` Notes for your agent: * Run every CLI command as `npx @prisma/cli@latest `, and add `--json` for structured output. * Check login state with `npx @prisma/cli@latest auth whoami`. * On the first deploy, the CLI creates the project and prints a live URL. Open it and confirm the app responds. The first deploy is promoted to production automatically. * To give the app a database, add `--db` to the deploy so Compute provisions and wires a Prisma Postgres database. * If the app needs config or secrets, scope them to the environment you're deploying. Use `--role production` for production deploys and `--role preview` for preview branches, then redeploy: `npx @prisma/cli@latest project env add KEY=value --role production` (or `--role preview`). Don't write production config to the preview scope. For the full scoping rules, see [Environment variables](/compute/environment-variables). What's next [#whats-next] * [Branching](/compute/branching): how preview branches isolate work and map to your Git branches. * [Add environment variables](/compute/environment-variables) for configuration, secrets, and your database connection string. * [Deployments](/compute/deployments): promote, roll back, and inspect what you ship. * [GitHub integration](/compute/github): the full picture on deploy-on-push, monorepos, and cleanup. * [Read the full CLI getting-started guide](/compute/getting-started) for frameworks, project linking, and CI. # 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`: #### bun ```bash bunx --bun prisma@latest init bunx create-db ``` #### pnpm ```bash pnpm dlx prisma@latest init pnpm dlx create-db ``` #### yarn ```bash yarn dlx prisma@latest init yarn dlx create-db ``` #### npm ```bash npx prisma@latest init npx 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: #### bun ```bash bun init ``` #### pnpm ```bash pnpm init ``` #### yarn ```bash yarn init ``` #### npm ```bash npm init ``` #### bun ```bash bun add typescript tsx @types/node @types/pg --dev ``` #### pnpm ```bash pnpm add typescript tsx @types/node @types/pg -D ``` #### yarn ```bash yarn add typescript tsx @types/node @types/pg --dev ``` #### npm ```bash npm install typescript tsx @types/node @types/pg -D ``` 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: #### bun ```bash bunx tsc --init ``` #### pnpm ```bash pnpm dlx tsc --init ``` #### yarn ```bash yarn dlx tsc --init ``` #### npm ```bash npx 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: #### bun ```bash bun add prisma --dev bun add @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 ``` #### npm ```bash npm install prisma --save-dev npm install @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): #### bun ```bash bunx prisma migrate dev --name init ``` #### pnpm ```bash pnpm dlx prisma migrate dev --name init ``` #### yarn ```bash yarn dlx prisma migrate dev --name init ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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: #### bun ```bash bunx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### npm ```bash npx 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: #### bun ```bash bunx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### npm ```bash npx 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: #### bun ```bash bunx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### npm ```bash npx 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: #### bun ```bash bunx tsx index.ts ``` #### pnpm ```bash pnpm dlx tsx index.ts ``` #### yarn ```bash yarn dlx tsx index.ts ``` #### npm ```bash npx 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: #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm dlx prisma studio ``` #### yarn ```bash yarn dlx prisma studio ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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 # 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:** #### bun ```bash bunx turbo db:studio ``` #### pnpm ```bash pnpm dlx turbo db:studio ``` #### yarn ```bash yarn dlx turbo db:studio ``` #### npm ```bash npx 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. * `search_prisma_documentation`: Answer a natural-language question about Prisma using the official Prisma documentation, returning a cited answer with links back to the docs. 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. Searching the Prisma documentation [#searching-the-prisma-documentation] The `search_prisma_documentation` tool lets your AI agent answer questions about Prisma ORM, Prisma Postgres, Prisma Compute, schema design, migrations, and more, grounded in the official documentation, without leaving your editor or terminal. Because it's read-only and exposed by the Prisma MCP server you're already connected to, there's no extra setup or second integration to install. When you ask your agent a Prisma question, it picks up the tool automatically and returns an answer with citations linking back to the relevant pages in the [Prisma documentation](/). This keeps the agent's answers current and accurate instead of relying on whatever it happened to learn during training. 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." * "Search the Prisma docs and explain how to deploy a project to Prisma Compute." 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: #### bun ```bash bunx skills add prisma/skills ``` #### pnpm ```bash pnpm dlx skills add prisma/skills ``` #### yarn ```bash yarn dlx skills add prisma/skills ``` #### npm ```bash npx skills add prisma/skills ``` Or install only the ones you need: #### bun ```bash bunx 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 ``` #### npm ```bash npx 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. Available skills for Prisma Next [#available-skills-for-prisma-next] [Prisma Next](/orm/next) ships its own skill set, versioned with the product. Projects scaffolded with `create-prisma` install them automatically; add them to an existing project with: #### bun ```bash bunx skills add prisma/prisma-next/skills ``` #### pnpm ```bash pnpm dlx skills add prisma/prisma-next/skills ``` #### yarn ```bash yarn dlx skills add prisma/prisma-next/skills ``` #### npm ```bash npx skills add prisma/prisma-next/skills ``` | Skill | What your agent uses it for | | ------------------------------- | ---------------------------------------------------------------------------------------------------- | | `prisma-next` | Route a general Prisma Next question to the right skill below | | `prisma-next-quickstart` | First-touch setup and orientation after scaffolding | | `prisma-next-contract` | Edit the schema: models, relations, enums, namespaces, extensions, then emit the contract | | `prisma-next-queries` | Write queries in the right lane: the ORM API, the SQL query builder, or the MongoDB pipeline builder | | `prisma-next-runtime` | Wire `db.ts`, middleware, and environment configuration | | `prisma-next-migrations` | Author migrations: `db update` vs `migration plan`, and filling in data transforms | | `prisma-next-migration-review` | Review migrations on deploy and reconcile concurrent migration work | | `prisma-next-build` | Integrate with the build tool (the Vite contract-emit plugin today) | | `prisma-next-debug` | Read structured error envelopes (`PN-*` codes) and route to the fix | | `prisma-next-upgrade` | Move a project between Prisma Next releases | | `prisma-next-extension-upgrade` | Upgrade extension packs alongside the core | | `prisma-next-feedback` | File a bug or feature request, or route a question to the Prisma Discord | The Prisma Next docs reference these in each page's "Prompt your coding agent" section, with prompts that map to the page you are reading. Useful commands [#useful-commands] List available skills before installing: #### bun ```bash bunx skills add prisma/skills --list ``` #### pnpm ```bash pnpm dlx skills add prisma/skills --list ``` #### yarn ```bash yarn dlx skills add prisma/skills --list ``` #### npm ```bash npx skills add prisma/skills --list ``` List skills currently installed in your project: #### bun ```bash bunx skills list ``` #### pnpm ```bash pnpm dlx skills list ``` #### yarn ```bash yarn dlx skills list ``` #### npm ```bash npx 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: #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm run dev ``` 2. Open Prisma Studio to view your seed data: #### bun ```bash bun run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### npm ```bash npm 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: #### bun ```bash bunx prisma db push --force-reset ``` #### pnpm ```bash pnpm dlx prisma db push --force-reset ``` #### yarn ```bash yarn dlx prisma db push --force-reset ``` #### npm ```bash npx 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: #### bun ```bash bun run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### npm ```bash npm 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: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm dlx prisma generate ``` #### yarn ```bash yarn dlx prisma generate ``` #### npm ```bash npx 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: #### bun ```bash bunx create-next-app@latest tweetsmith ``` #### pnpm ```bash pnpm dlx create-next-app@latest tweetsmith ``` #### yarn ```bash yarn dlx create-next-app@latest tweetsmith ``` #### npm ```bash npx 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: #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm 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: #### bun ```bash bun add lucide-react ``` #### pnpm ```bash pnpm add lucide-react ``` #### yarn ```bash yarn add lucide-react ``` #### npm ```bash npm install 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] #### bun ```bash bun add prisma tsx --dev bun add @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 ``` #### npm ```bash npm install prisma tsx --save-dev npm install @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. #### bun ```bash bunx --bun prisma init --output ../app/generated/prisma bunx 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 ``` #### npm ```bash npx prisma init --output ../app/generated/prisma npx 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] #### bun ```bash bunx prisma db push bunx prisma generate bun 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 ``` #### npm ```bash npx prisma db push npx prisma generate npm run db:test ``` You should see success messages. Open Prisma Studio to view your data: #### bun ```bash bun run db:studio ``` #### pnpm ```bash pnpm run db:studio ``` #### yarn ```bash yarn db:studio ``` #### npm ```bash npm 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] #### bun ```bash bun add uploadthing @uploadthing/react ``` #### pnpm ```bash pnpm add uploadthing @uploadthing/react ``` #### yarn ```bash yarn add uploadthing @uploadthing/react ``` #### npm ```bash npm install 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 # 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). # 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma db pull ``` #### pnpm ```bash pnpm dlx prisma db pull ``` #### yarn ```bash yarn dlx prisma db pull ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma db pull --schema=./alternative/schema.prisma ``` Print to stdout instead of writing to file [#print-to-stdout-instead-of-writing-to-file] #### bun ```bash bunx prisma db pull --print ``` #### pnpm ```bash pnpm dlx prisma db pull --print ``` #### yarn ```bash yarn dlx prisma db pull --print ``` #### npm ```bash npx prisma db pull --print ``` Force overwrite existing schema [#force-overwrite-existing-schema] Ignore any customizations in the current schema: #### bun ```bash bunx prisma db pull --force ``` #### pnpm ```bash pnpm dlx prisma db pull --force ``` #### yarn ```bash yarn dlx prisma db pull --force ``` #### npm ```bash npx prisma db pull --force ``` Set composite type depth for MongoDB [#set-composite-type-depth-for-mongodb] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma db push ``` #### pnpm ```bash pnpm dlx prisma db push ``` #### yarn ```bash yarn dlx prisma db push ``` #### npm ```bash npx prisma db push ``` Accept data loss [#accept-data-loss] Proceed even if the changes might result in data loss: #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma db push --accept-data-loss ``` Specify a schema path [#specify-a-schema-path] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma db push --schema=/tmp/schema.prisma ``` Force reset before push [#force-reset-before-push] Reset the database before applying changes: #### bun ```bash bunx prisma db push --force-reset ``` #### pnpm ```bash pnpm dlx prisma db push --force-reset ``` #### yarn ```bash yarn dlx prisma db push --force-reset ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma db seed ``` #### pnpm ```bash pnpm dlx prisma db seed ``` #### yarn ```bash yarn dlx prisma db seed ``` #### npm ```bash npx prisma db seed ``` Pass custom arguments [#pass-custom-arguments] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma dev ``` #### pnpm ```bash pnpm dlx prisma dev ``` #### yarn ```bash yarn dlx prisma dev ``` #### npm ```bash npx 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: #### bun ```bash bunx prisma dev --name="mydbname" ``` #### pnpm ```bash pnpm dlx prisma dev --name="mydbname" ``` #### yarn ```bash yarn dlx prisma dev --name="mydbname" ``` #### npm ```bash npx prisma dev --name="mydbname" ``` Run in detached mode [#run-in-detached-mode] Run the server in the background: #### bun ```bash bunx prisma dev --detach ``` #### pnpm ```bash pnpm dlx prisma dev --detach ``` #### yarn ```bash yarn dlx prisma dev --detach ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma dev ls ``` #### pnpm ```bash pnpm dlx prisma dev ls ``` #### yarn ```bash yarn dlx prisma dev ls ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma dev rm mydb ``` #### pnpm ```bash pnpm dlx prisma dev rm mydb ``` #### yarn ```bash yarn dlx prisma dev rm mydb ``` #### npm ```bash npx prisma dev rm mydb ``` Remove multiple databases with a pattern [#remove-multiple-databases-with-a-pattern] Remove all databases starting with `mydb`: #### bun ```bash bunx prisma dev rm mydb* ``` #### pnpm ```bash pnpm dlx prisma dev rm mydb* ``` #### yarn ```bash yarn dlx prisma dev rm mydb* ``` #### npm ```bash npx prisma dev rm mydb* ``` Force remove a running database [#force-remove-a-running-database] Stop and remove a database in one command: #### bun ```bash bunx prisma dev rm --force mydb ``` #### pnpm ```bash pnpm dlx prisma dev rm --force mydb ``` #### yarn ```bash yarn dlx prisma dev rm --force mydb ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma dev start mydb ``` #### pnpm ```bash pnpm dlx prisma dev start mydb ``` #### yarn ```bash yarn dlx prisma dev start mydb ``` #### npm ```bash npx prisma dev start mydb ``` Start multiple databases with a pattern [#start-multiple-databases-with-a-pattern] Start all databases starting with `mydb`: #### bun ```bash bunx prisma dev start mydb* ``` #### pnpm ```bash pnpm dlx prisma dev start mydb* ``` #### yarn ```bash yarn dlx prisma dev start mydb* ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma dev stop mydb ``` #### pnpm ```bash pnpm dlx prisma dev stop mydb ``` #### yarn ```bash yarn dlx prisma dev stop mydb ``` #### npm ```bash npx prisma dev stop mydb ``` Stop multiple databases with a pattern [#stop-multiple-databases-with-a-pattern] Stop all databases starting with `mydb`: #### bun ```bash bunx prisma dev stop mydb* ``` #### pnpm ```bash pnpm dlx prisma dev stop mydb* ``` #### yarn ```bash yarn dlx prisma dev stop mydb* ``` #### npm ```bash npx 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 # 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] #### bun ```bash bunx prisma platform status ``` #### pnpm ```bash pnpm dlx prisma platform status ``` #### yarn ```bash yarn dlx prisma platform status ``` #### npm ```bash npx prisma platform status ``` Output status as JSON [#output-status-as-json] #### bun ```bash bunx prisma platform status --json ``` #### pnpm ```bash pnpm dlx prisma platform status --json ``` #### yarn ```bash yarn dlx prisma platform status --json ``` #### npm ```bash npx prisma platform status --json ``` # 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] #### bun ```bash bunx prisma migrate deploy ``` #### pnpm ```bash pnpm dlx prisma migrate deploy ``` #### yarn ```bash yarn dlx prisma migrate deploy ``` #### npm ```bash npx prisma migrate deploy ``` Specify a schema path [#specify-a-schema-path] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma migrate dev ``` #### pnpm ```bash pnpm dlx prisma migrate dev ``` #### yarn ```bash yarn dlx prisma migrate dev ``` #### npm ```bash npx prisma migrate dev ``` Name the migration [#name-the-migration] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma migrate dev --name added_job_title ``` Create migration without applying [#create-migration-without-applying] #### bun ```bash bunx prisma migrate dev --create-only ``` #### pnpm ```bash pnpm dlx prisma migrate dev --create-only ``` #### yarn ```bash yarn dlx prisma migrate dev --create-only ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma migrate diff \ --from-config-datasource \ --to-schema=next_datamodel.prisma \ --script ``` Compare schema to database [#compare-schema-to-database] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma migrate diff \ --from-migrations ./migrations \ --to-config-datasource \ --script ``` Pipe output to db execute [#pipe-output-to-db-execute] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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: #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma migrate reset ``` #### pnpm ```bash pnpm dlx prisma migrate reset ``` #### yarn ```bash yarn dlx prisma migrate reset ``` #### npm ```bash npx prisma migrate reset ``` Skip confirmation prompt [#skip-confirmation-prompt] #### bun ```bash bunx prisma migrate reset --force ``` #### pnpm ```bash pnpm dlx prisma migrate reset --force ``` #### yarn ```bash yarn dlx prisma migrate reset --force ``` #### npm ```bash npx prisma migrate reset --force ``` Specify a schema path [#specify-a-schema-path] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma migrate resolve --applied 20201231000000_add_users_table ``` Mark a migration as rolled back [#mark-a-migration-as-rolled-back] #### bun ```bash bunx 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 ``` #### npm ```bash npx prisma migrate resolve --rolled-back 20201231000000_add_users_table ``` Specify a schema path [#specify-a-schema-path] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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] #### bun ```bash bunx prisma migrate status ``` #### pnpm ```bash pnpm dlx prisma migrate status ``` #### yarn ```bash yarn dlx prisma migrate status ``` #### npm ```bash npx prisma migrate status ``` Specify a schema path [#specify-a-schema-path] #### bun ```bash bunx 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 ``` #### npm ```bash npx 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 # CLI configuration (/docs/cli/next/configuration) Location: CLI > Next > CLI configuration Prisma Next CLI commands use `prisma-next.config.ts` as the project entrypoint for contract emission, database operations, and migrations. Config file [#config-file] Commands that need project context read the Prisma Next config from your project. For PostgreSQL projects, use the Postgres config helper: ```typescript title="prisma-next.config.ts" import "dotenv/config"; import { defineConfig } from "@prisma-next/postgres/config"; export default defineConfig({ contract: "./prisma/contract.prisma", db: { connection: process.env["DATABASE_URL"]!, }, }); ``` For MongoDB projects, import `defineConfig` from `@prisma-next/mongo/config` instead. Pass `--config` when your config file is not in the default project location: ```bash prisma-next contract emit --config ./config/prisma-next.config.ts ``` Emit-only config [#emit-only-config] `contract emit` does not connect to a database, so the config can omit `db.connection`: ```typescript title="prisma-next.config.ts" import { defineConfig } from "@prisma-next/postgres/config"; export default defineConfig({ contract: "./prisma/contract.prisma", }); ``` Add `db.connection` before running commands such as `db verify`, `db sign`, `db init`, `db update`, `db schema`, `contract infer`, or `migration apply`. Extension packs [#extension-packs] Add extension control descriptors to the config when your contract uses extension-provided types: ```typescript title="prisma-next.config.ts" import { defineConfig } from "@prisma-next/postgres/config"; import pgvector from "@prisma-next/extension-pgvector/control"; export default defineConfig({ contract: "./prisma/contract.prisma", extensions: [pgvector], db: { connection: process.env["DATABASE_URL"]!, }, }); ``` Re-run `prisma-next contract emit` after changing extension packs, then update the matching runtime client. Database URLs [#database-urls] Database commands accept `--db `. If you omit it, Prisma Next can use the database connection from `prisma-next.config.ts`. ```bash prisma-next db verify --db "$DATABASE_URL" ``` Environment variables [#environment-variables] | Variable | What it does | | -------------- | -------------------------------------------------------------------------------------- | | `DATABASE_URL` | Common place to store the database connection string used by config files and scripts. | | `NO_COLOR=1` | Disables colored terminal output. | Output modes [#output-modes] Use the default text output when running commands locally. Use `--json` in CI or automation: ```bash prisma-next db verify --db "$DATABASE_URL" --json ``` Use `--no-interactive` for scripts that must never pause for user input. ## Related pages - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. - [`prisma-next db sign`](https://www.prisma.io/docs/cli/next/db-sign): Sign a database with the current Prisma Next contract. # prisma-next contract emit (/docs/cli/next/contract-emit) Location: CLI > Next > prisma-next contract emit `prisma-next contract emit` reads your contract source and writes the generated artifacts used by the runtime, verification, and migration tooling. The command is offline. It does not need a database connection. Usage [#usage] ```bash prisma-next contract emit ``` Options [#options] | Option | What it does | | ----------------- | ---------------------------------------------- | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--json` | Prints a machine-readable result. | | `-q`, `--quiet` | Suppresses nonessential output. | | `-v`, `--verbose` | Prints more detail. | What it creates [#what-it-creates] The command emits: * `contract.json`, the canonical machine-readable contract * `contract.d.ts`, the generated TypeScript contract declarations Do not edit these files by hand. Re-run `contract emit` after changing the contract source or extension pack list. Examples [#examples] ```bash prisma-next contract emit prisma-next contract emit --config ./custom-config.ts prisma-next contract emit --json ``` Next steps [#next-steps] After emitting, choose the database workflow: * use [`prisma-next db init`](/cli/next/db-init) for first-time bootstrap * use [`prisma-next db update`](/cli/next/db-update) for direct reconciliation * use [`prisma-next migration plan`](/cli/next/migration-plan) for checked-in migrations * use [`prisma-next db verify`](/cli/next/db-verify) to check drift ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. - [`prisma-next db sign`](https://www.prisma.io/docs/cli/next/db-sign): Sign a database with the current Prisma Next contract. # prisma-next contract infer (/docs/cli/next/contract-infer) Location: CLI > Next > prisma-next contract infer `prisma-next contract infer` inspects a live database and writes a starter PSL contract. Use it when you are adding Prisma Next to an existing database and want an initial contract to review and edit. Usage [#usage] ```bash prisma-next contract infer --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | ---------------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--output ` | Writes the inferred PSL contract to a specific path. | | `--json` | Prints a machine-readable result. | Examples [#examples] ```bash prisma-next contract infer --db "$DATABASE_URL" prisma-next contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma prisma-next contract infer --db "$DATABASE_URL" --json ``` What to review [#what-to-review] Inference gives you a starting point, not a finished design. Review: * model and field names * relation names * mapped database names * defaults, indexes, and constraints * extension-backed column types Then run: ```bash prisma-next contract emit prisma-next db sign --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` `db sign` is the handoff point where you record that the existing database matches the reviewed contract. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. - [`prisma-next db sign`](https://www.prisma.io/docs/cli/next/db-sign): Sign a database with the current Prisma Next contract. # prisma-next db init (/docs/cli/next/db-init) Location: CLI > Next > prisma-next db init `prisma-next db init` creates missing database structures from the current emitted contract and signs the database. Use it for first setup of a database that should match your current contract. Usage [#usage] ```bash prisma-next db init --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | ----------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--dry-run` | Shows planned operations without applying them. | | `--json` | Prints a machine-readable result. | Behavior [#behavior] `db init` is intended for bootstrap work. It creates missing structures needed by the contract and writes the contract marker after the database matches. Run a dry run first when you are not working with a disposable local database: ```bash prisma-next db init --db "$DATABASE_URL" --dry-run ``` Examples [#examples] ```bash prisma-next contract emit prisma-next db init --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` ```bash prisma-next db init --db "$DATABASE_URL" --dry-run --json ``` When to use db update instead [#when-to-use-db-update-instead] Use [`prisma-next db update`](/cli/next/db-update) when the database already exists and you want Prisma Next to reconcile it with a changed contract. Use [`prisma-next migration plan`](/cli/next/migration-plan) when you want a reviewable migration package in version control. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. - [`prisma-next db sign`](https://www.prisma.io/docs/cli/next/db-sign): Sign a database with the current Prisma Next contract. # prisma-next db schema (/docs/cli/next/db-schema) Location: CLI > Next > prisma-next db schema `prisma-next db schema` reads the live database schema and prints it. The command is read-only. Use it when you need to inspect what Prisma Next sees in the database before inferring, signing, updating, or debugging drift. Usage [#usage] ```bash prisma-next db schema --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | ---------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--json` | Prints machine-readable schema output. | Examples [#examples] ```bash prisma-next db schema --db "$DATABASE_URL" prisma-next db schema --db "$DATABASE_URL" --json > schema.json ``` Related commands [#related-commands] Use [`prisma-next contract infer`](/cli/next/contract-infer) when you want to turn a live schema into a starter PSL contract. Use [`prisma-next db verify`](/cli/next/db-verify) when you want to compare the live schema with the emitted contract. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db sign`](https://www.prisma.io/docs/cli/next/db-sign): Sign a database with the current Prisma Next contract. # prisma-next db sign (/docs/cli/next/db-sign) Location: CLI > Next > prisma-next db sign `prisma-next db sign` verifies that the live database satisfies the emitted contract and writes the database signature. Use it after importing or inferring an existing schema, or after a deployment flow that already applied the required database changes. Usage [#usage] ```bash prisma-next db sign --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | ---------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--json` | Prints a machine-readable result. | Example [#example] ```bash prisma-next contract emit prisma-next db sign --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` When to use it [#when-to-use-it] Use `db sign` only after you believe the live database already matches the emitted contract. It is common after: * `contract infer` for a brownfield database * a manually reviewed migration flow * a database restore that you need to mark as matching the current contract Do not use `db sign` to hide drift. If verification fails, fix the contract or database first. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. # prisma-next db update (/docs/cli/next/db-update) Location: CLI > Next > prisma-next db update `prisma-next db update` compares the live database with the emitted contract and applies the required changes. Use it for direct reconciliation when you do not need a checked-in migration package. Usage [#usage] ```bash prisma-next db update --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | --------------------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--dry-run` | Shows planned operations without applying them. | | `-y`, `--yes` | Confirms prompts where the command supports confirmation. | | `--json` | Prints a machine-readable result. | Recommended flow [#recommended-flow] ```bash prisma-next contract emit prisma-next db update --db "$DATABASE_URL" --dry-run prisma-next db update --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` Use `--dry-run` before applying changes in shared environments. When to use migrations instead [#when-to-use-migrations-instead] For reviewable database changes in version control, use [`prisma-next migration plan`](/cli/next/migration-plan) and [`prisma-next migration apply`](/cli/next/migration-apply). Use `db update` for local development, preview environments, and workflows where direct reconciliation is acceptable. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. # prisma-next db verify (/docs/cli/next/db-verify) Location: CLI > Next > prisma-next db verify `prisma-next db verify` checks whether the database marker and live schema match your emitted contract. Use it in CI and deployment checks before application code that depends on a contract reaches users. Usage [#usage] ```bash prisma-next db verify --db "$DATABASE_URL" ``` Options [#options] | Option | What it does | | ----------------- | --------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--config ` | Reads a specific `prisma-next.config.ts` file. | | `--marker-only` | Checks only the database marker. | | `--schema-only` | Checks only whether the live schema satisfies the contract. | | `--strict` | Fails if the database includes schema elements not present in the contract. | | `--json` | Prints machine-readable output. | Examples [#examples] ```bash prisma-next db verify --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" --strict prisma-next db verify --db "$DATABASE_URL" --schema-only prisma-next db verify --db "$DATABASE_URL" --marker-only ``` Use JSON output in automation: ```bash prisma-next db verify --db "$DATABASE_URL" --json ``` What failures mean [#what-failures-mean] | Failure | Meaning | | ------------------ | -------------------------------------------------------------------------------------------- | | Marker mismatch | The database was not signed for the emitted contract, or the contract changed after signing. | | Schema mismatch | The live database does not satisfy the emitted contract. | | Strict mismatch | The database has extra schema elements not present in the contract. | | Extension mismatch | The contract requires an extension that is not wired in the config. | Fix the database or contract, emit again if needed, then verify again. ## Related pages - [`CLI configuration`](https://www.prisma.io/docs/cli/next/configuration): Configure Prisma Next CLI commands with prisma-next.config.ts and global flags. - [`prisma-next contract emit`](https://www.prisma.io/docs/cli/next/contract-emit): Emit Prisma Next contract artifacts. - [`prisma-next contract infer`](https://www.prisma.io/docs/cli/next/contract-infer): Infer a starter contract from an existing database. - [`prisma-next db init`](https://www.prisma.io/docs/cli/next/db-init): Initialize a database from the current Prisma Next contract. - [`prisma-next db schema`](https://www.prisma.io/docs/cli/next/db-schema): Inspect a live database schema. # Prisma Next CLI (/docs/cli/next) Location: CLI > Prisma Next CLI The Prisma Next CLI is exposed as `prisma-next`. It reads your `prisma-next.config.ts`, emits contract artifacts, verifies databases, and manages Prisma Next migrations. > [!NOTE] > Prisma Next is in Early Access > > Prisma Next is the next major version of Prisma ORM, available now in Early Access. It’s the cutting-edge version of Prisma ORM and will become the future of Prisma, so we’d love for you to try it, explore what’s new, and [share your feedback in Discord](https://pris.ly/discord). > > If you want to stay on the current generally available version of Prisma ORM, you can continue with [Prisma 7](/getting-started). Install the CLI package in a Prisma Next project: ```bash npm install -D prisma-next ``` Then run commands with your package manager: ```bash npx prisma-next help npx prisma-next contract emit ``` For a full app scaffold, use a [Prisma Next quickstart](/next/quickstart/postgresql). That path creates the project files and package scripts for you. This CLI reference is for the lower-level commands those scripts call. Common workflows [#common-workflows] Start an existing project: ```bash prisma-next init --target postgres --authoring psl prisma-next contract emit prisma-next db init --db "$DATABASE_URL" ``` Adopt an existing database: ```bash prisma-next contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma prisma-next contract emit prisma-next db sign --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` Use checked-in migrations: ```bash prisma-next contract emit prisma-next migration plan --name add-users prisma-next migration status --db "$DATABASE_URL" prisma-next migration apply --db "$DATABASE_URL" prisma-next db verify --db "$DATABASE_URL" ``` Command groups [#command-groups] | Command | Purpose | | ------------------------------------------------------------ | ----------------------------------------------------------------------------------- | | [`prisma-next init`](/cli/next/init) | Add Prisma Next files to a project. | | [`prisma-next contract emit`](/cli/next/contract-emit) | Emit `contract.json` and `contract.d.ts` from your contract source. | | [`prisma-next contract infer`](/cli/next/contract-infer) | Infer a starter PSL contract from an existing database. | | [`prisma-next db init`](/cli/next/db-init) | Create missing database structures from the current contract and sign the database. | | [`prisma-next db update`](/cli/next/db-update) | Reconcile an existing database with the current contract. | | [`prisma-next db schema`](/cli/next/db-schema) | Inspect the live database schema. | | [`prisma-next db sign`](/cli/next/db-sign) | Record that a database matches the current contract. | | [`prisma-next db verify`](/cli/next/db-verify) | Check that a database still matches the current contract. | | [`prisma-next migration plan`](/cli/next/migration-plan) | Create an on-disk migration package from contract changes. | | [`prisma-next migration new`](/cli/next/migration-new) | Scaffold a migration package for manual authoring. | | [`prisma-next migration apply`](/cli/next/migration-apply) | Apply pending on-disk migrations. | | [`prisma-next migration status`](/cli/next/migration-status) | Show migration history and applied state. | | [`prisma-next migration show`](/cli/next/migration-show) | Inspect a migration package. | | [`prisma-next migration ref`](/cli/next/migration-ref) | Manage named migration refs. | Global flags [#global-flags] Most Prisma Next commands accept these flags. | Flag | What it does | | ------------------ | ---------------------------------------------------------- | | `--json` | Print machine-readable output. Use this in CI and scripts. | | `-q`, `--quiet` | Suppress nonessential output. | | `-v`, `--verbose` | Print more detail. | | `--trace` | Include stack traces for failures. | | `--color` | Force colored output. | | `--no-color` | Disable colored output. | | `--interactive` | Allow prompts. | | `--no-interactive` | Disable prompts. | | `-y`, `--yes` | Accept prompts where the command supports confirmation. | Use `prisma-next --help` when you need the exact command help from the installed preview version. ## 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 # prisma-next init (/docs/cli/next/init) Location: CLI > Next > prisma-next init `prisma-next init` scaffolds the Prisma Next config, contract source, and runtime files inside an existing project. Use a [Prisma Next quickstart](/next/quickstart/postgresql) when you want a complete new application template. Use `prisma-next init` when you already have a project and want to add the lower-level Prisma Next files. Usage [#usage] ```bash prisma-next init ``` Run it non-interactively: ```bash prisma-next init --yes --target postgres --authoring psl ``` Options [#options] | Option | What it does | | ---------------------- | -------------------------------------------------------------- | | `--target ` | Sets the database target. Use `postgres` or `mongodb`. | | `--authoring