# Prisma Documentation - Full Content Feed This file contains the current Prisma documentation in machine-readable format. Legacy Prisma ORM v6 content is not included here; fetch any v6 page directly by appending `.md` to its URL (for example, https://www.prisma.io/docs/orm/v6/....md). For the documentation index, see https://www.prisma.io/docs/llms.txt. --- # Start a TypeScript app with Postgres on Prisma for free (/docs/full-stack-tutorial) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. From an empty directory to a live TypeScript app with a Prisma Postgres database on Prisma Compute, with the Free plan limits listed. Location: Start a TypeScript app with Postgres on Prisma for free The fastest path to a TypeScript app with a Postgres database on Prisma is the CLI: it scaffolds the app, runs it on a local [Prisma Postgres](https://www.prisma.io/docs/postgres) database with no account, and, once you sign in, deploys it to [Prisma Compute](https://www.prisma.io/docs/compute) and creates its database there. Everything runs on the [Free plan](#what-the-free-plan-includes) with no credit card. The steps below do it by hand, and the prompt under [Use with your agent](#use-with-your-agent) runs the same journey end to end. [Prisma Composer](https://www.prisma.io/docs/composer) declares your app: its services, its databases, and how they connect. [Prisma ORM](https://www.prisma.io/docs/orm) types your data. Prisma Postgres stores it, locally while you develop and on the platform when you deploy. One declaration drives everything: the same `module.ts` runs the app on your machine and deploys it to Prisma Compute. Plan on about 15 minutes. It uses the `hono` template so you get a small API you can verify with curl at every step. The same journey works for the other templates; the [framework guides](https://www.prisma.io/docs/guides) cover each one. ## Prerequisites [#prerequisites] * Node.js 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer (24 recommended), or Bun * If you use npm, the npm that ships with your Node.js release (npm 10 on Node.js 22) * A [Prisma Data Platform account](https://pris.ly/pdp) for the deploy step, free to create, with no credit card needed on the [Free plan](#what-the-free-plan-includes) * No database needed: local runs provision a local Prisma Postgres, and deploys provision a real one, both from your Composer declaration > [!NOTE] > Already have an app? > > Keep your code and add a small Prisma Composer declaration next to it: a `service.ts` for each server and one `module.ts`. The server reads its port from `service.port()` and binds `0.0.0.0`; [Port an existing app](https://www.prisma.io/docs/composer/porting-an-app) lists the other changes and has an agent prompt that makes them, and [Bring an app you already have](https://www.prisma.io/docs/prisma-compute/deploy#bring-an-app-you-already-have) is a worked example. Once `npm run build` and `npx prisma dev` run it, continue at [step 5](#5-deploy-app-and-database-to-prisma-compute). SvelteKit and Deno apps do not deploy to Prisma Compute yet. ## What the Free plan includes [#what-the-free-plan-includes] Everything in this tutorial runs on the Free plan: $0 a month, no credit card, no time limit, and no usage billing. The limits below are the ones on the [pricing page](https://www.prisma.io/pricing), which also lists the paid plans. They apply to your whole [workspace](https://www.prisma.io/docs/console/concepts#workspace), the billing unit of your Prisma account that holds all of your projects and databases, so each number is shared across everything in the workspace, not granted to each database. Prisma ORM is optional on both products: Prisma Postgres works with any PostgreSQL client, and Compute runs apps that do not use Prisma ORM. See [Do I need Prisma ORM to use Compute?](https://www.prisma.io/docs/compute/faq#do-i-need-prisma-orm-to-use-compute). The scaffold in this tutorial uses Prisma ORM 8, which is a release candidate; see [Release status](https://www.prisma.io/docs/orm/release-status). ### Prisma Postgres [#prisma-postgres] | Limit | Free plan | | ------------------ | --------------- | | Operations | 200,000 a month | | Storage | 2 GB | | Databases | 50 | | Data transfer | Unlimited | | Pooled connections | 10 | | Direct connections | 10 | | Automated backups | None | Each query is one operation, whether it reads or writes. See [What is an operation?](https://www.prisma.io/docs/postgres/faq#what-is-an-operation). Direct connections are the ones PostgreSQL tools such as `pg_dump` open, and 5 of the 10 are reserved for platform operations; see [Connection limits](https://www.prisma.io/docs/postgres/database/connection-pooling#connection-limits). The Free plan has no automated backups, and Prisma Postgres cannot yet restore a database to an earlier point in time, so keep your own copies with `pg_dump`, the PostgreSQL command-line backup tool, over a direct connection. See [Backups](https://www.prisma.io/docs/postgres/database/backups). ### Prisma Compute [#prisma-compute] | Meter | Free plan | | ------------------ | -------------------- | | Requests | 1,000,000 a month | | Provisioned memory | 360 GB-hours a month | | Active CPU | 4 vCPU-hours a month | | Outbound bandwidth | 10 GB a month | A GB-hour is one gigabyte of memory allocated for one hour, and a vCPU-hour is one virtual CPU in use for one hour. Memory counts only while the app is running or you have chosen to keep it awake, because an idle app scales to zero: it stops running and costs nothing while idle. Outbound bandwidth is the data your app sends out to the internet, and incoming requests do not count. It is separate from the database's unlimited data transfer: Compute includes 10 GB of outbound bandwidth a month on Free. See [Compute pricing](https://www.prisma.io/docs/compute/pricing) for what each meter measures. ### Check your usage and upgrade [#check-your-usage-and-upgrade] The Free plan has no usage billing, so reaching a limit does not add a charge. Operations and the four Compute meters are monthly limits, while storage and the number of databases are not tied to a month. To see how much a database has used, run `npx prisma postgres usage `, or track usage in the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=%28index%29); see [Billing and limits](https://www.prisma.io/docs/postgres#billing-and-limits). Usage reporting for Compute in the CLI and API is still being built. To go past a limit, move the workspace to a paid plan. Paid plans include more operations, storage, and requests, then bill usage beyond those amounts. Compute memory, CPU, and bandwidth are billed per use on paid plans, and a spend limit you set in the Console counts those charges and stops queries to the workspace's databases when it is reached. The [pricing page](https://www.prisma.io/pricing) has the rates. ## Use with your agent [#use-with-your-agent] If you would rather hand the work to a coding agent, this prompt runs the same journey as the one on the [getting started page](https://www.prisma.io/docs), with the `hono` template chosen for you: The prompt uses npm and Node.js. On Bun, replace `npm create prisma@latest --` with `bun create prisma@latest`, `npx` with `bunx`, and `npm run` with `bun run`. ```text Create a new Hono API composed with Prisma Composer and Prisma ORM, run it locally, and deploy it to Prisma Compute. Check the Node.js version first: `node --version` must print 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer. For the nuxt template, it must print 22.22.3 or newer on the 22 line, 24.15 or newer on the 24 line, or 26 or newer, because Nuxt requires it. The npm that ships with your Node.js release works; on Node.js 22 that is npm 10. 1. Scaffold: `npm create prisma@latest -- my-app --template hono --provider postgres --yes`. Then run `npx prisma@latest init` in `my-app` to confirm the Prisma agent skills the scaffold installed are current, and use them. 2. Read `module.ts` and `service.ts` first: the Composer module provisions the database and the service, and it is what `dev` and `deploy` operate on. 3. Build and run locally: `npm run build`, then `npx prisma dev --detach`, which returns once the app answers and leaves it running. This provisions a local Prisma Postgres database and applies the contract; no DATABASE_URL is needed. Sample users are seeded on the app's first query. Verify that `curl "$(npx prisma dev url my-app.app)/users"` returns the seeded users, then run `npx prisma dev stop`. 4. Deploy: check `npx prisma auth whoami`; if I am not signed in, stop and ask me to run `npx prisma auth login` (it opens a browser). The scaffold already wrote the baseline migration under `migrations/app/`; note its directory name, which ends in `_init`. The `composer` section of the scaffold's `prisma.config.ts` already sets the deploy region, so do not add one. Then run `npx prisma deploy` and verify the live URL's /users endpoint with curl. The deploy creates the project and provisions the database from the module declaration; do not pass a DATABASE_URL. 5. Evolve the schema: add `role String @default("member")` to the User model in `src/prisma/contract.prisma`, run `npx prisma contract emit`, add `"role"` to the typed select and the returned object in `src/prisma/users.ts`, and plan the migration with `npx prisma migration plan --name add-user-role --from `. Then run `npm run build` and `npx prisma deploy` again, and verify the live /users now returns `role: "member"` with the same createdAt values as before. ``` ## 1. Scaffold the app [#1-scaffold-the-app] One command creates a Composer-declared app with Prisma ORM wired in: #### bun ```bash bun create prisma@latest my-app --template hono --provider postgres --no-deploy ``` #### pnpm ```bash pnpm create prisma@latest my-app --template hono --provider postgres --no-deploy ``` #### yarn ```bash yarn create prisma@latest my-app --template hono --provider postgres --no-deploy ``` #### npm ```bash npm create prisma@latest -- my-app --template hono --provider postgres --no-deploy ``` Answer the prompts for contract authoring style, package manager, and agent skills, or pass the `--authoring`, `--package-manager`, and `--skills` flags to skip them (see the [create-prisma reference](https://www.prisma.io/docs/prisma-orm/create-prisma); Deno projects cannot deploy to Prisma Compute yet, so this tutorial uses Node.js or Bun). Then enter the project: #### bun ```bash cd my-app ``` #### pnpm ```bash cd my-app ``` #### yarn ```bash cd my-app ``` #### npm ```bash cd my-app ``` If you work with a coding agent, run [`npx prisma@latest init`](https://www.prisma.io/docs/cli/init) once. The scaffold ran it already, so on a fresh project `init` confirms the setup and reports each step as already done: the [Prisma agent skills](https://www.prisma.io/docs/ai/tools/skills) that ship inside the Prisma packages are synced, and `package.json` has a `postinstall` hook (`prisma skills sync || exit 0`) that resyncs them on every install, plus a `skills:sync` script for refreshing them by hand. Running `init` again is what repairs the setup after you upgrade a Prisma package. See [`skills`](https://www.prisma.io/docs/cli/skills). ## 2. The Composer app [#2-the-composer-app] Start with the declaration, because it is what every later command operates on. The scaffold declares the whole app in two files, and `prisma.config.ts` holds the deploy config. `module.ts` is the app: it provisions a Prisma Postgres database and the service, and wires one to the other: ```ts title="module.ts" import { module } from "@prisma/composer"; import { postgres } from "@prisma/composer-prisma-cloud/orm"; import { appContract } from "./src/prisma/composer.ts"; import app from "./service.ts"; export default module("my-app", ({ provision }) => { const database = provision( postgres({ name: "database", contract: appContract, config: "./prisma.config.ts", }), { id: "database" }, ); provision(app, { deps: { database } }); }); ``` `service.ts` declares the service itself: its name, its dependency on the database, and how it is built: ```ts title="service.ts" import node from "@prisma/composer/node"; import { compute } from "@prisma/composer-prisma-cloud"; import { postgres } from "@prisma/composer-prisma-cloud/orm"; import { appContract } from "./src/prisma/composer.ts"; export default compute({ name: "app", deps: { database: postgres(appContract), }, build: node({ module: import.meta.url, entry: "./dist/server.mjs" }), }); ``` `prisma.config.ts` is this project's Prisma config: the Prisma CLI reads it, and your app never imports it. Its `orm` section points Prisma ORM at your contract and database, its `skills` section lists the agents you chose at the prompt, and the deploy config is its `composer` section: the entry module, `./module.ts`, the extensions that deploy your app, and the store that keeps deploy state. The `composer` section already names the region the first deploy needs to create your project, `us-east-1`, so there is nothing to set before you deploy. To deploy somewhere else, change the region here before the first deploy; the region ids are listed under [Limitations](https://www.prisma.io/docs/compute/limitations). The file below is shown for Prisma schema authoring with Claude Code picked for agent skills. Your `skills` list holds the agents you picked, and TypeScript authoring points `contract` at `contract.ts` and adds an `output` path. ```ts title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; import { defineConfig as composer } from "@prisma/composer/config"; import { nodeBuild } from "@prisma/composer/node/control"; import { prismaCloud, prismaState } from "@prisma/composer-prisma-cloud/control"; export default definePrismaConfig({ skills: { agents: ["claude"], }, orm: ormConfig({ contract: "./src/prisma/contract.prisma", db: { connection: process.env.DATABASE_URL!, }, }), composer: composer({ entry: "./module.ts", extensions: [prismaCloud({ region: "us-east-1" }), nodeBuild()], state: prismaState(), }), }); ``` Notice there is no connection string in the declaration. The database is a declared dependency, typed by your contract, and Composer injects the connection wherever the app runs. The `DATABASE_URL` in the `orm` section is used only by the ORM commands that connect to a database directly, such as the `db:*` scripts at the end of [step 4](#4-run-it-locally-on-prisma-postgres); `prisma dev` and `prisma deploy` do not need it. The declaration is ordinary TypeScript: `npx tsc --noEmit` checks the wiring, and mistakes fail the compile instead of a deploy. [Composer](https://www.prisma.io/docs/composer) covers the model in full: modules, services, dependencies, and the first-party building blocks. ## 3. The Prisma ORM data model [#3-the-prisma-orm-data-model] The data side lives under `src/prisma/`. Your schema is the starter contract in `src/prisma/contract.prisma`; `npm run contract:emit` compiles it into the contract artifacts your queries are type-checked against, and `src/prisma/db.ts` is the typed client the route handlers import. The `/users` route in `src/index.ts` is ordinary Hono code calling an ordinary Prisma ORM query. Change the contract when you are ready to model your own data, re-emit it, and the compiler walks you through every query the change touches. The [fundamentals](https://www.prisma.io/docs/orm/fundamentals/reading-data) cover the query patterns. ## 4. Run it locally on Prisma Postgres [#4-run-it-locally-on-prisma-postgres] Build the server, then bring the whole declaration up on your machine: #### bun ```bash bun run build bunx prisma dev ``` #### pnpm ```bash pnpm run build pnpm prisma dev ``` #### yarn ```bash yarn build yarn prisma dev ``` #### npm ```bash npm run build npx prisma dev ``` `dev` provisions a local Prisma Postgres database, applies the contract to it, starts the service, and prints the app's local URL when everything is ready. No account, credentials, or connection string are involved; see [Local development](https://www.prisma.io/docs/local-development) for how the local platform works. Sample users are seeded automatically the first time the app queries the database. Confirm the API serves the seeded rows. `dev` keeps running until you press Ctrl-C, so run the curl in a second terminal in the same directory. `dev` picks a free port for the service, and `prisma dev url my-app.app` prints the URL of the service named `app`, whichever port it got: ```bash curl "$(npx prisma dev url my-app.app)/users" ``` ```json no-copy [ { "id": "1", "email": "alice@prisma.io", "username": "alice", "name": "Alice", "createdAt": "2026-08-24T13:51:34.797Z" }, { "id": "2", "email": "bob@prisma.io", "username": "bob", "name": "Bob", "createdAt": "2026-08-24T13:51:34.803Z" }, { "id": "3", "email": "carol@prisma.io", "username": "carol", "name": "Carol", "createdAt": "2026-08-24T13:51:34.804Z" } ] ``` If you prefer the framework's own dev server, `npm run dev` runs it directly. Composer does not manage that mode, so the app needs a database of your own in `DATABASE_URL`. Create one with the CLI, in a project named differently from the module so that it does not collide with the project the deploy in [step 5](#5-deploy-app-and-database-to-prisma-compute) creates: #### bun ```bash bunx prisma auth login bunx prisma project create my-app-local bunx prisma postgres create mydb ``` #### pnpm ```bash pnpm prisma auth login pnpm prisma project create my-app-local pnpm prisma postgres create mydb ``` #### yarn ```bash yarn prisma auth login yarn prisma project create my-app-local yarn prisma postgres create mydb ``` #### npm ```bash npx prisma auth login npx prisma project create my-app-local npx prisma postgres create mydb ``` `postgres create` prints the connection string once; export it as `DATABASE_URL`, and mint another later with `npx prisma postgres connection create mydb` if you need one. The `db:*` scripts in `package.json` initialize and verify that database. See [`postgres`](https://www.prisma.io/docs/cli/postgres). ## 5. Deploy app and database to Prisma Compute [#5-deploy-app-and-database-to-prisma-compute] Sign in once (it opens your browser): #### bun ```bash bunx prisma auth login ``` #### pnpm ```bash pnpm prisma auth login ``` #### yarn ```bash yarn prisma auth login ``` #### npm ```bash npx prisma auth login ``` Deployed databases evolve through the migrations you commit, so the first migration must create your starting schema. The scaffold already planned it for you as `migrations/app/_init`; commit it with your code. You will chain the next migration from it in [step 7](#7-evolve-the-data-model). Build and deploy the same declaration: #### bun ```bash bun run build bunx prisma deploy ``` #### pnpm ```bash pnpm run build pnpm prisma deploy ``` #### yarn ```bash yarn build yarn prisma deploy ``` #### npm ```bash npm run build npx prisma deploy ``` Composer creates a project named after your module, in the region from the `composer` section of `prisma.config.ts`, provisions the Prisma Postgres database declared in `module.ts`, connects it to the service, and starts the app. There is no environment file to pass, because the deployed database comes from the declaration exactly as the local one did. When everything is up, the deploy prints what it made, each part of your app next to the platform resource it became, along with the public URL: ```text no-copy my-app ├─ database postgres-database db_abc123 └─ app compute-service cps_abc123 https://xyz.ewr.prisma.build ``` > [!WARNING] > The module name must be unique in your workspace > > `deploy` looks the module name up in your workspace and reuses the project this module deployed before rather than creating another. If a `my-app` project exists whose hosted state the CLI cannot verify (one deployed from a different checkout, for example), the deploy stops with `HostedStateBootstrapError` and names a project id you did not choose. Deploy under a different name with [`--name`](https://www.prisma.io/docs/cli/deploy#flags), or rename the module in `module.ts`: > > > > > #### bun > ```bash > bunx prisma deploy --name my-app-tutorial > ``` > > > #### pnpm > ```bash > pnpm prisma deploy --name my-app-tutorial > ``` > > > #### yarn > ```bash > yarn prisma deploy --name my-app-tutorial > ``` > > > #### npm > ```bash > npx prisma deploy --name my-app-tutorial > ``` > > ## 6. Verify the live URL [#6-verify-the-live-url] ```bash curl https://xyz.ewr.prisma.build/users ``` The same three users come back, now served from production next to your database, seeded on the deployed app's first query. Re-deploying is safe to run more than once: build again, deploy again, and the platform applies only the difference. That includes removals, because your module is the source of truth: delete a provision from `module.ts`, deploy again, and the resource disappears from the platform. See [Removing resources](https://www.prisma.io/docs/composer/deploying#removing-resources). ## 7. Evolve the data model [#7-evolve-the-data-model] Live apps outgrow their starter schema, so give users a role. Add one line to the contract: ```prisma title="src/prisma/contract.prisma" // use prisma-8 model User { id Int @id @default(autoincrement()) email String @unique username String? name String? role String @default("member") posts Post[] createdAt TimestamptzString @default(now()) updatedAt DateTime(as: string) @onCreate(now()) @onUpdate(now()) } ``` Re-emit the contract, then plan the migration that carries the change, chaining from the baseline migration you committed in [step 5](#5-deploy-app-and-database-to-prisma-compute): #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add-user-role --from _init ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add-user-role --from _init ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add-user-role --from _init ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add-user-role --from _init ``` `--from` names the migration you are building on, and here it is required: a Composer deploy never sets the `db` ref that `migration plan` chains from by default, so a plan without it would describe every table again. The [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) and [`migration ref`](https://www.prisma.io/docs/cli/migration-ref) references cover the default, the ref, and how to keep plans chaining on their own. The plan is your change and nothing else. Review it like any other diff, with [`migration show`](https://www.prisma.io/docs/cli/migration-show) or by reading the generated package: ```text no-copy ALTER TABLE "public"."User" ADD COLUMN "role" text DEFAULT 'member' NOT NULL ``` Emitting also updated the query types, so include the new field in the route's typed select in `src/prisma/users.ts`, adding `"role"` to the `.select(...)` list and `role: user.role` to the returned object: ```ts title="src/prisma/users.ts" const users = await db.orm.public.User.select("id", "email", "username", "name", "role", "createdAt").limit(limit).all(); ``` This is the Prisma ORM loop: the contract is the source of truth, the emit step regenerates the types, and the compiler points at every query the change touches. If you want to see the change on your machine first, run `npm run build` and `npx prisma dev` again; the local database applies the new migration on start and `/users` returns the role there too. Then build and deploy again: #### bun ```bash bun run build bunx prisma deploy ``` #### pnpm ```bash pnpm run build pnpm prisma deploy ``` #### yarn ```bash yarn build yarn prisma deploy ``` #### npm ```bash npm run build npx prisma deploy ``` The deploy applies the committed migration to the deployed database in place. The same users come back with `role: "member"`, backfilled by the column default, and their `createdAt` timestamps unchanged; nothing was dropped or recreated: ```bash curl https://xyz.ewr.prisma.build/users ``` ```json no-copy [ { "id": "1", "email": "alice@prisma.io", "username": "alice", "name": "Alice", "role": "member", "createdAt": "2026-08-24T18:40:06.375Z" } ] ``` ## 8. Clean up (optional) [#8-clean-up-optional] The project keeps running until you remove it. Deleting it removes the service and the database, so the command asks you to repeat the project id (find it with `npx prisma project list`): #### bun ```bash bunx prisma project delete --confirm ``` #### pnpm ```bash pnpm prisma project delete --confirm ``` #### yarn ```bash yarn prisma project delete --confirm ``` #### npm ```bash npx prisma project delete --confirm ``` ## Next steps [#next-steps] * [Learn Composer](https://www.prisma.io/docs/composer/getting-started): typed contracts between services, databases, storage, and scheduled jobs. * [Pick your framework](https://www.prisma.io/docs/guides): the same journey for Next.js, Nuxt, Astro, NestJS, TanStack Start, and more. * [Environments](https://www.prisma.io/docs/compute/branching): how each branch gets its own isolated environment. * [Learn the fundamentals](https://www.prisma.io/docs/orm/fundamentals/reading-data): reading, writing, relations, and transactions. * [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push): connect GitHub and add a deploy workflow so a push to the default branch deploys production and a push to any other branch deploys a preview environment for it. ## Related pages - [`Choose a Prisma ORM setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to try Prisma ORM in a new or existing project. - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Introduction to Prisma ORM`](https://www.prisma.io/docs/prisma-orm): Prisma ORM 8 is a release candidate. - [`Local development`](https://www.prisma.io/docs/local-development): Run the whole Prisma stack on your machine, with your app on Bun, a local Prisma Postgres database, and local object storage. - [`Overview`](https://www.prisma.io/docs/cli): Prisma CLI reference # Choose a Prisma ORM setup path (/docs/getting-started) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Choose the fastest path to try Prisma ORM in a new or existing project. Location: Choose a Prisma ORM setup path Start with a quickstart if you want [Prisma ORM](https://www.prisma.io/docs/orm) to create the app. Use the existing-project path if you already have an app and database. Coming from an earlier version? [Coming from Prisma ORM 7](https://www.prisma.io/docs/orm/coming-from-prisma-orm-7) maps every Prisma ORM 7 API to its Prisma ORM 8 form, and [Release status](https://www.prisma.io/docs/orm/release-status) says where Prisma ORM 8 stands today. ## Prerequisites [#prerequisites] * **Node.js 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer.** Check with `node --version`. Node.js 24 is recommended. The Nuxt template needs 22.22.3 or newer on the 22 line, or 24.15 or newer on the 24 line, because Nuxt requires it. * **A package manager.** The npm that ships with your Node.js release works; on Node.js 22 that is npm 10. pnpm, Bun, and Yarn 4.10 or newer are also supported. ## Start a new project [#start-a-new-project] #### bun ```bash bun create prisma@latest ``` #### pnpm ```bash pnpm create prisma@latest ``` #### yarn ```bash yarn create prisma@latest ``` #### npm ```bash npm create prisma@latest ``` The [create-prisma reference](https://www.prisma.io/docs/prisma-orm/create-prisma) lists every template and flag. - [Start a TypeScript app with Postgres on Prisma for free](https://www.prisma.io/docs/full-stack-tutorial): The whole journey in one sitting: scaffold, Prisma Postgres, first query, and a Prisma Compute deploy. - [Create a new app with PostgreSQL](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql): Create the app, run it against a local Prisma Postgres from Composer or your own PostgreSQL, and run the first query. - [Create a new app with MongoDB](https://www.prisma.io/docs/prisma-orm/quickstart/mongodb): Create the app, connect a MongoDB deployment, apply the first migration, and run the first query. ## Add to an existing project [#add-to-an-existing-project] #### bun ```bash bunx prisma@latest orm init ``` #### pnpm ```bash pnpm dlx prisma@latest orm init ``` #### yarn ```bash yarn dlx prisma@latest orm init ``` #### npm ```bash npx prisma@latest orm init ``` - [Add to PostgreSQL](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql): Add Prisma ORM to an existing PostgreSQL app and infer a starter contract from the live schema. - [Add to MongoDB](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/mongodb): Add Prisma ORM 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-8.md` or the installed Prisma ORM 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 ORM overview](https://www.prisma.io/docs/orm) when you want the concepts behind the setup. ## Use with your agent [#use-with-your-agent] You can hand either setup path to your coding agent. Copy the prompt that matches your project and give it to your agent. Both prompts use PostgreSQL. To create a new app, use this prompt: ```text Create a new [framework] application with Prisma ORM, seed it, and run it locally. If I have not told you which framework, stop and ask before scaffolding. Valid --template values: minimal (the default), next, hono, nuxt, astro, nest, svelte, tanstack-start, elysia. Check the Node.js version first: `node --version` must print 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer. For the nuxt template, it must print 22.22.3 or newer on the 22 line, 24.15 or newer on the 24 line, or 26 or newer, because Nuxt requires it. The npm that ships with your Node.js release works; on Node.js 22 that is npm 10. 1. Scaffold the app: `npm create prisma@latest -- my-app --template [framework] --provider postgres --yes`. 2. Get a database connection string: use the one I give you, or create a Prisma Postgres database with `npx create-db@latest` and show me the claim URL it prints. Export it as `DATABASE_URL` in the shell; the generated scripts read the environment variable, not `.env`. 3. From the project directory, apply the starter contract: `npm run db:init`. Sample users are seeded automatically on the app's first query; there is no separate seed script. 4. Edit the starter contract under `src/prisma/` into a small schema for my use case, then run `npm run contract:emit` and plan and apply the migration: `npx prisma migration plan`, then `npx prisma db migrate --yes`. Migration planning diffs the emitted contract, so the emit step is required. 5. Update the seed script under `src/prisma/` and the app routes to query the new schema, start `npm run dev` in the background (with `DATABASE_URL` exported), and verify with a request against the running app. For the `nest` template, if routes return 500s with `reading 'findAll'` in the logs, add explicit `@Inject()` tokens as shown in https://www.prisma.io/docs/guides/frameworks/nestjs.md. Use the installed Prisma ORM skills and the current Prisma docs: https://www.prisma.io/docs/llms.txt (append `.md` to any docs URL for a markdown version). ``` To add Prisma ORM to an app you already have, use this prompt: ```text Add Prisma ORM to this existing project. This flow is for PostgreSQL. If the project uses MongoDB, follow https://www.prisma.io/docs/prisma-orm/add-to-existing-project/mongodb.md instead; for other databases, stop and tell me. 1. Run `npx prisma@latest orm init --yes --target postgres --authoring psl` (the flags are required when the CLI cannot prompt). It writes `prisma.config.ts`, a starter contract and `db.ts` under `src/prisma/`, and installs dependencies. Then run `npx prisma skills sync` to install the Prisma ORM skills. 2. Set `DATABASE_URL` in `.env` to my database. If I did not give you one, create a Prisma Postgres database with `npx create-db@latest`, put its connection string in `.env`, and show me the claim URL it prints so I can keep the database (claiming needs a free Prisma account). 3. If the database already has tables, infer the contract from it: `npx prisma contract infer`, then `npx prisma contract emit`, then sign it with `npx prisma db sign`. If the database is empty, keep the starter contract and run `npx prisma db init`. 4. Write one query with the generated `db` client in an existing code path, run it, and show me the returned rows. Follow https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql.md and the installed Prisma ORM skills. ``` ## Related pages - [`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 ORM`](https://www.prisma.io/docs/prisma-orm): Prisma ORM 8 is a release candidate. - [`Local development`](https://www.prisma.io/docs/local-development): Run the whole Prisma stack on your machine, with your app on Bun, a local Prisma Postgres database, and local object storage. - [`Overview`](https://www.prisma.io/docs/cli): Prisma CLI reference - [`Overview`](https://www.prisma.io/docs/guides): Practical, step-by-step guides for building with Prisma ORM and deploying to Prisma Compute, each one run end to end before it ships. # Get started with Prisma (/docs) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. **Build** your TypeScript app and run all of it locally, then **deploy** it to the Prisma platform with one command. New here? Follow the [full-stack tutorial](https://www.prisma.io/docs/full-stack-tutorial). ## Build Define your app in TypeScript and run it locally. - **[Local development](https://www.prisma.io/docs/local-development)**: Run your whole app on your machine with local Postgres and storage. No cloud credentials needed. - **[Composer](https://www.prisma.io/docs/composer)**: Declare your services and what they need: databases, jobs, buckets, secrets. - **[ORM](https://www.prisma.io/docs/orm)**: Model your data and query it with type safety, end to end. ## Deploy One command provisions and connects everything. - **[Compute](https://www.prisma.io/docs/compute)**: Hosts your Node.js, Bun or Next.js services next to your database, with isolated previews per branch. - **[Storage](https://www.prisma.io/docs/storage)**: S3-compatible buckets in your Prisma project. Use any S3 client, with keys scoped to one bucket. - **[Postgres](https://www.prisma.io/docs/postgres)**: Managed PostgreSQL 17 with built-in connection pooling. Scales automatically, no instance to size. **Deploy with one command** ```bash npx prisma deploy ``` Ships everything your app declares to production. Use `--environment` for an isolated copy. See the [Deploy guide](https://www.prisma.io/docs/prisma-compute/deploy). ## Prisma ORM Use Prisma ORM on its own, with your own PostgreSQL or MongoDB database. Pick where you're starting from; each guide links its MongoDB version. - [I'm creating a new app](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql): Start from a template - [I have an app, no database yet](https://www.prisma.io/docs/prisma-orm/quickstart/existing-app/postgresql): Add Prisma ORM, then create the tables - [I have a database already](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql): Start from the tables you have - [I have a Prisma 6 or 7 app](https://www.prisma.io/docs/guides/upgrade-prisma-orm): Upgrade to Prisma 8 ## Pick your framework Each guide covers the same steps: scaffold, connect Prisma Postgres, run a query, deploy. SvelteKit and Deno stop at a local run for now. - [Next.js](https://www.prisma.io/docs/guides/frameworks/nextjs) - [Hono](https://www.prisma.io/docs/guides/frameworks/hono) - [TanStack Start](https://www.prisma.io/docs/guides/frameworks/tanstack-start) - [NestJS](https://www.prisma.io/docs/guides/frameworks/nestjs) - [Astro](https://www.prisma.io/docs/guides/frameworks/astro) - [Nuxt](https://www.prisma.io/docs/guides/frameworks/nuxt) - [SvelteKit](https://www.prisma.io/docs/guides/frameworks/sveltekit) - [Bun](https://www.prisma.io/docs/guides/runtimes/bun) - [Elysia](https://www.prisma.io/docs/guides/frameworks/elysia) - [Deno](https://www.prisma.io/docs/guides/runtimes/deno) Using Express or another Node.js server? Choose a [Prisma ORM setup path](https://www.prisma.io/docs/getting-started). ## Prisma ORM 7 Still fully supported, with Prisma Postgres and Compute. Prisma ORM 8 is the upgrade path. - **New project:** `npx create-prisma@stable` ([5-min quickstart](https://www.prisma.io/docs/v7/prisma-orm/quickstart/prisma-postgres)) - **Existing project:** `npx prisma@prev init` ([Setup paths](https://www.prisma.io/docs/v7/getting-started)) ## Other setups Each path has a guide, and a prompt you can hand to your agent. **Existing project** Add Prisma ORM to the app you already have, on its PostgreSQL database. With no database yet, the prompt creates a Prisma Postgres one. Using MongoDB? [Add Prisma ORM to a MongoDB app](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/mongodb). ```text Add Prisma ORM to this existing project. This flow is for PostgreSQL. If the project uses MongoDB, follow https://www.prisma.io/docs/prisma-orm/add-to-existing-project/mongodb.md instead; for other databases, stop and tell me. 1. Run `npx prisma@latest orm init --yes --target postgres --authoring psl` (the flags are required when the CLI cannot prompt). It writes `prisma.config.ts`, a starter contract and `db.ts` under `src/prisma/`, and installs dependencies. Then run `npx prisma skills sync` to install the Prisma ORM skills. 2. Set `DATABASE_URL` in `.env` to my database. If I did not give you one, create a Prisma Postgres database with `npx create-db@latest`, put its connection string in `.env`, and show me the claim URL it prints so I can keep the database (claiming needs a free Prisma account). 3. If the database already has tables, infer the contract from it: `npx prisma contract infer`, then `npx prisma contract emit`, then sign it with `npx prisma db sign`. If the database is empty, keep the starter contract and run `npx prisma db init`. 4. Write one query with the generated `db` client in an existing code path, run it, and show me the returned rows. Follow https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql.md and the installed Prisma ORM skills. ``` Follow the guide: [PostgreSQL guide](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql) **Your own PostgreSQL** Start a new app with Prisma ORM against a PostgreSQL database you already run. Nothing hosted is provisioned. Using MongoDB? Follow the [MongoDB quickstart](https://www.prisma.io/docs/prisma-orm/quickstart/mongodb). ```text Create a new [framework] application with Prisma ORM against my existing PostgreSQL database. If I have not given you a connection string, stop and ask; do not invent one. Valid --template values: minimal (the default), next, hono, nuxt, astro, nest, svelte, tanstack-start, elysia. Check the Node.js version first: `node --version` must print 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer. For the nuxt template, it must print 22.22.3 or newer on the 22 line, 24.15 or newer on the 24 line, or 26 or newer, because Nuxt requires it. The npm that ships with your Node.js release works; on Node.js 22 that is npm 10. 1. Scaffold: `npm create prisma@latest -- my-app --template [framework] --provider postgres --yes`. 2. Export my connection string as `DATABASE_URL` in the shell; the generated scripts read the environment variable, not `.env`. From the project directory: `npm run db:init`, then start `npm run dev` in the background and verify the sample query returns data. Sample users are seeded automatically on the app's first query; there is no separate seed script. 3. Evolve the starter contract under `src/prisma/` into my schema, then run `npm run contract:emit`, `npx prisma migration plan`, and `npx prisma db migrate --yes`. Do not provision any hosted database. Use the installed Prisma ORM skills and https://www.prisma.io/docs/llms.txt for current docs. ``` Follow the guide: [Quickstart](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql) **Postgres only** Create a Prisma Postgres database with `npx create-db`, no account needed, and use it from the ORM or query builder you already have. Using Kysely, Drizzle, or TypeORM? Each has its own quickstart: [Kysely](https://www.prisma.io/docs/prisma-postgres/quickstart/kysely), [Drizzle](https://www.prisma.io/docs/prisma-postgres/quickstart/drizzle-orm), [TypeORM](https://www.prisma.io/docs/prisma-postgres/quickstart/typeorm). ```text Create a Prisma Postgres database for this project. 1. Run `npx create-db@latest`. It creates a temporary Prisma Postgres database without an account and prints a connection string plus a claim URL. 2. Put the connection string in `.env` as DATABASE_URL and wire it into whichever of Prisma ORM, Kysely, Drizzle, TypeORM, or node-postgres the project already uses (detect it from package.json; if none, ask me). Verify the connection with one trivial query such as `select 1`. 3. Remind me to open the claim URL to keep the database in my Prisma workspace (claiming needs a free Prisma account). Current docs: https://www.prisma.io/docs/postgres.md. ``` Follow the guide: [create-db guide](https://www.prisma.io/docs/postgres/npx-create-db) **Compute only** Deploy an app you already have to Prisma Compute: declare it with Composer, check it locally, then run `npx prisma deploy`. ```text Deploy this app to Prisma Compute using `npx prisma@latest`. Compute runs apps declared with Prisma Composer: your server code plus a small TypeScript declaration. Port the app following https://www.prisma.io/docs/composer/porting-an-app.md. SvelteKit and Deno are not supported yet; if the app is one of those, stop and tell me. 1. Install `@prisma/composer` and `@prisma/composer-prisma-cloud`, and install `prisma` as a dev dependency. Do not pin `effect`: Composer pins it. Only if another dependency pins a different `effect` and `prisma.config.ts` fails with `CLI.CONFIG_UNREADABLE`, add the override from https://www.prisma.io/docs/composer/deploying#when-prismaconfigts-fails-on-an-effect-version-conflict. Then install the Composer skill with `npx prisma skills sync`, and use it. 2. Declare the app: a `service.ts` with `compute({ name, deps, build })`, a `module.ts` that provisions it, and a `prisma.config.ts` whose `composer` section names `module.ts` as the `entry` and lists the extensions and the state store (`definePrismaConfig` from `prisma/config`, `defineConfig as composer` from `@prisma/composer/config`). Read the port from `service.port()` and bind 0.0.0.0. Replace other `process.env` reads with the service input schema, binding credentials like DATABASE_URL with `envSecret`. Composer does not build: produce one self-contained entry file per service (for example `esbuild --bundle --platform=node --format=esm --outfile=dist/server.mjs`), or use the framework build adapter (Next.js needs the `nextjs` adapter and `output: "standalone"`). 3. Verify locally: run the build, then `npx prisma dev --detach`, curl each service at the URL `npx prisma dev url .` prints, then run `npx prisma dev stop`. 4. Confirm I am signed in with `npx prisma auth whoami`; if not, stop and ask me to run `npx prisma auth login` (it opens a browser). 5. Deploy: run the build, then `npx prisma deploy` with the app's env values (like DATABASE_URL) exported in the shell; the first deploy copies input values up to the deployment. Verify the printed public URL with curl. Current docs: https://www.prisma.io/docs/composer/porting-an-app.md and https://www.prisma.io/docs/prisma-compute/deploy.md. ``` Follow the guide: [Deploy guide](https://www.prisma.io/docs/prisma-compute/deploy) ## Browse the docs The full docs for each product, and the references you'll come back to. - [Prisma ORM](https://www.prisma.io/docs/orm): Prisma ORM 8 and 7 docs - [Prisma Postgres](https://www.prisma.io/docs/postgres): The managed database - [Prisma Compute](https://www.prisma.io/docs/compute): Hosting and previews - [CLI reference](https://www.prisma.io/docs/cli): Every command and flag - [Guides](https://www.prisma.io/docs/guides): Frameworks and workflows - [AI tools](https://www.prisma.io/docs/ai): Skills, MCP, and prompts # Prisma with AI coding tools (/docs/ai) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Use Prisma with AI coding tools like Cursor, Codex, and ChatGPT Location: Prisma with AI coding tools Prisma ORM and Prisma Postgres work with AI coding agents through installable skills, an MCP server, and editor integrations. This page collects the setup guides, prompts, and tutorials for using them together. ## Get started [#get-started] Run the following command to bootstrap your database with a prompt: #### bun ```bash bunx --bun prisma@prev init --prompt "Create a habit tracker application" ``` #### pnpm ```bash pnpm dlx prisma@prev init --prompt "Create a habit tracker application" ``` #### yarn ```bash yarn dlx prisma@prev init --prompt "Create a habit tracker application" ``` #### npm ```bash npx prisma@prev init --prompt "Create a habit tracker application" ``` ## AI Coding Tools [#ai-coding-tools] Each guide covers setup and prompts for using Prisma in a specific AI editor or agent. * [Cursor](https://www.prisma.io/docs/ai/tools/cursor) - Define project-specific rules and use your schema as context to generate accurate queries and code. * [Codex](https://www.prisma.io/docs/ai/tools/codex) - Install the Prisma Codex plugin with Prisma ORM skills and the remote Prisma MCP server. * [Windsurf](https://www.prisma.io/docs/ai/tools/windsurf) - Automate your database workflows by generating schemas, queries, and seed data in this AI-powered editor. * [Github Copilot](https://www.prisma.io/docs/ai/tools/github-copilot) - Get Prisma-aware code suggestions, run CLI commands from chat, and query the Prisma docs. * [ChatGPT](https://www.prisma.io/docs/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](https://www.prisma.io/docs/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 create Prisma Postgres databases, run SQL queries, restore automated backups, and manage Object Storage. It can also manage Prisma Compute deployments, read app logs, set environment variables, and inspect how your [Composer](https://www.prisma.io/docs/composer) services connect. ```json title="Integrate in AI tool" { "mcpServers": { "Prisma": { "url": "https://mcp.prisma.io/mcp" } } } ``` * [Available tools](https://www.prisma.io/docs/ai/mcp-tools) - The full list of tools the Prisma MCP server exposes. * [Integrating in AI tools](https://www.prisma.io/docs/ai/tools/mcp-server#integrating-in-ai-tools) - Configuration for Cursor, Claude, Warp, and other AI tools. * [How we built it](https://www.prisma.io/blog/about-mcp-servers-and-how-we-built-one-for-prisma) - How the MCP protocol works and how the Prisma MCP server was built. ## Vibe Coding Tutorials [#vibe-coding-tutorials] Tutorials that build a full application from scratch with an AI coding assistant. * [Build a Linktree Clone SaaS](https://www.prisma.io/docs/ai/tutorials/linktree-clone) - Build a 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](https://www.prisma.io/docs/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 in automated workflows * [Firebase Studio](https://www.prisma.io/docs/guides/postgres/idx) - Prompt your application with Firebase Studio & Prisma Postgres ## Related pages - [`Choose a Prisma ORM setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to try Prisma ORM in a new or existing project. - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Introduction to Prisma ORM`](https://www.prisma.io/docs/prisma-orm): Prisma ORM 8 is a release candidate. - [`Local development`](https://www.prisma.io/docs/local-development): Run the whole Prisma stack on your machine, with your app on Bun, a local Prisma Postgres database, and local object storage. - [`Overview`](https://www.prisma.io/docs/cli): Prisma CLI reference # MCP tools (/docs/ai/mcp-tools) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Available Prisma MCP tools for databases, Compute deployments, Object Storage, and Composer projects. Location: AI > MCP tools These tools are available through the [Prisma MCP server](https://www.prisma.io/docs/ai/tools/mcp-server) in your selected workspace. Your AI client lists each tool's input parameters when it connects. > [!WARNING] > Tools that change or delete resources can cause data loss or interrupt live traffic. Check the target workspace and resources before approving an operation in your AI tool. ## Workspace and databases [#workspace-and-databases] * `fetch_workspace_details`: Fetch the details of a Prisma Postgres workspace. * `list_prisma_postgres_databases`: Fetch a list of available Prisma Postgres databases for the user's workspace. * `create_prisma_postgres_database`: Create a managed Prisma Postgres database and a new project. * `delete_prisma_postgres_database`: Permanently delete a Prisma Postgres database by ID. This tool cannot delete a project's default database. ## Connection strings [#connection-strings] * `list_prisma_postgres_connection_strings`: Fetch a list of available connection strings for the given database id. * `create_prisma_postgres_connection_string`: Create a new connection string for a Prisma Postgres database with the given id. * `delete_prisma_postgres_connection_string`: Delete a connection string with the given connection string id. ## Backups and recovery [#backups-and-recovery] * `list_prisma_postgres_backups`: List available automated backups for a Prisma Postgres database. * `create_prisma_postgres_recovery`: Restore a Prisma Postgres database to a new database with the given backup id. ## Schema and queries [#schema-and-queries] * `introspect_database_schema`: Read the schema of a Prisma Postgres database to show its structure. * `execute_sql_query`: Run SQL to read, modify, or delete data in a Prisma Postgres database, without changing its schema. * `execute_prisma_postgres_schema_update`: Execute a schema update on a Prisma Postgres database with the given id. ## Object Storage [#object-storage] * `list_object_store_buckets`: List object-store buckets in the workspace, optionally filtered by project id. * `create_object_store_bucket`: Create a new object-store bucket in the given project. * `delete_object_store_bucket`: Permanently delete an object-store bucket, all objects stored in it, and all its access keys. * `create_object_store_bucket_key`: Create an S3-compatible access key for an object-store bucket. * `delete_object_store_bucket_key`: Delete an object-store bucket access key. The key stops working immediately. ## Documentation [#documentation] * `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. ## Compute apps and builds [#compute-apps-and-builds] * `list_prisma_compute_apps`: List Prisma Compute apps in the selected workspace, optionally filtered by project. * `list_prisma_compute_builds`: List builds, newest first, with optional project, branch, and state filters. * `list_prisma_compute_deployments`: List deployments for a Prisma Compute app, newest first. * `get_prisma_compute_deployment_logs`: Read runtime logs for a deployment, one page at a time. ## Compute deployment management [#compute-deployment-management] * `promote_prisma_compute_deployment`: Make a running deployment the live version of an app. * `rollback_prisma_compute_app`: Make an existing deployment live, starting it first if it is stopped. * `start_prisma_compute_deployment`: Start an existing deployment from an already uploaded build. This tool does not build or upload the app. * `stop_prisma_compute_deployment`: Stop a deployment, disconnecting it from the app's public URL if it is the live version. * `delete_prisma_compute_deployment`: Permanently delete a deployment, stopping it first if needed. * `delete_prisma_compute_app`: Permanently delete an app. To stop and delete its deployments too, set `deleteDeployments` to true; otherwise, active deployments block deletion. ## Compute environment variables [#compute-environment-variables] * `set_prisma_compute_env_var`: Set an environment variable for a project's production or preview environment, or override it for one preview branch. Values are encrypted and never returned. * `delete_prisma_compute_env_var`: Permanently delete an environment variable by ID. ## Composer projects [#composer-projects] [Composer](https://www.prisma.io/docs/composer) defines your application's services, databases, and other resources in TypeScript. * `get_prisma_composer_topology`: Show the saved connections between a project's Composer services and resources, with Console links and stored app URLs. The result may be out of date and does not check whether apps are running. The Compute tools manage existing apps and deployments; they do not build or upload your source code. To deploy a new app, follow the [Prisma Compute guide](https://www.prisma.io/docs/compute). # auth (/docs/cli/auth) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. Location: CLI > auth Use `auth` commands to manage authentication for the platform commands. Signing in opens a browser flow and stores a session. Every platform command in that environment reuses that session. ## Usage [#usage] #### bun ```bash bunx prisma auth login bunx prisma auth whoami ``` #### pnpm ```bash pnpm prisma auth login pnpm prisma auth whoami ``` #### yarn ```bash yarn prisma auth login yarn prisma auth whoami ``` #### npm ```bash npx prisma auth login npx prisma auth whoami ``` ## Commands [#commands] | 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 | | `auth workspace list` | List your workspace sessions | | `auth workspace use [id-or-name]` | Make one of your workspace sessions current | | `auth workspace logout ` | End one workspace session | `auth login` signs you in through the browser. Afterward, anything running in that environment inherits the session, including coding agents. For CI, set [`PRISMA_SERVICE_TOKEN`](https://www.prisma.io/docs/cli/environment-variables) instead. ## Related pages - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. - [`contract infer`](https://www.prisma.io/docs/cli/contract-infer): Infer a starter contract from an existing database. # branch (/docs/cli/branch) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. List platform branches for a project. Location: CLI > branch Use `branch` commands to inspect the platform branches of a project. The commands do not create anything on the platform. See [Environments](https://www.prisma.io/docs/compute/branching) for how platform branches work. ## Usage [#usage] #### bun ```bash bunx prisma branch list ``` #### pnpm ```bash pnpm prisma branch list ``` #### yarn ```bash yarn prisma branch list ``` #### npm ```bash npx prisma branch list ``` ## Commands [#commands] | Command | Description | | ------------- | --------------------------------------------- | | `branch list` | List platform branches for the linked project | ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. - [`contract infer`](https://www.prisma.io/docs/cli/contract-infer): Infer a starter contract from an existing database. # bucket (/docs/cli/bucket) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Create and manage object-store buckets. Location: CLI > bucket Use `bucket` commands to manage object-store buckets in a project. ## Usage [#usage] #### bun ```bash bunx prisma bucket list bunx prisma bucket create --name my-bucket ``` #### pnpm ```bash pnpm prisma bucket list pnpm prisma bucket create --name my-bucket ``` #### yarn ```bash yarn prisma bucket list yarn prisma bucket create --name my-bucket ``` #### npm ```bash npx prisma bucket list npx prisma bucket create --name my-bucket ``` ## Commands [#commands] | Command | Description | | ---------------------------------------- | ------------------------------------------------------------------------------------------------ | | `bucket list` | List object-store buckets | | `bucket create` | Create an object-store bucket (`--name ` sets the display name, auto-generated if omitted) | | `bucket delete ` | Delete a bucket and all its access keys | | `bucket key list ` | List access keys for a bucket | | `bucket key create ` | Create a bucket access key and print its one-time credentials | | `bucket key delete ` | Revoke and delete a bucket access key | ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. - [`contract infer`](https://www.prisma.io/docs/cli/contract-infer): Infer a starter contract from an existing database. # Configuration (/docs/cli/configuration) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Configure Prisma ORM CLI commands with prisma.config.ts and global flags. Location: CLI > Configuration Prisma ORM CLI commands read `prisma.config.ts`, starting in the directory you run them from. The file has one section per part of the CLI. The `orm` section holds your schema, database, and migration settings, which the `contract`, `db`, and `migration` commands read. The `skills` section holds the settings for the [agent skills commands](https://www.prisma.io/docs/cli/skills), which copy Prisma's instructions for AI coding agents into your project. The `composer` section holds [Prisma Composer](https://www.prisma.io/docs/composer)'s deploy config, the entry module, the extensions and the deploy-state store that [`deploy`](https://www.prisma.io/docs/cli/deploy) and [`dev`](https://www.prisma.io/docs/cli/dev) read; [Composer getting started](https://www.prisma.io/docs/composer/getting-started) shows how to write it. ## Config file [#config-file] The outer `definePrismaConfig` comes from `prisma/config` and marks the file as a Prisma ORM 8 CLI config. A Prisma ORM 7 `prisma.config.ts` without that marker is rejected rather than misread. The import resolves from your project's `node_modules`, so `prisma` must be a local dependency. The `orm` section uses the config helper for your database. For PostgreSQL: ```typescript title="prisma.config.ts" import "dotenv/config"; import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ contract: "./prisma/contract.prisma", db: { connection: process.env["DATABASE_URL"]!, }, }), }); ``` For MongoDB projects, import the section helper from `@prisma/orm-mongo/config` instead. Both packages export this helper as `defineConfig`, and the examples on this page rename it to `ormConfig` when they import it. This paragraph is only for a config written for a Prisma ORM 8 release candidate before `8.0.0-rc.12`. Such a config may import `defineConfig` from `@prisma/cli-engine`. That import no longer exists, so the config fails to load. Replace it with `definePrismaConfig` from `prisma/config`, and rename the call to match: it is the same function under its new name. Leave the `defineConfig` import from `@prisma/orm-postgres/config` or `@prisma/orm-mongo/config` as it is. That one is the helper for the `orm` section, and its name has not changed. [`orm init`](https://www.prisma.io/docs/cli/orm-init) writes this file for you. Without `--config`, the CLI looks for `prisma.config.ts` in the directory you run the command from and in the directories above it, as [How the CLI finds the config](#how-the-cli-finds-the-config) explains. Pass `--config` to use a config file in another place, such as a subdirectory: #### bun ```bash bunx prisma contract emit --config ./config/prisma.config.ts ``` #### pnpm ```bash pnpm prisma contract emit --config ./config/prisma.config.ts ``` #### yarn ```bash yarn prisma contract emit --config ./config/prisma.config.ts ``` #### npm ```bash npx prisma contract emit --config ./config/prisma.config.ts ``` ## How the CLI finds the config [#how-the-cli-finds-the-config] The CLI starts with `prisma.config.ts` in the current directory, or with the file you pass to `--config`. It then also reads the `prisma.config.ts` in each parent directory that has one, up to the root of the repository, which is the first directory that has a `.git` entry. If neither the starting directory nor any directory above it has a `.git` entry, the CLI reads only the file it started with. The CLI combines the files it finds one section at a time. Inside a section such as `orm`, it takes each top-level key, such as `contract`, `db`, or `migrations`, from the nearest file that sets it, and it takes the whole value of that key from that one file. So if a config higher up sets `db.connection` and your project's config sets only `contract`, the CLI uses your `contract` and the other file's `db`. The `composer` section is not combined this way. The CLI takes it whole from the nearest file that declares a `composer` section and ignores the `composer` sections of files higher up. Extensions are the exception: if your project config has its own `orm` section, it never inherits `extensions` from a config higher up, even when it lists none. List the extensions your contract uses, as [Extension packs](#extension-packs) shows, in each project's own config. > [!WARNING] > More than one project in a repository > > If a `prisma.config.ts` higher up sets `db` or `migrations`, a project config that leaves them out uses that file's database and migrations folder. `db update`, `db migrate` and `db verify` then connect to the other project's database, and `migration plan` writes into the other project's migrations folder, without a warning. Set `db` and `migrations`, such as `migrations: { dir: "./migrations" }`, in every project's own config, or add `parent: false` to it. To stop a project's config from inheriting anything, add `parent: false` to it. The search then ends at that file: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ parent: false, orm: ormConfig({ contract: "./prisma/contract.prisma", }), }); ``` `parent` can also be a path to another config file, which the CLI reads next in place of the one in the parent directory. The path is relative to the directory of the config file that sets it, and it may point outside the repository. After reading that file, the CLI goes on to search the directories above that file in the usual way, unless that file sets `parent` too: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ parent: "../shared/prisma.config.ts", orm: ormConfig({ contract: "./prisma/contract.prisma", }), }); ``` A relative path in a config file, such as `contract`, `output`, or `migrations.dir`, resolves from the directory of the config file that sets it, not from the directory you run the command in. So `--config ./config/prisma.config.ts` with `contract: "./prisma/contract.prisma"` reads `./config/prisma/contract.prisma`. ## Split the schema across several files [#split-the-schema-across-several-files] `contract` accepts a glob, a path pattern where `*` matches any file name and `**` matches any number of folders, so one schema can span several `.prisma` files: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ contract: "./prisma/**/*.prisma", }), }); ``` `contract emit` builds one contract from every matched file whose first line is `// use prisma-8`. The same rule applies when `contract` names a single file: that file must start with the line too. `contract emit` skips a matched file without that line and does not warn, so the line is what makes a file part of the schema. The Prisma editor extension uses the same rule, so the editor and `contract emit` agree on which files make up the schema. If the glob matches files but none of them starts with the line, `contract emit` fails with `CONTRACT.SOURCE_LOAD_FAILED`, and the error's details name the problem `PSL_NO_OPTED_IN_SCHEMA_FILES`. If the glob matches no file at all, for example because of a typo in the pattern, they name it `PSL_NO_SCHEMA_FILES_MATCHED` instead. [What `contract emit` creates](https://www.prisma.io/docs/cli/contract-emit#what-it-creates) says where these details appear in the output. A new file joins the schema the next time you run `contract emit`, with no change to the config. The emitted files go in the folder before the first wildcard, here `./prisma/contract.json` and `./prisma/contract.d.ts`. ## Use a Prisma ORM 7 schema [#use-a-prisma-orm-7-schema] On PostgreSQL, Prisma ORM 8 can read a Prisma ORM 7 `schema.prisma` directly as its contract source, so the two versions can run side by side on the database that Prisma ORM 7 migrates. Wrap the path in `prisma7Schema`: ```typescript title="prisma.config.ts" import "dotenv/config"; import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig, prisma7Schema } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ contract: prisma7Schema("prisma/schema.prisma"), db: { connection: process.env["DATABASE_URL"]!, }, }), }); ``` `prisma7Schema` takes one schema file, or a directory of `.prisma` files as Prisma ORM 7 reads it. `prisma7Schema` reads every `.prisma` file it is given, so these files do not need the `// use prisma-8` first line. `contract emit` writes `contract.json` and `contract.d.ts` into the directory that holds the schema, here `prisma/`, unless you set `output`. Prisma ORM 7 keeps owning the database and its migrations, and you run its commands as `prisma7`, the Prisma ORM 7 CLI that [`orm init --from-prisma7-schema`](https://www.prisma.io/docs/cli/orm-init#on-a-prisma-orm-7-project) installs next to Prisma ORM 8. `orm init --from-prisma7-schema` also writes this config for you. With `prisma7Schema`, each date and time field keeps its column and reads as the type below: | Prisma ORM 7 field | Prisma ORM 8 type | Your code reads | | -------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------- | | `DateTime` | `TimestampJsDate(3)`, printed `DateTime(storage: timestamp)` | a JavaScript `Date`, the stored value read as UTC, as Prisma ORM 7 did | | `@db.Timestamptz(p)` | `TimestamptzJsDate(p)`, printed `DateTime(precision: p)` | a JavaScript `Date` | | `@db.Timestamp(p)` | `TimestampJsDate(p)` | a JavaScript `Date`, the stored value read as UTC | | `@db.Date` | `DateString` | an ISO 8601 string, such as `"2026-09-14"` | | `@db.Time(p)` | `TimeString(p)` | an ISO 8601 string, such as `"10:00:00.5"` | | `@db.Timetz(p)` | `Timetz(p)` | an ISO 8601 string with a full offset, such as `"10:00:00+02:00"` | A `Date` holds milliseconds, so a `@db.Timestamptz(6)` or `@db.Timestamp(6)` column with values that use the extra digits reads with them dropped. A `Date` cannot hold `infinity` or `-infinity` either, so a row that stores one fails to read with `RUNTIME.DECODE_FAILED`. To read other types, such as strings that keep every digit or `Temporal` objects, write a Prisma ORM 8 contract with `npx prisma contract print --output prisma/contract.prisma`. In that file, add `as: string` or `as: temporal` to a `DateTime(...)` field, as in `DateTime(as: string, storage: timestamp)`, and write `Date(as: temporal)` or `Time(as: temporal)` for a date or a time. `Temporal` is the newer JavaScript date and time API. Runtimes without it, such as Node.js 24, need the `temporal-polyfill` package and `import "temporal-polyfill/full/global"` at the top of the file that creates your client, before it reads a `Temporal` field. A column that can hold `infinity` needs `as: string`. Then change `contract` in `prisma.config.ts` from `prisma7Schema("prisma/schema.prisma")` to `"./prisma/contract.prisma"`, so that `contract emit` reads the edited file. When your code creates or updates a row, Prisma ORM fills each `@updatedAt` field with the time from your application's clock, as a `Date` or as text in the form its type reads, rounded down to the column's precision. This also works on a `@db.Date`, `@db.Time`, or `@db.Timetz` field. A field can have both `@updatedAt` and `@default(now())`, and `@default(now())` stays the column's default in the database. When your code creates a row without a value for a `@default(now())` field, Prisma ORM fills it with the current UTC time, as the Prisma ORM 7 client did, so it reads `@default(now())` as `@default(now()) @onCreate(now())`. An `INSERT` from outside Prisma ORM still gets the column default. A list such as `String[]` reads as a list whose elements may be `null`, because the database that Prisma ORM 7 built does not stop a list from holding `null` elements. A `@db.Citext` field reads as `citext.Citext`, from the citext pack in `@prisma/orm-postgres-contrib`. Add the pack to the config with `import citext from "@prisma/orm-postgres-contrib/citext/control"` and `extensions: [citext]`; without it, `contract emit` refuses the field with `PSL.PRISMA7_EXTENSION_PACK_MISSING`, which names the import to add. The datasource's `extensions` list, such as `extensions = [vector, pg_trgm]`, is read too: an extension a configured pack provides, such as pgvector's `vector`, comes from the pack, and any other is declared in the contract, so `db sign` checks that the database has it. Once the config is in place, run `npx prisma contract emit` and then [`npx prisma db sign`](https://www.prisma.io/docs/cli/db-sign). `db sign` checks that the database matches the contract and then records that in the database, without changing your tables. Run both commands again after each Prisma ORM 7 migration, whether you ran `npx prisma7 migrate dev` or `npx prisma7 migrate deploy`, so that the record names the new contract. An `Unsupported("ltree")` field becomes a column of that database type with no field on the model, as in the Prisma ORM 7 client: migrations and `db verify` keep the column, and your code cannot read or write it. `contract print` cannot write such a column yet, so a schema with `Unsupported(...)` fields stays your contract source. `contract emit` fails on any part of the schema that Prisma ORM 8 cannot represent exactly, such as a `view` block or `relationMode = "prisma"`. The error names the file and the line and suggests an edit to the Prisma ORM 7 schema. When that edit would also change the database on the next Prisma ORM 7 migration, the error says so. Prisma ORM 8 has no views, so for a `view` block the error suggests removing the view or replacing it with a model over the table the view reads. `contract emit` also fails when a default function gets an argument it does not take, such as `uuid(5)` or `cuid(1)`. The error code is `PSL.PRISMA7_UNKNOWN_DEFAULT`, and the message names the values the function takes, for example `uuid: version must be 4 or 7, got 5`. The contract also keeps the columns and tables of `@ignore` fields and `@@ignore` models, as storage that no model maps, so adding or removing `@ignore` plans no migration. The ORM still leaves those fields and models out of its queries. Because they are in the contract, they have to meet the same rules as the rest of the schema: every `@db.*` type Prisma ORM 7 accepts on PostgreSQL is read, and `@db.Citext` needs the citext pack even on an ignored model. The contract keeps the constraint names Prisma ORM 7 gave the database. Where Prisma ORM 7's name for a primary key or foreign key differs from the name Prisma ORM 8 would derive, the contract states it: a `map` on `@id`, `@@id`, or `@relation`, the primary key of an implicit many-to-many table such as `_PostToTag_AB_pkey`, and a name Prisma ORM 7 cut to 63 bytes. A later migration that touches one of these constraints then targets the name the database has. A `map` longer than PostgreSQL keeps is refused, as Prisma ORM 7 refuses it. After Prisma ORM 8 takes over the migrations, you can give an existing integer column `@default(autoincrement())`. `migration plan` and `db update` create or reuse a sequence for it and start the sequence past the column's current maximum, so rows already in the table do not collide with new ones. ## Use a Prisma ORM 6 MongoDB schema [#use-a-prisma-orm-6-mongodb-schema] On MongoDB, Prisma ORM 8 can read a Prisma ORM 6 `schema.prisma` directly as its contract source. Wrap the path in `prisma6Schema`: ```typescript title="prisma.config.ts" import "dotenv/config"; import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig, prisma6Schema } from "@prisma/orm-mongo/config"; export default definePrismaConfig({ orm: ormConfig({ contract: prisma6Schema("prisma/schema.prisma"), db: { connection: process.env["DATABASE_URL"]!, }, }), }); ``` The schema file does not need the `// use prisma-8` first line. Run `npx prisma contract emit` and then [`npx prisma db sign`](https://www.prisma.io/docs/cli/db-sign), which checks that the database Prisma ORM 6 built matches the contract. `prisma6Schema` reads each field as the BSON type Prisma ORM 6 stores. A plain `Int` and an `Int @db.Long` are a `number` in your code, written as a BSON long, and a stored value with a fraction fails to read with `RUNTIME.DECODE_FAILED`. A `Bytes @db.ObjectId` field reads as a 24-digit hex string and takes a hex string or an `ObjectId`, not a `Buffer`. Every native type Prisma ORM 6 accepts on MongoDB is read, except `DateTime @db.Timestamp`. Each index keeps the name Prisma ORM 6 gave it: the name its `map:` sets (or `name:` on `@@index`), or else the name Prisma ORM 6 derives, such as `User_email_key` for a unique index on `email` and `User_email_idx` for a plain one. `db verify` checks these names against the database. If it reports an index whose name differs, write the name the database holds with `map:`. The indexes are kept as Prisma ORM 6 wrote them, and none are merged. Two indexes of one model with the same fields and the same sort, such as `@unique` and `@@unique` on one field, are refused with `PSL.PRISMA6_MONGO_INDEX_ALREADY_EXISTS`, as Prisma ORM 6 refuses them. Remove one of them, and when only one is unique, keep that one. A unique and a plain index on the same field that Prisma ORM 6 accepts, such as `@unique` beside `@@index([email(sort: Asc)])`, are both kept. Two indexes of one model with one name are refused with `PSL.PRISMA6_MONGO_INDEX_NAME_DUPLICATE`, and an empty `map:` or one longer than 127 bytes with `PSL.PRISMA6_MONGO_INDEX_NAME_INVALID`. After you upgrade from a release before `8.0.0-rc.23`, a contract emitted from a schema with indexes gets a new storage hash. Run `npx prisma contract emit`, then `npx prisma db verify` and `npx prisma db sign` against each database. The database does not change; `db sign` only updates the storage hash it records. `contract emit` fails on any part of the schema that Prisma ORM 8 cannot represent exactly, with an error code that starts with `PSL.PRISMA6_MONGO_`. The [error reference](https://www.prisma.io/docs/orm/reference/error-reference) lists each code and what to change. ## Write your own contract source [#write-your-own-contract-source] A config that builds `contract.source` itself, as an object with a `load` function, must give the object a `format`: `"psl"` when its inputs are PSL text, and `"typescript"` when it builds the contract in TypeScript. Without it, every command that reads the config fails with `CONFIG.VALIDATION_FAILED`. A path, a glob, `prisma7Schema` and `prisma6Schema` set the format for you. ## Emit-only config [#emit-only-config] `contract emit` does not connect to a database, so the `orm` section can omit `db.connection`: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ 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 `db migrate`. ## Extension packs [#extension-packs] Add extension control descriptors to the `orm` section when your contract uses extension-provided types: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; import pgvector from "@prisma/orm-extension-pgvector/control"; export default definePrismaConfig({ orm: ormConfig({ contract: "./prisma/contract.prisma", extensions: [pgvector], db: { connection: process.env["DATABASE_URL"]!, }, }), }); ``` Re-run `contract emit` after changing extension packs, then update the matching runtime client. ## Agent skills [#agent-skills] The `skills` section controls the [agent skills commands](https://www.prisma.io/docs/cli/skills) and the staleness check: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; export default definePrismaConfig({ skills: { agents: ["claude", "cursor"], check: true, }, }); ``` | Field | What it does | | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `agents` | The agent harnesses `skills sync` writes and `skills list` reports: `claude`, `cursor`, `agents`, `devin`. An empty array records that no agent skills are wanted, and the next `skills sync` removes the copies already on disk. Default: all of them. | | `check` | Set `false` to stop commands reporting out-of-date skills, for everyone working in the project. Default: `true`. | [`init`](https://www.prisma.io/docs/cli/init) scaffolds this section for you. ## Database URLs [#database-urls] Database commands accept `--db `. If you omit it, Prisma ORM uses the database connection from `prisma.config.ts`. #### bun ```bash bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db verify --db "$DATABASE_URL" ``` ## Environment variables [#environment-variables] The variables the CLI reads, such as `PRISMA_DISABLE_TELEMETRY`, `PRISMA_SKILLS_CHECK`, and the `PRISMA_SERVICE_TOKEN` pair for CI, are listed on [Environment variables](https://www.prisma.io/docs/cli/environment-variables). `DATABASE_URL` is not one of them: your config file reads it, as in the example above. ## Output modes [#output-modes] Use the default text output when running commands locally. Use `--json` in CI or automation: #### bun ```bash bunx prisma db verify --db "$DATABASE_URL" --json ``` #### pnpm ```bash pnpm prisma db verify --db "$DATABASE_URL" --json ``` #### yarn ```bash yarn prisma db verify --db "$DATABASE_URL" --json ``` #### npm ```bash npx prisma db verify --db "$DATABASE_URL" --json ``` Piping a command does not switch it to JSON: without `--json`, standard output gets the command's plain data, such as one line per item of a list. See [Global flags](https://www.prisma.io/docs/cli/global-flags#output-formats). For an AI agent that reads the output as text rather than parsing JSON, use `--format markdown`; see [Global flags](https://www.prisma.io/docs/cli/global-flags#output-formats). Use `--no-interactive` for scripts that must never pause for user input. Use `--confirm ` to grant a consent prompt non-interactively. Commands that ask about data loss, such as [`db update`](https://www.prisma.io/docs/cli/db-update), take their answers as flags instead: `--delete`, `--rename`, and `--allow`. ## JSON output [#json-output] In `--json` mode, commands emit newline-delimited JSON events. Progress events have `kind: "step-finished"`. The final event has `kind: "result"` and carries the `envelope` object your script branches on: * `envelope.ok`: `true` or `false`. * `envelope.result`: the command's data, when `ok` is `true`. * `envelope.error.code`: a dotted `NAMESPACE.SUBCODE`, for example `PROJECT.NOT_FOUND` or `SERVICE.PROJECT_SETUP_REQUIRED`. * `envelope.error.summary` and `envelope.error.why`: what failed and why it was rejected. * `envelope.nextActions`: machine-readable follow-up commands, so agents can drive the CLI. Branch on `envelope.error.code`, not the message text: codes are a stable contract, while message wording can change between releases. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. - [`contract infer`](https://www.prisma.io/docs/cli/contract-infer): Infer a starter contract from an existing database. # contract emit (/docs/cli/contract-emit) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Emit Prisma ORM contract artifacts. Location: CLI > contract emit `contract emit` reads your contract source (TypeScript or Prisma schema) and writes the generated artifacts used by the runtime, verification, and migration tooling. The command is offline: it does not need a database connection. A Prisma schema source can be one `.prisma` file or a glob that matches several files; see [Split the schema across several files](https://www.prisma.io/docs/cli/configuration#split-the-schema-across-several-files). `contract emit` reads only the `.prisma` files whose first line is `// use prisma-8`, and skips any other file without a warning. When no file starts with that line, it fails with `CONTRACT.SOURCE_LOAD_FAILED` and reports the problem with the code `PSL_NO_OPTED_IN_SCHEMA_FILES`. ## Usage [#usage] #### bun ```bash bunx prisma contract emit ``` #### pnpm ```bash pnpm prisma contract emit ``` #### yarn ```bash yarn prisma contract emit ``` #### npm ```bash npx prisma contract emit ``` ## Options [#options] | Option | What it does | | --------------------- | --------------------------------------------------------------------- | | `--output-path ` | Writes `contract.json` and `contract.d.ts` into a specific directory. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ## What it creates [#what-it-creates] The command emits: * `contract.json`, the canonical machine-readable contract * `contract.d.ts`, the generated TypeScript contract declarations * for each extension pack in the config, such as pgvector, its files under `migrations//`: its contract, its head ref and its migrations. Commit them with your own migrations. After you upgrade or downgrade the pack, the next emit moves them to the installed version. With `--output-path`, which writes the contract outside the project, none are written. Do not edit these files by hand. Re-run `contract emit` after changing the contract source or extension pack list. The first emit after you upgrade from a release before `8.0.0-rc.12` reorders the entries in `contract.d.ts` to follow the order in `contract.json`, which needs no change to your code. The first emit after you upgrade from a release before `8.0.0-rc.13` renames two keys in `contract.json`: each generated default under `execution.mutations.defaults` names its target as `entry` and `field` instead of `table` and `column`. The client refuses a contract that has the old keys, so run `contract emit` after you upgrade. `contract emit` does not rewrite the contracts stored under `migrations/`, such as the snapshots in `migrations/snapshots/`. To rename the keys in them, download the [`rename-execution-ref-keys` script](https://github.com/prisma/orm/blob/v8.0.0-rc.15/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts) into your project root and run it there: ```bash title="Terminal" curl -O https://raw.githubusercontent.com/prisma/orm/v8.0.0-rc.15/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts npx tsx rename-execution-ref-keys.ts ``` The script renames `table` to `entry` and `column` to `field` in each `ref` under `execution.mutations.defaults`, in every `.json` and `.d.ts` file under a `migrations/` folder. It leaves each `executionHash` as it is, and a second run changes nothing. Pass `--check` to list the files it would change without writing them. Since `8.0.0-rc.15`, each SQL column in `contract.json` stores its data type id, such as `"dataType": "pg/text"`, in place of `nativeType`, and the client refuses a contract in the old format. When you upgrade from a release before `8.0.0-rc.15`, upgrade every extension that ships migrations, such as pgvector and PostGIS, in the same step. Then, before the first emit, run the [`data-type-in-contract` script](https://github.com/prisma/orm/blob/v8.0.0-rc.15/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts) in your project root, and sign every database with [`db sign`](https://www.prisma.io/docs/cli/db-sign): ```bash title="Terminal" curl -O https://raw.githubusercontent.com/prisma/orm/v8.0.0-rc.15/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts node data-type-in-contract.ts npx prisma db sign --db "$DATABASE_URL" ``` The script runs on any Node.js version Prisma ORM supports: 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer. It rewrites every contract, snapshot, migration, ref, `migration.ts`, and `contract.d.ts` in the project, and every storage hash changes once. Until a database is signed, `db migrate` refuses with `MIGRATION.MARKER_MISMATCH`. Commit your work before you run it, so you can review its changes. When you upgrade from a release before `8.0.0-rc.19`, run `contract emit` again, because the files an earlier release wrote do not work with this one. A SQL `contract.d.ts` from an earlier release no longer compiles. The CLI refuses every older MongoDB `contract.json`, and some older PostgreSQL ones, with `CONTRACT.VALIDATION_FAILED`. Then look at the `storageHash` value in `contract.json`. It identifies the tables and columns your contract describes, and `db sign` records it in each database. If the new emit changed it, run [`db sign`](https://www.prisma.io/docs/cli/db-sign) against every database that uses the contract, such as development, staging, and production. Until you do, `db migrate` fails with `MIGRATION.MARKER_MISMATCH` and `db verify` fails with `CONTRACT.MARKER_MISMATCH`, because the database still records the old value. The [upgrade instructions](https://github.com/prisma/orm/blob/v8.0.0-rc.19/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/) include scripts that update the copies of the contract stored under `migrations/`. When you upgrade from a release before `8.0.0-rc.22` and a `contract.json` keeps `valueObjects` in its domain section, the CLI refuses it with `CONTRACT.VALIDATION_FAILED`: since `8.0.0-rc.22`, value objects are part of the storage the contract describes, so changing one is a migration. Before you emit again, run the `value-objects-in-storage` script from the [upgrade instructions](https://github.com/prisma/orm/blob/v8.0.0-rc.22/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/), which rewrites the contracts and snapshots under `migrations/`, then run `db sign` against each database, then emit. On PostgreSQL, the next `migration plan` adds a check on each value object column and discriminator column. The same release also changes what some PostgreSQL date and time types read, and those instructions list every change and the order to make them in. When the contract source cannot be read, the command fails with `CONTRACT.SOURCE_LOAD_FAILED` and prints each finding, meaning each problem it found in the source, with the file and line where it knows them. In `--json` output, the findings are the entries of the `envelope.diagnostics` array in the final `result` event, next to `envelope.error`. Each entry has a `code`, a `summary`, and, where known, `where.path` and `where.line`. If an entry's `code` is `CONTRACT.SOURCE_DIAGNOSTIC`, the code of the specific problem, such as `PSL_NO_OPTED_IN_SCHEMA_FILES`, is in its `meta.code`. A warning in the contract source, such as `PSL_DEPRECATED_SCALAR_NAME` for a MongoDB scalar type name that is deprecated, does not stop the command. It is reported as a diagnostic whose `severity` is `warn`, and the command still writes both files. In `--json` output, the warning is an entry of `envelope.diagnostics` in the final `result` event, with `code` set to `CONTRACT.SOURCE_DIAGNOSTIC` and the warning's own code in `meta.code`. ## Run it automatically [#run-it-automatically] In development, a Vite plugin runs `contract emit` for you: once when the dev server starts, and again whenever the contract source or `prisma.config.ts` changes. It needs Vite 7 or 8, and comes with your database package, so there is nothing to install: ```typescript title="vite.config.ts" import { defineConfig } from "vite"; import { prismaVitePlugin } from "@prisma/orm-postgres/vite-plugin-contract-emit"; export default defineConfig({ plugins: [prismaVitePlugin()], }); ``` On MongoDB, import it from `@prisma/orm-mongo/vite-plugin-contract-emit`. The plugin reads `prisma.config.ts` from the Vite root; pass another path as the first argument, `prismaVitePlugin("config/prisma.config.ts")`. A second argument takes `debounceMs` (how long to wait after a change before emitting, 150 by default) and `logLevel` (`"silent"`, `"info"`, or `"debug"`). The dev server prints one line per emit: ```text [prisma-vite-plugin-contract-emit] Emitted contract (storageHash: ab5014a0...) ``` An emit that fails shows in Vite's error overlay. The plugin does nothing in a production build, so builds and CI still run the command themselves. With any other bundler, or for a build, add the command as a `prebuild` script, which npm, pnpm, and yarn run before `build`: ```json title="package.json (excerpt)" { "scripts": { "prebuild": "prisma contract emit", "build": "next build" } } ``` ## Examples [#examples] #### bun ```bash bunx prisma contract emit bunx prisma contract emit --output-path ./generated bunx prisma contract emit --json ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma contract emit --output-path ./generated pnpm prisma contract emit --json ``` #### yarn ```bash yarn prisma contract emit yarn prisma contract emit --output-path ./generated yarn prisma contract emit --json ``` #### npm ```bash npx prisma contract emit npx prisma contract emit --output-path ./generated npx prisma contract emit --json ``` ## JSON output [#json-output] With `--json`, standard output gets one JSON object per line. The command first prints a line for each step as it starts and finishes, with `kind` set to `step-started` or `step-finished`. The last line has `kind` set to `result`. When the command succeeds, `envelope.ok` is `true` and `envelope.result` holds what it wrote. Here the line is formatted for reading: ```json { "kind": "result", "envelope": { "ok": true, "commandId": "contract.emit", "result": { "ok": true, "storageHash": "1054ff66dd2721cf119b17845c6da6043491cc100c62e59d5fd50f134bfea938", "profileHash": "3916f444a8a17ad749191acf9e08dad97d1a327b88c2f1d45d12f240296aa8b2", "outDir": "/path/to/project/src/prisma", "files": { "json": "/path/to/project/src/prisma/contract.json", "dts": "/path/to/project/src/prisma/contract.d.ts" }, "timings": { "total": 187 } }, "exitCode": 0, "diagnostics": [], "nextActions": [] }, "commandId": "contract.emit", "timestamp": "2026-10-28T15:50:45.533Z" } ``` When the command fails, `envelope.ok` is `false`, `envelope.error.code` holds the error code, and there is no `envelope.result`. `storageHash` is the contract's hash: the value that [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref) and the `--to` flags accept. To read it in a script, keep only the result line, and use `jq -e` with `pipefail` so that the script stops when emitting fails: ```bash set -eo pipefail hash=$(npx prisma contract emit --json | jq -er 'select(.kind == "result") | .envelope.result.storageHash') ``` ## Data lines [#data-lines] Without `--json`, standard output gets two lines: the path of `contract.json`, then the path of `contract.d.ts`, each relative to the working directory. The status lines go to standard error. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ```bash npx prisma contract emit | head -n 1 ``` ## Next steps [#next-steps] After emitting, choose the database workflow: * use [`db init`](https://www.prisma.io/docs/cli/db-init) for first-time bootstrap * use [`db update`](https://www.prisma.io/docs/cli/db-update) for direct reconciliation * use [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) for checked-in migrations * use [`db verify`](https://www.prisma.io/docs/cli/db-verify) to check drift ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract infer`](https://www.prisma.io/docs/cli/contract-infer): Infer a starter contract from an existing database. # contract infer (/docs/cli/contract-infer) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Infer a starter contract from an existing database. Location: CLI > contract infer `contract infer` inspects a live database and writes a starter PSL contract. An existing file at the output path is overwritten, with a warning. Use it when you are adding Prisma ORM to an existing database and want an initial contract to review and edit. ## Usage [#usage] #### bun ```bash bunx prisma contract infer [--db "$DATABASE_URL"] ``` #### pnpm ```bash pnpm prisma contract infer [--db "$DATABASE_URL"] ``` #### yarn ```bash yarn prisma contract infer [--db "$DATABASE_URL"] ``` #### npm ```bash npx prisma contract infer [--db "$DATABASE_URL"] ``` ## Options [#options] | Option | What it does | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `--db ` | Connects to the database. Optional: without it the command uses `db.connection` from `prisma.config.ts`, and fails only when neither is set. | | `--output ` | Writes the inferred PSL contract to a specific path. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ## Examples [#examples] #### bun ```bash bunx prisma contract infer --db "$DATABASE_URL" bunx prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma bunx prisma contract infer --db "$DATABASE_URL" --json ``` #### pnpm ```bash pnpm prisma contract infer --db "$DATABASE_URL" pnpm prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma pnpm prisma contract infer --db "$DATABASE_URL" --json ``` #### yarn ```bash yarn prisma contract infer --db "$DATABASE_URL" yarn prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma yarn prisma contract infer --db "$DATABASE_URL" --json ``` #### npm ```bash npx prisma contract infer --db "$DATABASE_URL" npx prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma npx prisma contract infer --db "$DATABASE_URL" --json ``` ## Data lines [#data-lines] Without `--json`, standard output gets one line: the path of the PSL file the command wrote, relative to the working directory. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ## 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 The file starts with `// use prisma-8`, because `contract emit` reads only `.prisma` files that start with that line. Each model is named after its table, and gets `@@map` only when the table name differs from the model name: a table `User` becomes `model User`, and a table `user_profile` becomes `model UserProfile` with `@@map("user_profile")`. Every column default is written in a form `contract emit` accepts, so you can emit the file without editing it. [Default values](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#default-values) shows those forms. In a list column's type, a `?` means something different depending on where it is: * `Type[]?`, with `?` after the brackets: the column itself can be `NULL`. * `Type?[]`, with `?` before the brackets: the list can hold `NULL` elements. A list column that Prisma ORM migrations created cannot hold `NULL` elements, because the migration adds a check that stops it, so it gets no `?` before the brackets. Any other list column gets one. Each column gets a type such as `String(storage: varchar, length: 20)`, `Int(storage: int2)`, `Bit(8)`, `Varbit(16)`, `Xml`, `Money`, or `Duration(precision: 3)`, written with the fewest parameters that describe the column exactly. Where a [convenience type](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#models-and-fields) gives the column's type, the contract writes it with only the arguments that differ from its defaults. The types come from Prisma ORM's types for your database and from the extension packs listed under `extensions` in `prisma.config.ts`. An extension pack is the Prisma ORM package for a database extension, such as pgvector. When a column has a type that none of these provide, the command writes no file. It fails with `CONTRACT.INFER_COLUMN_TYPE_UNCLAIMED` and lists every such column, such as `public.doc.meta: hstore`. To get past the error, do one of the following for each listed column: * If the type comes from a database extension that has a Prisma ORM pack, add the pack to `extensions` in `prisma.config.ts` and run `contract infer` again. * Write the contract by hand, and declare the column's field as ``Raw(sql`hstore`)``. `Raw(...)` declares a field by the database's own name for its type, here the type the error lists. [Columns of any database type](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#columns-of-any-database-type) shows how. * Change the column's type, or remove the column from the database. `contract infer` writes date and time columns with the [convenience date and time types](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#models-and-fields), which need no `Temporal`, the newer JavaScript date and time API. A `timestamptz(3)` column is written `DateTime` and a `timestamptz` column `DateTime(precision: 6)`, both read as a JavaScript `Date`; a `timestamp(3)` column is `DateTime(storage: timestamp)`, read as a `Date` with the stored time taken as UTC; `date` is `Date` and `time(3)` is `Time(precision: 3)`, read as ISO 8601 strings such as `"2026-09-14"` and `"10:00:00.123"`; and `interval` is `Duration`, an ISO 8601 duration. A `Date` holds milliseconds, so a column with six digits of a second reads with the last three dropped. To keep them, add `as: string` or `as: temporal`, as in `DateTime(as: string, precision: 6)`. A `Date` cannot hold `infinity` or `-infinity` either, so a row that stores one fails to read with `RUNTIME.DECODE_FAILED`; `as: string` reads them as `infinity` and `-infinity`. A `bytea` default is written as the hexadecimal text PostgreSQL prints, inside backticks with `bytea` in front, such as ``@default(bytea`\x68656c6c6f`)``. The word in front of the backticks names the type of the value. A contract inferred before `8.0.0-rc.15` keeps its types until you run `contract infer` again. When you do, the date and time fields and any `bytea` default change, and so does the storage hash: emit the contract, update the code that used `Temporal` values for these fields, then run `prisma db sign` for a database you keep with `db update`, or create an empty migration with [`migration new`](https://www.prisma.io/docs/cli/migration-new) and apply it when you use migrations. If you keep an inferred contract in version control, running `contract infer` again after an upgrade can write the same database differently, so review the diff before you commit it. The command stops at `contract.prisma`. Follow it with the emit and sign steps: #### bun ```bash bunx prisma contract emit bunx prisma db sign --db "$DATABASE_URL" bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma db sign --db "$DATABASE_URL" pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract emit yarn prisma db sign --db "$DATABASE_URL" yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract emit npx prisma db sign --db "$DATABASE_URL" npx prisma db verify --db "$DATABASE_URL" ``` `db sign` is the handoff point where you record that the existing database matches the reviewed contract. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # contract print (/docs/cli/contract-print) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Write the configured contract as a Prisma ORM 8 PSL contract. Location: CLI > contract print `contract print` loads the contract that `contract` names in `prisma.config.ts` and writes it as a Prisma ORM 8 PSL contract. The source can be a Prisma ORM 7 schema, a TypeScript contract, or a PSL contract. Use it to move from a Prisma ORM 7 `schema.prisma`, read through [`prisma7Schema`](https://www.prisma.io/docs/cli/configuration#use-a-prisma-orm-7-schema), to a contract file written for Prisma ORM 8. The command is offline. It does not need a database connection. ## Usage [#usage] #### bun ```bash bunx prisma contract print [--output ] ``` #### pnpm ```bash pnpm prisma contract print [--output ] ``` #### yarn ```bash yarn prisma contract print [--output ] ``` #### npm ```bash npx prisma contract print [--output ] ``` ## Options [#options] | Option | What it does | | ----------------- | ---------------------------------------------------------------------------------------------------------- | | `--output ` | Writes the PSL to this file. Without it, the command writes the PSL to standard output and writes no file. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result, with the PSL in `psl.text`. | ## Examples [#examples] #### bun ```bash bunx prisma contract print bunx prisma contract print --output ./src/prisma/contract.prisma bunx prisma contract print --json ``` #### pnpm ```bash pnpm prisma contract print pnpm prisma contract print --output ./src/prisma/contract.prisma pnpm prisma contract print --json ``` #### yarn ```bash yarn prisma contract print yarn prisma contract print --output ./src/prisma/contract.prisma yarn prisma contract print --json ``` #### npm ```bash npx prisma contract print npx prisma contract print --output ./src/prisma/contract.prisma npx prisma contract print --json ``` Without `--output`, standard output gets only the PSL, while the status line goes to standard error. So you can redirect or pipe it: ```bash npx prisma contract print > contract.v8.prisma ``` The PSL is printed as it is, not as data lines, so tabs and line breaks in it are not escaped. With `--output`, standard output gets nothing. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the data lines of the other commands. ## What it writes [#what-it-writes] The file starts with `// use prisma-8`, the first line `contract emit` looks for in a `.prisma` file. When you point `contract` at the file and run `contract emit`, you get the same contract as before, with the same hashes, so the database needs no migration and no new `db sign`. A value that Prisma ORM generates in your application, rather than in the database, is written with `@onCreate(...)` and `@onUpdate(...)` after the field's type. `@onCreate` sets the value when a row is created, and `@onUpdate` sets it again on every update. So a Prisma ORM 7 `@default(uuid())` prints as `@onCreate(uuid())`, and an `@updatedAt` field prints as, for example, `DateTime(storage: timestamp) @onCreate(now()) @onUpdate(now())`. A Prisma ORM 7 `@default(now())` prints as `@default(now()) @onCreate(now())`, because the Prisma ORM 7 client also filled it on create. In a Prisma ORM 8 schema you write these attributes too: `contract emit` refuses `@default(uuid())` and points you to `@onCreate(uuid())`. `@default(now())` and `@default(autoincrement())` still work, because the database fills those values. A date, time, or bytes default prints with the name of its type in front of the value, and the value in backticks, such as ``@default(timestamptz`2024-01-01T00:00:00Z`)``. A column whose database type has no Prisma ORM 8 field type prints as ``Raw(sql`...`)``, which declares the column by the database's name for its type, such as ``Raw(sql`ltree`)``. A Prisma ORM 7 schema with an `Unsupported(...)` field cannot be printed yet. Prisma ORM 8 reads such a field as a column with no field on the model, so your code cannot read or write it. A `Raw(...)` field is different: it is a field on the model, and your code reads and writes its value. Prisma ORM 8 PSL has no way to declare a column without a field, so keep the Prisma ORM 7 schema as the contract source until it does. When a part of the contract has no PSL form, the command names that part, fails, and writes nothing. It also refuses an `--output` path that is one of the files it reads, `prisma.config.ts`, or a file `contract emit` writes. A warning in the contract source, such as `PSL_DEPRECATED_SCALAR_NAME`, does not stop the command. It is reported as a diagnostic whose `severity` is `warn`. In `--json` output, the warning is an entry of the result's `diagnostics`, with `code` set to `CONTRACT.SOURCE_DIAGNOSTIC` and the warning's own code in `meta.code`. ## Next steps [#next-steps] * Set `contract` in `prisma.config.ts` to the file you wrote, as [Configuration](https://www.prisma.io/docs/cli/configuration) shows. * Run [`contract emit`](https://www.prisma.io/docs/cli/contract-emit) to write `contract.json` and `contract.d.ts` from it. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db init (/docs/cli/db-init) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Initialize a database from the current Prisma ORM contract. Location: CLI > db init `db init` bootstraps a database to match the current emitted contract and signs it. It creates everything the contract declares and the database does not have yet, using additive operations only. Structures already in place and compatible are left alone. A conflict that would need a destructive change stops the run. ## Usage [#usage] #### bun ```bash bunx prisma db init --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db init --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db init --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db init --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--dry-run` | Shows planned operations without applying them. | | `--advance-ref ` | Advances the named [ref](https://www.prisma.io/docs/cli/migration-ref) to the post-command contract hash. Without it, `db init` advances `db` when `--db` is omitted, and advances nothing when `--db` is passed. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--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. ### How the db ref moves [#how-the-db-ref-moves] Run without `--db`, `db init` takes the connection from `db.connection` in `prisma.config.ts` and advances the [ref](https://www.prisma.io/docs/cli/migration-ref) named `db` to the contract it just applied. Pass `--db` and that advancement is suppressed, even when the URL is the same one the config holds. Pass `--advance-ref db` alongside `--db` to get it back. The `db` ref is what [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) uses as its starting point when you do not pass `--from`. Passing `--db` only suppresses the advancement; it never removes a `db` ref that already exists. So a loop that always passes `--db` without `--advance-ref db` leaves the ref wherever it was last set, and the next `migration plan` starts from that stale contract. If the ref was never created, `migration plan` plans from an empty database while `migrations/app/` is empty, and refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` once migrations exist on disk. Run a dry run first when you are not working with a disposable local database: #### bun ```bash bunx prisma db init --db "$DATABASE_URL" --dry-run ``` #### pnpm ```bash pnpm prisma db init --db "$DATABASE_URL" --dry-run ``` #### yarn ```bash yarn prisma db init --db "$DATABASE_URL" --dry-run ``` #### npm ```bash npx prisma db init --db "$DATABASE_URL" --dry-run ``` ## Examples [#examples] #### bun ```bash bunx prisma contract emit bunx prisma db init --db "$DATABASE_URL" --advance-ref db bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma db init --db "$DATABASE_URL" --advance-ref db pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract emit yarn prisma db init --db "$DATABASE_URL" --advance-ref db yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract emit npx prisma db init --db "$DATABASE_URL" --advance-ref db npx prisma db verify --db "$DATABASE_URL" ``` #### bun ```bash bunx prisma db init --db "$DATABASE_URL" --dry-run --json ``` #### pnpm ```bash pnpm prisma db init --db "$DATABASE_URL" --dry-run --json ``` #### yarn ```bash yarn prisma db init --db "$DATABASE_URL" --dry-run --json ``` #### npm ```bash npx prisma db init --db "$DATABASE_URL" --dry-run --json ``` ## Data lines [#data-lines] `db init` prints nothing on standard output. Its exit code is the result, and `--json` carries the plan and what ran. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the data lines of the other commands. ## When to use db update instead [#when-to-use-db-update-instead] Use [`db update`](https://www.prisma.io/docs/cli/db-update) when the database already exists and you want Prisma ORM to reconcile it with a changed contract. Use [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) when you want a reviewable migration package in version control. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db migrate (/docs/cli/db-migrate) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Apply pending Prisma ORM migrations. Location: CLI > db migrate `db migrate` applies pending on-disk migrations to advance the database. It walks every contract space and applies migrations in canonical order: extensions alphabetically, then the app. It applies only the migrations that exist on disk and never generates new operations. Prisma ORM keeps one migration history for your own models, called the `app` space, in `migrations/app/`, and one for each [extension package](https://www.prisma.io/docs/orm/extensions/using-extensions) that ships its own migrations, such as pgvector. Each of these histories is a [contract space](https://www.prisma.io/docs/orm/migrations/the-migration-graph#terms-used-on-this-page). Use it from a controlled deployment step after reviewing migration packages. ## Usage [#usage] #### bun ```bash bunx prisma db migrate --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db migrate --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db migrate --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db migrate --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--to ` | Applies migrations up to a target contract state. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, [`^`](#contract-references), [`@contract`](#contract-references), [`@db`](#contract-references), or [`@empty`](#contract-references). | | `--advance-ref ` | Advances the named [ref](https://www.prisma.io/docs/cli/migration-ref) to the post-apply marker after success. | | `--show` | Previews the migration route without applying (read-only). | | `--from ` | Use it with `--show`, where it sets the starting state for the preview. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, [`^`](#contract-references), [`@contract`](#contract-references), [`@db`](#contract-references), or [`@empty`](#contract-references). | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ### Contract references [#contract-references] A ref name is a name you gave a contract state with [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref), such as `prod`. `^` is a migration directory name followed by `^`, and it names the contract state before that migration, while the directory name alone names the state after it. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) lists the forms for every command. `@contract` names the contract in `contract.json`, which `contract emit` writes. The database stores a marker, a row that says which contract state it matches. `@db` names that state, or the empty database when the database has no marker. `@empty` names the empty database, before any migration. ## Recommended flow [#recommended-flow] #### bun ```bash bunx prisma migration status --db "$DATABASE_URL" bunx prisma db migrate --db "$DATABASE_URL" bunx prisma migration status --db "$DATABASE_URL" bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma migration status --db "$DATABASE_URL" pnpm prisma db migrate --db "$DATABASE_URL" pnpm prisma migration status --db "$DATABASE_URL" pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma migration status --db "$DATABASE_URL" yarn prisma db migrate --db "$DATABASE_URL" yarn prisma migration status --db "$DATABASE_URL" yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma migration status --db "$DATABASE_URL" npx prisma db migrate --db "$DATABASE_URL" npx prisma migration status --db "$DATABASE_URL" npx prisma db verify --db "$DATABASE_URL" ``` Run `migration status` before and after applying migrations to see what changed. ## Previewing the route [#previewing-the-route] `--show` prints the route `db migrate` would take without touching the database: #### bun ```bash bunx prisma db migrate --show bunx prisma db migrate --show --from @contract --to production ``` #### pnpm ```bash pnpm prisma db migrate --show pnpm prisma db migrate --show --from @contract --to production ``` #### yarn ```bash yarn prisma db migrate --show yarn prisma db migrate --show --from @contract --to production ``` #### npm ```bash npx prisma db migrate --show npx prisma db migrate --show --from @contract --to production ``` ## Applying to a target [#applying-to-a-target] If your project uses named [refs](https://www.prisma.io/docs/cli/migration-ref), apply up to a target ref: #### bun ```bash bunx prisma db migrate --db "$DATABASE_URL" --to production ``` #### pnpm ```bash pnpm prisma db migrate --db "$DATABASE_URL" --to production ``` #### yarn ```bash yarn prisma db migrate --db "$DATABASE_URL" --to production ``` #### npm ```bash npx prisma db migrate --db "$DATABASE_URL" --to production ``` Manage refs with [`migration ref`](https://www.prisma.io/docs/cli/migration-ref). ## When the marker is outside your migrations [#when-the-marker-is-outside-your-migrations] Before it runs anything, `db migrate` checks that the database's marker names a contract state that one of your migrations starts or ends at, in every contract space. When it does not, the command fails with `MIGRATION.MARKER_MISMATCH` and changes nothing. The error's `why` says what moved the database there, such as a migration that is no longer on disk or a `db update`. Its next actions give two ways back, and neither resets the database: `db update` for a database whose migration history does not need to be kept, or new migrations for a database that changes only through migrations, such as production. [Drift](https://www.prisma.io/docs/orm/migrations/rollbacks-and-recovery#drift-when-the-database-isnt-where-migrations-left-it) walks through both. ## When an apply fails [#when-an-apply-fails] Each operation checks the database before and after it runs, as [How migrations work](https://www.prisma.io/docs/orm/migrations/how-migrations-work#every-operation-checks-itself) explains. When a check fails, `db migrate` stops and its `why` says which check failed and, when the check names one object, what the database already has or lacks: ```text ✘ [MIGRATION.PRECHECK_FAILED] Operation table.user failed during precheck: ensure table "user" does not exist why: Before operation table.user runs, it checks: ensure table "user" does not exist. That check failed: the database already has table "user". The failed apply changed nothing. ``` Some checks name no object, such as a check about data or a check in a migration planned before `8.0.0-rc.20`. For those, `why` says only "That check failed on this database." The `why` ends by saying whether the database changed. On PostgreSQL and SQLite a failed apply is rolled back, so it says "The failed apply changed nothing." MongoDB has no transaction around a migration, so once an operation has written anything it says "The operations that ran before the failure stay applied." Before `8.0.0-rc.20`, `db migrate` said a failed apply on MongoDB changed nothing even when earlier operations stayed applied. When the apply stopped in an extension's [contract space](https://www.prisma.io/docs/cli/migration-status#contract-spaces) rather than your own, the `why` also names it, ending with `The apply stopped in contract space "".`, and `meta.failingSpace` holds its id. After you fix the cause, run `db migrate` again: it skips the migrations that were applied and finishes the rest. With `--json`, the error's `meta` holds the same facts: ```json { "failedCheck": { "operationId": "table.user", "phase": "precheck", "description": "ensure table \"user\" does not exist", "expectation": { "expects": "absent", "object": "table \"user\"" } }, "failingSpace": "app", "databaseUnchanged": true } ``` `databaseUnchanged` is `true` when the database is exactly as it was before the apply, and `false` when changes stay. When the schema check after the last operation fails, `meta.schemaIssues` lists the differences, in the shape [`db verify`](https://www.prisma.io/docs/cli/db-verify#schema-differences-in-json-output) describes. `nextActions` lists each way to fix the failure as its own entry. A script reads its `kind`: * `run-command`: running this command alone fixes the failure, such as `prisma db sign` for a database that already matches the contract. * `edit-file`: a person edits a file first, such as the contract source or a migration's `migration.ts`. * `user-choice`: a person decides, because the step changes data or chooses between plans. ## Data lines [#data-lines] Without `--json`, standard output gets one line per applied migration, with these fields separated by tabs: `space`, `name`, `from`, `to`, and the number of operations run. With `--show`, it gets one line per migration that will run, with `space`, `name`, `from`, and `to`; there is no operation count before the run. `from` is empty for a migration that starts from the empty database. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ```bash npx prisma db migrate --show | cut -f2 ``` ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db schema (/docs/cli/db-schema) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Inspect a live database schema. Location: CLI > db schema `db schema` reads the live database schema and prints it as a tree, or as the result document with `--json`. The command is always read-only: it never writes a file and never changes the database. Use it when you need to inspect what Prisma ORM sees in the database before inferring, signing, updating, or debugging drift. ## Usage [#usage] #### bun ```bash bunx prisma db schema --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db schema --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db schema --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db schema --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ----------------- | ------------------------------------------------------ | | `--db ` | Connects to the database. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints machine-readable schema output. | ## Examples [#examples] #### bun ```bash bunx prisma db schema --db "$DATABASE_URL" bunx prisma db schema --db "$DATABASE_URL" --json > schema.json ``` #### pnpm ```bash pnpm prisma db schema --db "$DATABASE_URL" pnpm prisma db schema --db "$DATABASE_URL" --json > schema.json ``` #### yarn ```bash yarn prisma db schema --db "$DATABASE_URL" yarn prisma db schema --db "$DATABASE_URL" --json > schema.json ``` #### npm ```bash npx prisma db schema --db "$DATABASE_URL" npx prisma db schema --db "$DATABASE_URL" --json > schema.json ``` ## Data lines [#data-lines] `db schema` prints the tree on standard error and nothing on standard output, because the tree's shape depends on the database family. Use `--json` to read the schema in a script. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the data lines of the other commands. ## Column types [#column-types] On PostgreSQL and SQLite, the tree and the JSON output show each column's type as the database names it. In the JSON output, this text is the column's `typeText`: ```bash npx prisma db schema --db "$DATABASE_URL" --json | jq 'select(.kind == "result") | .envelope.result.schema.tables[].columns[].typeText' ``` On PostgreSQL, `typeText` is the full type name, such as `integer` or `character varying(20)`, not a short name such as `int4`. An enum is named as your contract names it, such as `My Mood`, or `app.status` for an enum outside the `public` schema. A type from a schema that is not on the search path keeps the schema name, such as `extensions.vector(3)` for a pgvector column. On SQLite, which Prisma ORM 8 supports as an [experimental package](https://www.prisma.io/docs/orm/supported-databases), `typeText` is the type the column was declared with, in lower case: a column declared `VARCHAR(255)` reads `varchar(255)`. If a script reads `nativeType` or `resolvedNativeType` from the JSON output, change it to read `typeText`, which has replaced both fields since `8.0.0-rc.19`. ## Related commands [#related-commands] Use [`contract infer`](https://www.prisma.io/docs/cli/contract-infer) when you want to turn a live schema into a starter PSL contract. Use [`db verify`](https://www.prisma.io/docs/cli/db-verify) when you want to compare the live schema with the emitted contract. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db sign (/docs/cli/db-sign) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Sign a database with the current Prisma ORM contract. Location: CLI > db sign `db sign` verifies that the live database satisfies the emitted contract and, if so, writes or updates the database signature. The signature records that this database instance matches a specific contract version. It signs every contract space: your application's contract, and the contract of each extension that ships one, such as pgvector or PostGIS. It verifies each space, then signs every space that verified, in one transaction on PostgreSQL and SQLite. A space that fails verification is not signed: the command prints its differences and exits with code `4`. A PostgreSQL extension the contract declares, such as pgvector's `vector`, is part of that check, so a database without it fails. A space whose head ref needs an invariant, an id a migration records when it runs, is refused with `MIGRATION.SIGN_INVARIANTS_MISSING` unless the database already records it, because only `db migrate` can run that migration; the error names the space and the missing invariants. It is safe to run more than once, and safe to run in CI or a deployment pipeline. Use it after importing or inferring an existing schema, or after a deployment flow that already applied the required database changes. After a successful signature, `db sign` also stores the signed contract as a snapshot and points the [ref](https://www.prisma.io/docs/cli/migration-ref) named `db` of each signed space at it, so the next [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) starts from the state you just signed instead of from an empty database. Unlike `db init` and `db update`, passing `--db` does not turn this off, because you normally sign the real database. Pass `--no-advance-ref` when you do not want the command to write a ref or a snapshot, for example in a deployment pipeline. ## Usage [#usage] #### bun ```bash bunx prisma db sign --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db sign --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db sign --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db sign --db "$DATABASE_URL" ``` ## Options [#options] | Argument or option | What it does | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `[contract]` | Signs against a specific contract state instead of the emitted contract. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, or [`^`](#contract-references). It refuses `@contract`, `@db`, and `@empty` with the error code `MIGRATION.REF_WRONG_GRAMMAR`. To sign against the contract in `contract.json`, leave the argument out. | | `--db ` | Connects to the database. | | `--contract ` | The same value as `[contract]`, passed as an option in place of the argument. | | `--advance-ref ` | Advances this ref instead of `db` after a successful signature. | | `--no-advance-ref` | Signs without writing any ref or snapshot. Cannot be combined with `--advance-ref`. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result, with one outcome per contract space. See [JSON output](#json-output). | ### Contract references [#contract-references] A ref name is a name you gave a contract state with [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref), such as `prod`. `^` is a migration directory name followed by `^`, and it names the contract state before that migration, while the directory name alone names the state after it. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) lists the forms for every command. ## Exit codes [#exit-codes] | Code | Meaning | | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `0` | Every contract space was signed. | | `2` | The command could not run: unresolvable contract reference, no emitted contract, or unreachable database. Also used when it signed the database but could not write every ref. | | `4` | Schema verification failed for a space, or another process changed that space's signature while `db sign` ran. That space's signature was not written. | ## Data lines [#data-lines] Without `--json`, standard output gets one line per contract space, with these fields separated by tabs: `space`, `status`, and the storage hash of the space's contract. `status` is the same value as in the JSON output below. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ```bash npx prisma db sign --db "$DATABASE_URL" | cut -f1,2 ``` ## JSON output [#json-output] With `--json`, `db sign` prints one JSON object per line, as every command does (see [JSON output](https://www.prisma.io/docs/cli/configuration#json-output)). The last line has `"kind": "result"`, and its `envelope.result` is this document: ```json title="db sign --json output" { "ok": true, "summary": "Database signed", "spaces": [ { "space": "app", "status": "updated", "contract": { "storageHash": "…", "profileHash": "…" }, "previous": { "storageHash": "…", "profileHash": "…" } } ], "advancedRefs": [{ "space": "app", "name": "db", "hash": "…" }] } ``` `spaces` has one entry per contract space, with the hashes of its contract in `contract`. `status` is one of: | Status | Meaning | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `created` | The space had no signature, and now has one. | | `updated` | The signature held other hashes, now in `previous`. | | `unchanged` | The signature already held the contract's hashes. | | `failed` | Verification failed. The entry has `schema`, the verification result, and `ok` is `false`. | | `conflict` | Another process, such as `db migrate`, changed the signature while `db sign` ran. The entry has `expected` and `found`, the hashes `db sign` read and the ones it found. Run `db sign` again once that process has finished. | `advancedRefs` lists each ref the command moved. It is empty with `--no-advance-ref`. When a space fails verification, the `--json` output has a diagnostic with the code `CONTRACT.SCHEMA_VERIFICATION_FAILED`, and its `meta.schemaIssues` lists the differences. [Schema differences in JSON output](https://www.prisma.io/docs/cli/db-verify#schema-differences-in-json-output) describes each field. Since `8.0.0-rc.15`, the document has this shape. Before, it was `{ ok, summary, contract, target, marker }` for the application's space only. ## Example [#example] #### bun ```bash bunx prisma contract emit bunx prisma db sign --db "$DATABASE_URL" bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma db sign --db "$DATABASE_URL" pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract emit yarn prisma db sign --db "$DATABASE_URL" yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract emit npx prisma db sign --db "$DATABASE_URL" npx prisma db verify --db "$DATABASE_URL" ``` ## Adopting an existing database [#adopting-an-existing-database] After [`contract infer`](https://www.prisma.io/docs/cli/contract-infer) and `contract emit`, one `db sign` is enough to hand the database over to Prisma ORM: #### bun ```bash bunx prisma db sign --db "$DATABASE_URL" bunx prisma migration plan --name add-users-bio ``` #### pnpm ```bash pnpm prisma db sign --db "$DATABASE_URL" pnpm prisma migration plan --name add-users-bio ``` #### yarn ```bash yarn prisma db sign --db "$DATABASE_URL" yarn prisma migration plan --name add-users-bio ``` #### npm ```bash npx prisma db sign --db "$DATABASE_URL" npx prisma migration plan --name add-users-bio ``` The plan starts from the signed contract, so it contains only the change you made after signing. Because `migrations/app/` is still empty, that first plan also writes a baseline package that records the schema you adopted; see [the automatic baseline](https://www.prisma.io/docs/cli/migration-plan#the-automatic-baseline). ## 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 an existing database * a manually reviewed migration flow * a database restore that you need to mark as matching the current contract * a Prisma ORM upgrade that changes your contract's storage hash but not the database When you upgrade from a release before `8.0.0-rc.19` and emit the contract again, the contract's storage hash can change even though the database does not. The storage hash is the `storageHash` value in `contract.json`, and `db sign` records it in the database. It changes for these contracts: * a SQLite contract with a datetime or JSON column * a PostgreSQL contract whose defaults `contract emit` now writes in another form * a contract that used `@noCheck`, which this release removes Until you sign, the database still holds the old hash, so `db migrate` fails with `MIGRATION.MARKER_MISMATCH` and `db verify` fails with `CONTRACT.MARKER_MISMATCH`. So after you emit the new contract, run `db sign` against every database that Prisma ORM 8 has already signed or migrated, which usually means development, staging, and production. Do not use `db sign` to hide drift. If verification fails, `db sign` writes no signature and offers two ways out. One changes the database: run `prisma db update` to make the database match the contract, then sign again. The other leaves the database as it is: change the contract source to describe the database, run `contract emit` again, then sign again. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db update (/docs/cli/db-update) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Update a database to match the current Prisma ORM contract. Location: CLI > db update `db update` compares the live database with the emitted contract and applies the changes that close the gap, whether or not the database was bootstrapped with `db init`. Use it for direct reconciliation when you do not need a checked-in migration package. ## Usage [#usage] #### bun ```bash bunx prisma db update --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db update --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db update --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db update --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--dry-run` | Shows planned operations without applying them. | | `--to ` | Updates to a specific contract state. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, or [`^`](#contract-references). It refuses `@contract`, `@db`, and `@empty` with the error code `MIGRATION.REF_WRONG_GRAMMAR`. To update to the contract in `contract.json`, leave out `--to`. | | `--rename :` | Renames a namespace, a model or a field and keeps its rows, instead of dropping and creating it, or moves a model to another namespace. On PostgreSQL and SQLite, also renames an enum value in the rows that hold it, as in `--rename Status.ARCHIVED:Status.RETIRED`, a field of a value object, as in `--rename GeoPoint.lat:GeoPoint.latitude`, and a variant. Repeatable. See [Renames and data loss](#renames-and-data-loss). | | `--delete ` | Lets the update lose the data of a model, a field, a table no model stores, every model of a namespace the contract removed, or, on PostgreSQL and SQLite, an enum value the contract removed, a field of a value object, or the rows of a variant. Repeatable. | | `--convert ` | On PostgreSQL and SQLite, rewrites the stored discriminator value of a variant whose value changed. Repeatable. | | `--allow ` | Lets one operation change who can read or write the model's data. Repeatable. | | `--advance-ref ` | Advances the named [ref](https://www.prisma.io/docs/cli/migration-ref) to the post-command contract hash. Without it, `db update` advances `db` when `--db` is omitted, and advances nothing when `--db` is passed. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ### Contract references [#contract-references] A ref name is a name you gave a contract state with [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref), such as `prod`. `^` is a migration directory name followed by `^`, and it names the contract state before that migration, while the directory name alone names the state after it. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) lists the forms for every command. ## How the db ref moves [#how-the-db-ref-moves] Run without `--db`, `db update` takes the connection from `db.connection` in `prisma.config.ts` and advances the [ref](https://www.prisma.io/docs/cli/migration-ref) named `db` to the contract it just applied. Pass `--db` and that advancement is suppressed, even when the URL is the same one the config holds. Pass `--advance-ref db` alongside `--db` to get it back. The `db` ref is what [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) uses as its starting point when you do not pass `--from`. Passing `--db` only suppresses the advancement; it never removes a `db` ref that already exists. So a loop that always passes `--db` without `--advance-ref db` leaves the ref wherever it was last set, and the next `migration plan` starts from that stale contract. If the ref was never created, `migration plan` plans from an empty database while `migrations/app/` is empty, and refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` once migrations exist on disk. ## Renames and data loss [#renames-and-data-loss] Before it applies anything, `db update` asks one question for each model, field or table whose data the update would lose, such as a dropped column or a type change that can change values. Answer each one on the command line: * `--delete ` lets the data go. A subject is `Model`, `Model.field`, or, for data no model stores, its storage name, such as `public.audit_log`. * `--rename :` keeps the data. The update renames the table or column, and the constraints and indexes named after it, instead of dropping and creating it. Each side is `Model`, `namespace.Model`, `Model.field` or `namespace.Model.field`, and a field's model is named as the new contract names it: `--rename Profile:User --rename User.name:User.fullName`. It also asks before each operation that changes who can read or write a model's data, such as dropping a row-level-security policy or disabling row-level security. The question ends with "would widen who can read and write its data" or "would change who can read and write its data". Answer each with `--allow `; two such operations on one model take `--allow User --allow User`. A script reading `--dry-run --json` finds these operations in `accessChanges`, which before `8.0.0-rc.20` was named `accessWidening`. #### bun ```bash bunx prisma db update --db "$DATABASE_URL" --advance-ref db --no-interactive --delete Legacy --rename User.name:User.fullName ``` #### pnpm ```bash pnpm prisma db update --db "$DATABASE_URL" --advance-ref db --no-interactive --delete Legacy --rename User.name:User.fullName ``` #### yarn ```bash yarn prisma db update --db "$DATABASE_URL" --advance-ref db --no-interactive --delete Legacy --rename User.name:User.fullName ``` #### npm ```bash npx prisma db update --db "$DATABASE_URL" --advance-ref db --no-interactive --delete Legacy --rename User.name:User.fullName ``` In a terminal, the command asks the questions you did not answer with a flag. In a CI job or a run with `--no-interactive`, it fails with [`CLI.CONSENT_REQUIRED`](https://www.prisma.io/docs/cli/error-reference#CLI.CONSENT_REQUIRED) instead. The error lists each question still unanswered, and its next actions give the flags to add. A `--delete` or `--allow` that answers no question fails the run with `CLI.CONSENT_UNUSED`. To list the questions without applying anything, run with `--dry-run --json` and read `dataLoss` and `accessChanges`. `--confirm` does not answer them: only `--rename`, `--delete`, `--allow` or your answers in a terminal do. Dropping an index, a unique or foreign-key constraint, a check, a default or a native enum type loses no data, so the update asks nothing about it. `db update` names each subject by model and field from the contract the database was last updated to, which it stores when it advances a ref. With `--db`, pass `--advance-ref ` on every run so that contract is stored for the next run. Without a stored contract, each subject is its storage name, and a run with `--rename` fails with `MIGRATION.STATEMENT_ORIGIN_UNKNOWN`. Adding `--advance-ref` to that run does not help, because the missing contract is the one the database is at before it. To store it, emit the contract the database is at, run `db update --advance-ref db --dry-run` with the same `--db`, and check that it plans no operations. Then run it again without `--dry-run`, which changes nothing in the database and stores the contract. Then emit the new contract and run the rename. On PostgreSQL, a namespace is renamed, moved or removed with the same flags. `--rename billing:finance` renames the schema, and everything in it stays in it. `--rename public.Invoice:billing.Invoice` moves the model's table to another schema with its rows, constraints, indexes and policies, and creates the schema first when the database does not have it. Namespace renames run before the other renames, whatever order you give them in. `public` and a schema another contract space declares are not renamed. A namespace is a PostgreSQL schema that your contract declares with a `namespace` block. When you remove that block, the command asks about each model in the namespace, as it asks about any removed model. Answer with the flag that matches what you meant: * If you renamed the namespace, answer with `--rename billing:finance`. Nothing is dropped. * To keep one model's data, move it to a namespace the contract keeps, as in `--rename billing.Invoice:public.Invoice`. * To drop the namespace, answer with `--delete billing`. This answers for every model in it, and drops its tables and the schema. The schema can also hold objects that no contract declares. A table created by hand is asked about by its storage name, as in `--delete billing.audit_log`, because `--delete billing` does not answer for it. Any other such object, such as a view or a function, makes the run fail before it changes anything. The error names each object, so drop or move it yourself, then run the command again. The command leaves alone a schema that no contract declared, such as Supabase's `auth`, and a namespace that only another contract space declares. Before `8.0.0-rc.20`, the command did not ask about a removed namespace and left its tables in place. On PostgreSQL and SQLite, removing a member from an `enum` block, or changing the value a member stores, is asked about too, because rows may hold the old value. The update asks once for each value, however many columns hold it: * If you renamed the member, answer with `--rename Status.ARCHIVED:Status.RETIRED`. The update changes the stored value in every column and list that holds it. * To let the value go, answer with `--delete Status.ARCHIVED`. Optional columns that hold it are set to `NULL`, and lists lose it. A required column cannot take `NULL`, so while any of its rows hold the value, the apply fails with `MIGRATION.PRECHECK_FAILED` before it changes anything. The error counts those rows and says how to keep them. A member you rename while keeping its stored value, such as `RETIRED = "archived"` in place of `ARCHIVED = "archived"`, changes no rows, so nothing is asked. A member that keeps its name but stores a new value, and two members that swap their stored values, can only be answered with `--delete`. `db update` cannot keep those rows in one run. Its question says to plan the change with [`migration plan --from `](https://www.prisma.io/docs/cli/migration-plan#renames-and-data-loss) instead, or, for a member that keeps its name, to rename it to a new member and back in two runs of `db update`. For a swap, only the migration works. Native PostgreSQL enums (`pg.enum(...)`) are not affected. Before `8.0.0-rc.21`, PostgreSQL failed at apply when a row held the removed value, and SQLite planned nothing. On PostgreSQL and SQLite, a field of a [value object](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#value-objects) is asked about too when the contract renames it, removes it, or makes it required. Name the field through its value object, such as `GeoPoint.lat`, not through a model. Each statement acts on every column that holds the value object, including lists of it and value objects nested in another: * `--rename GeoPoint.lat:GeoPoint.latitude` renames the key in every stored object. * `--delete GeoPoint.lng` removes the key from every stored object. * An enum value inside a value object is asked about as the enum value. `--rename Status.ARCHIVED:Status.RETIRED` rewrites it wherever it is stored, and `--delete Status.DRAFT` sets an optional field that holds it to JSON `null` and takes it out of a list. * A field that becomes required gets a temporary value, such as `""`, `0`, `false` or `[]`, in every stored object that lacks the key or holds JSON `null` there, when the field's type takes one. A stored object that already holds a value keeps it. A field whose type takes none of them, such as a `DateTime`, is refused. To fill it with a value of your own, plan the change with [`migration plan --backfill`](https://www.prisma.io/docs/cli/migration-plan#renames-and-data-loss) instead. A [variant](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#base-models-and-variants) whose discriminator value changes, or that the contract removes, is asked about as a model: * `--convert Bug` rewrites the old value to the new one in the base table's discriminator column. * `--rename Bug:Defect` of a variant whose value also changed rewrites the value in the same way. * `--delete Bug` deletes the rows that hold the old value, then drops a removed variant's own table or the columns only it used. On MongoDB, `--rename` of a value object field or of a variant whose discriminator value changes is refused, and so is `--convert` of a variant. On MongoDB, a model rename renames its collection and keeps its documents, indexes and validator, and a field rename renames the field in every document that holds it. `--rename` and `--delete` name fields by their names in the schema, not by the names they are stored under. Removing a field from a model removes it from every document that holds it, so the update asks about it: answer with `--delete .`, or with `--rename`. Without a stored contract, the field is named by its collection, as in `--delete profiles.nickname`. On PostgreSQL and SQLite, a type change that can lose values is answered with `--delete `, which lets the database's own cast run; it may cut or round values, and a value it cannot cast fails the update. To write the conversion yourself, use [`migration plan --convert`](https://www.prisma.io/docs/cli/migration-plan#type-changes-and-required-fields) instead. ## Recommended flow [#recommended-flow] #### bun ```bash bunx prisma contract emit bunx prisma db update --db "$DATABASE_URL" --dry-run bunx prisma db update --db "$DATABASE_URL" --advance-ref db bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma db update --db "$DATABASE_URL" --dry-run pnpm prisma db update --db "$DATABASE_URL" --advance-ref db pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract emit yarn prisma db update --db "$DATABASE_URL" --dry-run yarn prisma db update --db "$DATABASE_URL" --advance-ref db yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract emit npx prisma db update --db "$DATABASE_URL" --dry-run npx prisma db update --db "$DATABASE_URL" --advance-ref db npx prisma db verify --db "$DATABASE_URL" ``` Use `--dry-run` before applying changes in shared environments. ## Data lines [#data-lines] `db update` prints nothing on standard output. Its exit code is the result, and `--json` carries the plan and what ran. The `--json` output is one JSON object per line, and the result is on the line whose `kind` is `result`: ```bash npx prisma db update --db "$DATABASE_URL" --dry-run --json | jq 'select(.kind == "result") | .envelope.result.dataLoss' ``` [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the data lines of the other commands. ## When to use migrations instead [#when-to-use-migrations-instead] For reviewable database changes in version control, use [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) and [`db migrate`](https://www.prisma.io/docs/cli/db-migrate). Use `db update` on any database whose migration history does not need to be kept, such as a local, development, preview, or staging database, shared or not. A database that changes only through migrations, such as production, must not use it, because it leaves no migration behind. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # db verify (/docs/cli/db-verify) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Verify a database against the current Prisma ORM contract. Location: CLI > db verify `db verify` checks whether the database marker and live schema match your emitted contract. It verifies the marker first, then checks the schema. Use it in CI and deployment checks before application code that depends on a contract reaches users. ## Usage [#usage] #### bun ```bash bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db verify --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ----------------- | --------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--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. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints machine-readable output. | ## Exit codes [#exit-codes] | Code | Meaning | | ---- | ---------------------------------------------------------------------------------------------- | | `0` | The database matches the contract. | | `2` | The check could not run: conflicting mode flags, no emitted contract, or unreachable database. | | `4` | Drift or a marker finding. | ## Examples [#examples] #### bun ```bash bunx prisma db verify --db "$DATABASE_URL" bunx prisma db verify --db "$DATABASE_URL" --strict bunx prisma db verify --db "$DATABASE_URL" --schema-only bunx prisma db verify --db "$DATABASE_URL" --marker-only ``` #### pnpm ```bash pnpm prisma db verify --db "$DATABASE_URL" pnpm prisma db verify --db "$DATABASE_URL" --strict pnpm prisma db verify --db "$DATABASE_URL" --schema-only pnpm prisma db verify --db "$DATABASE_URL" --marker-only ``` #### yarn ```bash yarn prisma db verify --db "$DATABASE_URL" yarn prisma db verify --db "$DATABASE_URL" --strict yarn prisma db verify --db "$DATABASE_URL" --schema-only yarn prisma db verify --db "$DATABASE_URL" --marker-only ``` #### npm ```bash npx prisma db verify --db "$DATABASE_URL" npx prisma db verify --db "$DATABASE_URL" --strict npx prisma db verify --db "$DATABASE_URL" --schema-only npx prisma db verify --db "$DATABASE_URL" --marker-only ``` Use JSON output in automation: #### bun ```bash bunx prisma db verify --db "$DATABASE_URL" --json ``` #### pnpm ```bash pnpm prisma db verify --db "$DATABASE_URL" --json ``` #### yarn ```bash yarn prisma db verify --db "$DATABASE_URL" --json ``` #### npm ```bash npx prisma db verify --db "$DATABASE_URL" --json ``` `db verify` prints nothing on standard output, even when piped. Its exit code is the result of the verification, and `--json` carries the findings. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the data lines of the other commands. ## 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. With `--strict`, tables that no contract declares are reported as `CONTRACT.SCHEMA_VERIFICATION_FAILED`, and the result's `unclaimed` list names them. Before `8.0.0-rc.15` they were reported as `CONTRACT.MARKER_REQUIRED`, which now only means the database has not been signed. | | Extension mismatch | The contract requires an extension pack that is not wired in the config. | | Missing PostgreSQL extension | The contract declares a PostgreSQL extension, such as `pg_trgm`, that the database does not have. | Fix the database or contract, emit again if needed, then verify again. ### Schema differences in JSON output [#schema-differences-in-json-output] When the live schema does not match the contract, the `--json` output has a diagnostic with the code `CONTRACT.SCHEMA_VERIFICATION_FAILED`. Its `meta.space` names the contract space. Its `meta.schemaIssues` lists each difference as an object with these keys: * `path`: where the difference is, as a list of names, such as `["public", "users", "email"]`. * `expected`: what the contract has. A missing object has only `expected`. * `actual`: what the database has. An extra object has only `actual`, and a mismatch has both. * `explanation`: an optional object with a `text`. The diagnostic's `why` lists the same differences as text. `db init`, `db update` and `db migrate` report `MIGRATION.SCHEMA_VERIFY_FAILED` with the same `meta.schemaIssues`. Before `8.0.0-rc.20`, the key was `meta.issues`, a list of strings such as `"missing: public/users/email"`, so update any script that reads it. ## How column types are compared [#how-column-types-are-compared] `db verify` treats two ways of writing the same column type as equal. So `Decimal(precision: 10)` in your contract matches a `numeric(10,0)` column, and `String(storage: varchar, length: 20)` matches `character varying(20)`. The migration planner compares types the same way, so neither command reports a difference that is only in how a type is written. When a database column has a type that Prisma ORM has no type for, either for your database or in the extensions listed in `prisma.config.ts`, the message says so: ```text The database column is "point", which no data type in the configured stack declares. ``` "The configured stack" in the message means your database and those extensions. Add the extension that provides the type to your config, or declare the column in your contract with ``Raw(sql`point`)``. ## How PostgreSQL defaults are compared [#how-postgresql-defaults-are-compared] When a column default is a literal value, `db verify` reads it as a value before it compares it with your contract, so the casts PostgreSQL adds when it prints the default do not cause a difference. This covers numbers such as `'-1'::integer` and `(5)::smallint`, text and enum values, including an enum value cast to a type in another PostgreSQL schema, `timestamp` values, `true`, `false`, `NULL`, JSON, and lists written as `'{...}'` or `ARRAY[...]`. `db verify` also recognizes `now()`, `clock_timestamp()`, `gen_random_uuid()`, and a sequence default, which it treats as `autoincrement()`. Any other default is a SQL expression, which you write in your contract as a `sql` default, such as ``@default(sql`(now() + '00:03:00'::interval)`)``. [Default values](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#default-values) shows how to write one. `db verify` cannot work out whether two SQL expressions give the same value, so it compares their text, ignoring letter case and spaces. PostgreSQL often rewrites an expression when it stores it, for example by adding casts, so write a `sql` default in your contract the way PostgreSQL stores it. To see that form, run `npx prisma contract infer --output ./inferred.prisma` and copy the column's `@default` from that file. When a `sql` default fails the check because PostgreSQL stores it in another form, the message shows both texts and the `sql` literal to write: ```text The database reads this default back as sql`(now() - '1 day'::interval)`; the contract declares sql`now() - interval '1 day'`. The database may store a default expression in its own form, so the two can mean the same. If they do, write the default as sql`(now() - '1 day'::interval)`. ``` Check constraints and the `WHERE` clause of a partial index are compared more strictly than `sql` defaults: their text must match exactly, including letter case and spaces. If `db verify` reports a difference in a `timestamptz` value inside a check constraint or a partial index's `WHERE` clause, check whether your contract was inferred before `8.0.0-rc.12` from a server that was not set to UTC. `db verify` reads the database with the time zone set to UTC and dates in ISO format, whatever the server or your database role sets, so a value that your contract has in another time zone no longer matches as text. To fix it, copy the new text from a fresh `npx prisma contract infer --output ./inferred.prisma` into your contract, emit the contract, and run `db sign`. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # deploy (/docs/cli/deploy) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Deploy a Composer application to Prisma Compute, to production or another environment. Location: CLI > deploy `deploy` deploys a [Prisma Composer](https://www.prisma.io/docs/composer) application to [Prisma Compute](https://www.prisma.io/docs/compute). It loads the module whose default export is the application root, named by `entry` in the `composer` section of `prisma.config.ts`, typically `./module.ts`. The command streams the deploy pipeline's own output to the terminal. `deploy` and [`dev`](https://www.prisma.io/docs/cli/dev) are root-level commands of the unified Prisma CLI. There is no `composer` command group. By default, the command uses the credentials from your existing `auth login` session. In CI or other headless environments, set `PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` instead. See [Deploying](https://www.prisma.io/docs/composer/deploying#credentials) for details. The first deploy of an app creates its project in your workspace, and a new project needs a region. Set it once, either as `prismaCloud({ region: 'us-east-1' })` in your deploy config or as the `PRISMA_REGION` environment variable; without one, the deploy stops with `project "" does not exist yet and no deploy region is configured`. A project that already exists keeps its region and needs neither. The region ids are listed under [Limitations](https://www.prisma.io/docs/compute/limitations). The `deploy` command does not build your application. Run your build command before deploying. ## Usage [#usage] #### bun ```bash bunx prisma deploy bunx prisma deploy --environment feat-auth ``` #### pnpm ```bash pnpm prisma deploy pnpm prisma deploy --environment feat-auth ``` #### yarn ```bash yarn prisma deploy yarn prisma deploy --environment feat-auth ``` #### npm ```bash npx prisma deploy npx prisma deploy --environment feat-auth ``` ## Flags [#flags] | Flag | Description | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--entry ` | Deploy the app from this module instead of the `entry` in `prisma.config.ts` | | `--name ` | Override the application name for this deploy. It defaults to the name of the exported application, and that name selects the project in your workspace: a project this module deployed before is reused, and a same-name project whose hosted state cannot be verified stops the deploy with `HostedStateBootstrapError`, so pass `--name` when the default would land in a project you did not mean to deploy into | | `--environment ` | The environment to deploy to (default: `production`). Any other name is a complete, isolated copy of the app, such as `staging` or one per pull request. Must be a valid git ref name | | `--report ` | Write the deploy's outcome as JSON to this path: resources, preview URLs, and the failure cause. Also settable as `PRISMA_COMPOSER_REPORT_FILE` | | `--build-id ` | Join the deploy record your CI already created rather than letting the target create one | ## Global flags [#global-flags] The Prisma CLI's global flags also apply: `--format`, `--json`, `--log-level`, `--verbose`, `--quiet`, `--yes`, `--confirm`, `--interactive`, `--color`, and `--config`. ## Environment variables [#environment-variables] | Variable | Description | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PRISMA_SERVICE_TOKEN` | A workspace service token from the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=cli), for CI and other headless environments. When unset, the command uses your stored `auth login` session | | `PRISMA_WORKSPACE_ID` | The workspace ID from the workspace's settings; pair it with the service token | | `PRISMA_REGION` | The region for a project this deploy creates; `prismaCloud({ region })` in the deploy config wins when both are set. Ignored once the project exists | | `PRISMA_COMPOSER_REPORT_FILE` | Path to write the deploy's JSON outcome report; the `--report` flag wins when both are set | ## Tearing down and log tailing [#tearing-down-and-log-tailing] The unified CLI has no `destroy` or `log` command. Both operations are available in-process through the control API below: `destroy` takes a required `environment` (production is `environment: 'production'`), and `log` tails a locally running application. ## The control API [#the-control-api] Everything the CLI does is also callable in-process, from `@prisma/composer/control`: typed `deploy`, `destroy`, `dev`, and `log` operations that return structured results instead of printing and exiting: ```ts import { fileURLToPath } from 'node:url'; import { deploy } from '@prisma/composer/control'; import prismaConfig from './prisma.config.ts'; const result = await deploy({ environment: 'pr-42', config: { value: prismaConfig.composer, file: fileURLToPath(new URL('./prisma.config.ts', import.meta.url)), }, }); if (!result.ok) console.error(result.failure.message); ``` Every operation takes a required `config`: the `composer` section of your `prisma.config.ts` and the path of the file that declares it. `deploy`'s `environment` defaults to `production`; `destroy`'s is required. Operations return `{ ok: true, value }` or `{ ok: false, failure }`. Failures come back as structured errors with a dotted `failure.code` and the same fix-naming `message` the CLI renders. The deploy engine's live output still streams to your process's stdio; the operations do not capture it. The operations authenticate with `PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` only. They do not read the session stored by `auth login`, so a script that runs fine next to the CLI's `deploy` fails under the control API with `environment variable PRISMA_WORKSPACE_ID is required` until both variables are exported. ## Next steps [#next-steps] * [`dev`](https://www.prisma.io/docs/cli/dev): run the same application locally, with no credentials. * [Getting started](https://www.prisma.io/docs/composer/getting-started): the commands in a working flow. * [Deploying](https://www.prisma.io/docs/composer/deploying): environments, CI, and what a deploy prints. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # dev (/docs/cli/dev) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Bring a Composer application up entirely on this machine, with no cloud credentials. Location: CLI > dev `dev` brings a [Prisma Composer](https://www.prisma.io/docs/composer) application up entirely on this machine. It loads the module whose default export is the application root, named by `entry` in the `composer` section of `prisma.config.ts`, typically `./module.ts`. The command runs credential-free against local emulators, programs on your machine that stand in for Prisma Compute, Prisma Postgres, and buckets. It watches the built output and restarts a service when its build changes. See [Local development](https://www.prisma.io/docs/composer/local-development). Like [`deploy`](https://www.prisma.io/docs/cli/deploy), `dev` runs your *built* output, so build first. ## Usage [#usage] #### bun ```bash bunx prisma dev bunx prisma dev --fresh bunx prisma dev --environment test --fresh bunx prisma dev --detach bunx prisma dev url my-app.gateway bunx prisma dev stop ``` #### pnpm ```bash pnpm prisma dev pnpm prisma dev --fresh pnpm prisma dev --environment test --fresh pnpm prisma dev --detach pnpm prisma dev url my-app.gateway pnpm prisma dev stop ``` #### yarn ```bash yarn prisma dev yarn prisma dev --fresh yarn prisma dev --environment test --fresh yarn prisma dev --detach yarn prisma dev url my-app.gateway yarn prisma dev stop ``` #### npm ```bash npx prisma dev npx prisma dev --fresh npx prisma dev --environment test --fresh npx prisma dev --detach npx prisma dev url my-app.gateway npx prisma dev stop ``` ## Commands [#commands] | Command | Description | | ------------------- | ----------------------------------------------------------------------------- | | `dev` | Run the app on this machine and watch it for changes until you press `Ctrl-C` | | `dev url
` | Print where a service, database, or bucket of the app answers locally | | `dev stop` | Stop the app that `prisma dev` ran from this directory | `dev url`, `dev stop`, and `--detach` are in `prisma` since `8.0.0-rc.24`. Check your version with `npx prisma --version`. ## Flags [#flags] | Flag | Description | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--entry ` | Load the app from this module instead of the `entry` in `prisma.config.ts` | | `--name ` | Run the app under this name instead of the name its root module declares. A different name gets its own local services, databases, and buckets | | `--environment ` | The environment to run as (default: `dev`). Each environment is a separate local copy of the app, so a second one, such as `test`, runs alongside `dev` and leaves its data alone | | `--fresh` | Before starting, delete this app's local services, databases, and buckets in the environment, with their data. Other apps and environments keep theirs | | `--detach` | Return once every service answers, and leave the app running without watching for changes. `prisma dev stop` stops it. Use it in scripts, agents, and CI | `dev` needs no credentials or environment variables; local runs never talk to the platform. When `dev` ends, by `Ctrl-C` or a failure, it stops the app's service processes and local Postgres servers. The emulators themselves keep running. Their data and ports are kept, so the next `dev` in this directory starts with the same ports and data. With `--detach`, `dev` prints the same `ready` line and service URLs as a foreground run, then exits with code `0` and leaves the app running. It does not pick up rebuilds: run `prisma dev --detach` again after a build, or run `prisma dev` in the foreground, which takes over the running app and watches it. If a detached start fails before every service answers, `dev` stops the whole app and exits non-zero. `--detach` combines with `--fresh`, `--name`, and `--environment`. Give `dev url` and `dev stop` the same `--environment`. ## dev url [#dev-url] `dev url
` prints the local URL of one node of the app that `prisma dev` runs from the current directory, in the environment `dev` unless you pass `--environment`. A node is a service, database, or bucket in the app, and its address is its path from the app's name, with dots between the names, such as `my-app.gateway` or, for a database inside a `catalog` module, `my-app.catalog.database`. #### bun ```bash bunx prisma dev url my-app.gateway ``` #### pnpm ```bash pnpm prisma dev url my-app.gateway ``` #### yarn ```bash yarn prisma dev url my-app.gateway ``` #### npm ```bash npx prisma dev url my-app.gateway ``` ```text no-copy ✔ The service my-app.gateway is running at http://localhost:3001 ``` | Node | What `dev url` prints | | -------- | ------------------------------------------------- | | Service | `http://localhost:` | | Database | Its connection string, with its local credentials | | Bucket | Its S3 endpoint followed by `/` | That line is for you to read. When standard output is a pipe or a file, or `$(...)` captures it, `dev url` writes the URL alone, so a script can use it directly. Check the exit status before using it, so a failure does not run the next command with an empty URL: ```bash url=$(npx prisma dev url my-app.gateway) && curl "$url" ``` Run it from the directory you ran `prisma dev` in, while the app runs. It starts nothing: it reads what the last `prisma dev` in this directory recorded. With `--json`, it prints `{ address, kind, url, state }` instead. `dev url` prints a URL only for a node that is running, so something is listening at the URL it prints. Otherwise it fails with one of these codes: | Code | Meaning | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DEV.NOT_STARTED_HERE` | `prisma dev` never ran that app in that environment in this directory | | `DEV.ENVIRONMENT_NAME_MISMATCH` | The environment's local folder belongs to an environment whose name differs only in case, such as `dev` for `--environment Dev` on macOS | | `DEV.ADDRESS_UNKNOWN` | The app has no node at that address. The message lists the addresses it has | | `DEV.EMULATOR_UNREACHABLE` | The emulator that runs the node is not running. Run `prisma dev` again, which starts it | | `DEV.NOT_RUNNING` | The node exists but is not running. Usually it was stopped, by `prisma dev stop` or by `prisma dev` ending. A service that keeps crashing is reported this way too, with the path of its log | ## dev stop [#dev-stop] `dev stop` stops the app that `prisma dev` ran from the current directory, in the environment `dev` unless you pass `--environment`: its service processes and local database servers, as `Ctrl-C` does in a foreground `prisma dev`. #### bun ```bash bunx prisma dev stop ``` #### pnpm ```bash pnpm prisma dev stop ``` #### yarn ```bash yarn prisma dev stop ``` #### npm ```bash npx prisma dev stop ``` Use it to stop an app started with `--detach`, or when `prisma dev` was killed without a chance to stop the app. It lists the services and databases it stopped. When nothing of the app was running, it prints `Nothing of was running.` and still exits with code `0`. Data and ports are kept, so the next `prisma dev` starts with the same ports and data. The emulators themselves keep running, because apps in other directories may use them. ## Global flags [#global-flags] The Prisma CLI's [global flags](https://www.prisma.io/docs/cli/global-flags) also apply: `--format`, `--json`, `--log-level`, `--verbose`, `--quiet`, `--yes`, `--confirm`, `--interactive`, `--color`, and `--config`. To tail the running application's merged logs, use the `log` operation of the [control API](https://www.prisma.io/docs/cli/deploy#the-control-api); the unified CLI has no `log` command. To see every local emulator and what runs on it, use [`emulator list`](https://www.prisma.io/docs/cli/emulator). ## Next steps [#next-steps] * [Local development](https://www.prisma.io/docs/composer/local-development): ports, what persists, and running in the background. * [`deploy`](https://www.prisma.io/docs/cli/deploy): the same application, on Prisma Compute. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # emulator (/docs/cli/emulator) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. List the local emulators that prisma dev runs your app on, and every instance they hold. Location: CLI > emulator Use `emulator` commands to inspect the local emulators. An emulator is a program on your machine that stands in for Prisma Compute, Prisma Postgres, or a bucket while [`prisma dev`](https://www.prisma.io/docs/cli/dev) runs a [Prisma Composer](https://www.prisma.io/docs/composer) app: one runs services, one runs Postgres databases, and one runs S3-compatible buckets. Each emulator holds instances, one for every service, database, or bucket that a `prisma dev` started, from any directory on the machine. The emulators keep running after `prisma dev` ends. An instance keeps its port and data until `prisma dev --fresh`, run from the directory that started it, deletes it. There is no command yet to remove the instances of a directory you deleted. `emulator list` is in `prisma` since `8.0.0-rc.24`. ## Usage [#usage] #### bun ```bash bunx prisma emulator list bunx prisma emulator list --json ``` #### pnpm ```bash pnpm prisma emulator list pnpm prisma emulator list --json ``` #### yarn ```bash yarn prisma emulator list yarn prisma emulator list --json ``` #### npm ```bash npx prisma emulator list npx prisma emulator list --json ``` ## Commands [#commands] | Command | Description | | --------------- | ----------------------------------------------------------------------------- | | `emulator list` | List every local emulator, whether it is running, and every instance it holds | ## emulator list [#emulator-list] `emulator list` works from any directory and needs no `prisma.config.ts`, because it describes the machine rather than one project. For each instance it shows the instance id, its URL, its state, and the node address and directory of the `prisma dev` that started it. #### bun ```bash bunx prisma emulator list ``` #### pnpm ```bash pnpm prisma emulator list ``` #### yarn ```bash yarn prisma emulator list ``` #### npm ```bash npx prisma emulator list ``` ```text no-copy ✔ Service emulator at http://127.0.0.1:4304 └─ svc_56b2c1618f6488d2 http://localhost:3001 running my-app.gateway in /Users/ada/my-app ✔ Database emulator at http://127.0.0.1:4305 └─ db_7cff71f83ae35c90 postgres://…:51650/template1?sslmode=disable running my-app.catalog.database in /Users/ada/my-app ℹ Bucket emulator (not running) ``` An emulator that is not running is listed with no instances. One that is running but does not answer, or answers with an error, is shown with that error, and the other emulators are still listed. When standard output is a pipe or a file, `emulator list` writes one line per instance, with six tab-separated fields: | Field | Value | | ----- | -------------------------------------------------------------------------------------- | | 1 | The emulator's kind: `service`, `database`, or `bucket` | | 2 | The instance id | | 3 | The instance's URL | | 4 | The instance's state | | 5 | The address of the node it runs, such as `my-app.gateway` or `my-app.catalog.database` | | 6 | The directory `prisma dev` ran from | The last two fields are empty for an instance that the emulator holds without a record of which app started it. For example, to print the URL of every running instance started from the current directory: ```bash npx prisma emulator list | awk -F '\t' -v dir="$PWD" '$4 == "running" && $6 == dir { print $3 }' ``` With `--json`, the result is `{ emulators: [{ kind, running, url, instances: [{ id, kind, url, state, labels }], error }] }`, where `url` is `null` for an emulator that is not running, and `error` is `null` unless the emulator is running but could not be listed. There is no `prisma emulator start` or `prisma emulator stop` yet, so to stop one app's services and databases, run [`prisma dev stop`](https://www.prisma.io/docs/cli/dev#dev-stop) from that app's directory. ## Global flags [#global-flags] The Prisma CLI's [global flags](https://www.prisma.io/docs/cli/global-flags) also apply: `--format`, `--json`, `--log-level`, `--verbose`, `--quiet`, `--yes`, `--confirm`, `--interactive`, `--color`, and `--config`. ## Next steps [#next-steps] * [`dev`](https://www.prisma.io/docs/cli/dev): run a Composer app on the emulators, and find or stop its services. * [Local development](https://www.prisma.io/docs/composer/local-development): how local services, databases, and buckets are kept per directory. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # Environment variables (/docs/cli/environment-variables) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. The environment variables the Prisma CLI reads, what each one does, and the release that added it. Location: CLI > Environment variables The `prisma` command reads these environment variables. Set them in your shell profile or in your CI configuration. For one command, put the variable in front of it, as in this [`contract emit`](https://www.prisma.io/docs/cli/contract-emit) run: ```bash title="Terminal" PRISMA_DISABLE_TELEMETRY=1 npx prisma contract emit ``` In PowerShell, set it for the session: ```powershell title="PowerShell" $env:PRISMA_DISABLE_TELEMETRY = "1" npx prisma contract emit ``` The CLI does not read `.env` files or `DATABASE_URL` itself. Your `prisma.config.ts` does that, and the one [`orm init`](https://www.prisma.io/docs/cli/orm-init) writes already loads `.env`; see [Configuration](https://www.prisma.io/docs/cli/configuration#config-file). > [!NOTE] > If you used the > > `prisma-next` > > preview command > > The `prisma` command ignores every `PRISMA_NEXT_*` variable, including `PRISMA_NEXT_DISABLE_TELEMETRY`. Drop the `NEXT_` part in shell profiles and CI: `PRISMA_NEXT_DISABLE_TELEMETRY` becomes `PRISMA_DISABLE_TELEMETRY`. > > Your `prisma-next` telemetry opt-out does not carry over either, so the one-time telemetry notice prints again. Run `prisma telemetry disable` to opt out. The `prisma` command stores that choice in `~/.config/prisma/config.json` (Windows: `%APPDATA%\prisma\config.json`). "Since" is the first `prisma` release that reads the variable. | Variable | What it does | Since | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `PRISMA_DISABLE_TELEMETRY` | Set to `1` to turn off anonymous [CLI telemetry](https://www.prisma.io/docs/cli/telemetry). Empty, `0`, and `false` leave it on. | 8.0.0-rc.1 | | `DO_NOT_TRACK` | Set to `1` to turn off telemetry. Other values do nothing. | 8.0.0-rc.1 | | `PRISMA_DEBUG` | Set to `1` to print the CLI's debug output to stderr. | 8.0.0-rc.1 | | `PRISMA_SKILLS_CHECK` | Set to `0` to silence the notice that your project's [agent skills](https://www.prisma.io/docs/cli/skills) are out of date. | 8.0.0-rc.9 | | `PRISMA_SERVICE_TOKEN` | A service token for a Prisma Platform workspace, created in the [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=cli). Only the [Platform commands](https://www.prisma.io/docs/cli#platform-commands) such as `auth`, `project`, and `deploy` use it, in place of a browser login, even if you are also logged in. | 8.0.0-rc.1 | | `PRISMA_WORKSPACE_ID` | The ID of the workspace the service token belongs to, from the workspace's settings in the Prisma Console. Set it alongside the token. | 8.0.0-rc.1 | | `NO_COLOR` | Set to any value to turn off colored output. The [`--color` and `--no-color` flags](https://www.prisma.io/docs/cli/global-flags) override it. | 8.0.0-rc.1 | | `CI` | Set to any value except `false` to mark the run as CI: no telemetry, no skills notice, and no interactive prompts. `CI=false` forces the non-CI behavior even when a CI system set it. | 8.0.0-rc.1 | Agent skills are files in your project, in `.claude/skills` and similar folders, that teach AI coding agents about Prisma. Silencing the notice does not update them; `prisma skills sync` does. You rarely need to set `CI` yourself: the CLI also detects the variables that CI providers such as GitHub Actions and GitLab CI set. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # Error reference (/docs/cli/error-reference) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. The structured error codes of the Prisma CLI platform commands, by namespace, with the condition that raises each one. Location: CLI > Error reference Every user-facing error the unified Prisma CLI emits is a structured envelope identified by a dotted `NAMESPACE.SUBCODE` code (see [Error Conventions](https://github.com/prisma/prisma-cli/blob/main/docs/product/error-conventions.md) and [ADR 0003](https://github.com/prisma/prisma-cli/blob/main/docs/architecture/adrs/0003-structured-output-and-errors.md)). This page lists the codes from every `prisma` command except the Prisma ORM ones. The codes from `prisma contract`, `prisma db`, `prisma migration`, and `prisma orm`, and the codes your app can raise at runtime, are on the [Prisma ORM error reference](https://www.prisma.io/docs/orm/reference/error-reference). When an error prints a `docsUrl`, that link opens the code's entry on this page. This page is generated from the `prisma/prisma-cli` repository. One exception: the `CLI.*` codes on this page come from the command-line layer that every `prisma` command runs through, for its arguments, for loading `prisma.config.ts`, for prompts, and for consent. They are on this page even when you ran a Prisma ORM command. `CLI.CONFIG_SECTION_INVALID` from `prisma contract emit` is one of them. The Prisma ORM commands also raise `CLI.*` codes of their own, and those are on the [Prisma ORM error reference](https://www.prisma.io/docs/orm/reference/error-reference). If a `CLI.*` code is not on this page, it is on the other. Recognize an error programmatically by running with `--json` and matching on `error.code` in the emitted envelope — never on message text. Envelopes carry `message`, and optionally `why`, `fix`, `where`, `meta`, `cause`, `nextActions`, and `docsUrl`. Most codes on this page are expected failures. Some are warn-severity diagnostics that ride a successful run: the command completes and exits `0`, and the diagnostic carries the code (the entry says so where it applies). The process exit-code contract is in [Error Conventions](https://github.com/prisma/prisma-cli/blob/main/docs/product/error-conventions.md). Codes raised by the command families the CLI mounts are listed here too, because the hosted reference is where their errors' docs links point. `pnpm check:error-reference` verifies only the codes in this repository's source, so a family's entries are kept current by hand when the CLI moves to a new release of that family. Every code on this page is assigned where the error is raised. No boundary invents a code from a server response or rewrites one on the way out, so an error's code never depends on which command you reached the failure through. When a REST API request fails, the CLI raises the domain's registered `*.API_ERROR` code and carries the API's own code and HTTP status in `meta.apiCode` and `meta.status`, where they are data you can read rather than a code you have to guess at. Namespaces on this page: * [`ADDRESS`](#address): Naming a Project, service, database or bucket by its address (`@:
`) instead of its id * [`AUTH`](#auth): Workspace authentication and sessions (`prisma auth`, credential resolution) * [`BRANCH`](#branch): Branch listing (`prisma branch`) * [`BUCKET`](#bucket): Bucket and bucket-key management (`prisma bucket`) * [`CLI`](#cli): Engine-level invocation: arguments, config loading, prompts, consent, credentials, child processes * [`CONFIG`](#config): The `composer` section of `prisma.config.ts` and its `config` and `secrets` adapters (`prisma dev`, `prisma deploy`) * [`DEPLOY`](#deploy): Deploying, listing and destroying a Composer app (`prisma deploy`, `prisma deploy list`, and the `deploy` and `destroy` operations of `@prisma/composer/control`) * [`DEV`](#dev): Running an app on this machine with Composer (`prisma dev`, `prisma dev url`, `prisma dev stop`, `prisma emulator list`) * [`FEEDBACK`](#feedback): Sending product feedback (`prisma feedback`) * [`GIT`](#git): Git repository connections (`prisma git`) * [`INIT`](#init): Project initialization diagnostics (`prisma init`) * [`POSTGRES`](#postgres): Database management (`prisma postgres`) * [`PROJECT`](#project): Project and environment management (`prisma project`) * [`SERVICE`](#service): Deployed service management (`prisma service`) * [`SKILLS`](#skills): Agent-skill delivery (`prisma skills`) ## ADDRESS [#address] These codes cover a subject written as `@`, an optional environment and `:`, then an address: the name the app gave a Project, service, database or bucket, such as `shop.api`. The environment is the one the app was deployed to: a Branch's git name, or production (the default Branch) when left out. Any project, service, postgres or bucket command given an address can fail with these codes before its own lookup runs, so an `ADDRESS` code can replace the group's own not-found code: a script that handles a missing database on `postgres delete` also needs to handle `ADDRESS.NOT_FOUND`. ### ADDRESS.AMBIGUOUS [#ADDRESS.AMBIGUOUS] An address matched more than one row: more than one Project in the workspace carries the app name as its logical id, or more than one service, database or bucket on the environment's branch carries the full address. The nextActions list the matching ids to pass instead. Meta: `address`, `matches` (the `id` and `name` of each match). ### ADDRESS.API_ERROR [#ADDRESS.API_ERROR] A REST API request made to look up an address (listing Projects, services, databases or buckets by logical id) failed. The `why` carries the API's message or HTTP status, and the fix is the API's hint when it sent one. A failed branch listing raises `BRANCH.API_ERROR` instead. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). ### ADDRESS.NOT_FOUND [#ADDRESS.NOT_FOUND] An address named nothing: no Project in the workspace has the app name as its logical id, the Project has no branch for the environment (no default branch for production, or no branch with that git name), or nothing on that branch has the address. The nextActions point at `prisma project list`, `prisma branch list`, or `prisma deploy list`. Meta: `address`, plus `app`, `environment`, `projectId`, `branchId` or `expected` as they apply. ### ADDRESS.USAGE_ERROR [#ADDRESS.USAGE_ERROR] A subject starting with `@` is not a valid address (an empty environment before `:`, an empty address, an empty part between dots, or whitespace), an address was combined with `--project` or `--branch`, which the address already names, or a project command was given an address with an environment, which a Project's address never has. Meta: `address`, plus `flags` for the flag conflict. ### ADDRESS.WRONG_KIND [#ADDRESS.WRONG_KIND] An address names a different kind of thing than the command acts on: a service, postgres or bucket command was given the bare app name (which names the Project) or the address of another kind of row, or a project command was given an address longer than the app name. The nextActions name the command group that acts on it. Meta: `address`, `expected`, `actual` (`project`, `service`, `database`, `bucket`, or `service, database or bucket` when a project command is given a longer address and the kind was not looked up). ## AUTH [#auth] ### AUTH.CREDENTIAL_WORKSPACE_MISMATCH [#AUTH.CREDENTIAL_WORKSPACE_MISMATCH] A credential's `workspace_id` claim disagrees with the workspace it is being stored under — raised by every CredentialManager (the CLI's file-backed manager and the engine's in-memory one) both when `createSession` receives a token claiming a different workspace and when a rotated token written back during refresh would re-scope an existing session. The fix is to run `prisma auth login` again and pick the intended workspace. Meta: none. ### AUTH.LOGIN_WORKSPACE_UNKNOWN [#AUTH.LOGIN_WORKSPACE_UNKNOWN] `prisma auth login` completed the browser sign-in but the minted credential carries no `workspace_id` claim, so no workspace session can be keyed by it. The fix is to sign in again and pick a workspace in the browser. Meta: none. ### AUTH.LOGIN_DENIED [#AUTH.LOGIN_DENIED] The OAuth callback reported `access_denied`. Authorization was not granted; this is an expected refusal, not a CLI crash. No session is created or cleared. Run `prisma auth login` again only to grant access intentionally. The callback description is not echoed. Meta: none. ### AUTH.NO_SESSION_FOR_WORKSPACE [#AUTH.NO_SESSION_FOR_WORKSPACE] A workspace reference matched none of the stored workspace sessions — raised by the command-side ref resolver behind `prisma auth workspace use` and `prisma auth workspace logout` (exact id match first, then case-insensitive name match), and by the credential managers when a session operation names a workspace with no stored record. Sessions are created only by `prisma auth login`, so the suggested fix is to sign in and pick that workspace in the browser; the workspace reference appears in the message, not in meta. Meta: none. ### AUTH.NO_WORKSPACE_SESSIONS [#AUTH.NO_WORKSPACE_SESSIONS] `prisma auth workspace use` was run with zero stored workspace sessions, so there is nothing to select among — the command only selects, it never creates a session or opens a browser. The fix is to run `prisma auth login` first. Meta: none. ### AUTH.SERVICE_TOKEN_EMPTY [#AUTH.SERVICE_TOKEN_EMPTY] The `PRISMA_SERVICE_TOKEN` environment variable is set but blank; a blank token authenticates nothing while still overriding stored workspace sessions, so the CLI surfaces it instead of silently ignoring it. It is raised identically wherever the environment credential is read — `activeCredential()`, the command needs check, and the engine's request path, including at the start of `prisma auth login` before a browser opens. The suggested actions are to unset the variable or set it to a valid service token. Meta: none. ### AUTH.SERVICE_TOKEN_REJECTED [#AUTH.SERVICE_TOKEN_REJECTED] The management API rejected (401) the service token supplied through `PRISMA_SERVICE_TOKEN`; such a token carries no refresh token and can never be renewed, and nothing stored is cleared. Built only through the shared `credentialRejectedError` dispatcher in the engine's API request path — the one place wording differs by credential origin (a stored session with the same failure gets `CLI.CREDENTIALS_REQUIRED` instead). `prisma auth whoami` fails with this code too rather than reporting the rejected token as signed in. The suggested action is to replace the variable with a valid service token or unset it to fall back to stored sessions. Meta: none. ### AUTH.SESSIONS_UNSUPPORTED [#AUTH.SESSIONS_UNSUPPORTED] A session mutation (`createSession`, `selectSession`, `endSession`, `endAllSessions`) was attempted on a host that uses the environment-only credential manager, whose sole credential source is `PRISMA_SERVICE_TOKEN` (plus `PRISMA_WORKSPACE_ID`) — such hosts, like composer's rebuilt CLI, hold no stored sessions, so there is nothing to create, select, or end. The suggested action is to set or change the environment variable instead. Meta: none. ### AUTH.USAGE_ERROR [#AUTH.USAGE_ERROR] A command that needs an active workspace found an authenticated credential that names no workspace — raised by the resource commands' `resolveActiveWorkspace` and the service commands' `requireWorkspace`, which read the engine's pinned credential; an environment token whose claims carry no workspace id is the usual cause. The suggested fix is to run `prisma auth login` and choose a workspace. Meta: none. ### AUTH.WORKSPACE_AMBIGUOUS [#AUTH.WORKSPACE_AMBIGUOUS] A user-typed workspace name matched more than one workspace, from two raise sites with different meta: the session-ref resolver behind `prisma auth workspace use`/`logout` when several stored sessions share the name (meta carries `workspaceIds` and `sessions`, each session holding `workspaceId` and a nullable `user`), and `prisma project transfer` when a `--to-workspace` reference matches several authenticated workspaces (meta carries `workspaceRef` and `matches`, each match holding `id`, `name`, `credentialWorkspaceId`). Both point the user at `prisma auth workspace list` to retry with an exact workspace id. Meta: `workspaceIds`, `sessions` (workspace commands) or `workspaceRef`, `matches` (project transfer). ### AUTH.WORKSPACE_NOT_AUTHENTICATED [#AUTH.WORKSPACE_NOT_AUTHENTICATED] `prisma project transfer` could not resolve the transfer recipient: the `--to-workspace` reference matched no stored OAuth session, or the matched recipient session proved invalid. The suggested fix is to run `prisma auth login` and authorize that workspace, after checking `prisma auth workspace list`. Meta: `workspaceRef`. ## BRANCH [#branch] ### BRANCH.API_ERROR [#BRANCH.API_ERROR] A REST API call made by `prisma branch list` failed. The `why` carries the API's message or, failing that, the HTTP status, and the fix suggests rerunning with `--log-level verbose` for the response details. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). ## BUCKET [#bucket] ### BUCKET.API_ERROR [#BUCKET.API_ERROR] A bucket REST API request (listing, creating, or deleting buckets or bucket keys) failed — raised by the provider (`lib/bucket/provider.ts`). The `why` carries the API's message or HTTP status, and the fix is the API's hint when it sent one. An HTTP 401 or 403 raises this code too, with a `why` saying the API rejected the request as unauthorized and a `prisma auth login` next action. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). ### BUCKET.KEY_SECRET_MISSING [#BUCKET.KEY_SECRET_MISSING] `prisma bucket key create` created the key, but the REST API response omitted part of the one-time credential payload (secret access key, access key id, endpoint, or bucket name), so the CLI cannot show credentials it will never see again. The fix is to create another key and store the returned credentials immediately. Meta: none. ### BUCKET.USAGE_ERROR [#BUCKET.USAGE_ERROR] A bucket subcommand was called without its required id argument: `bucket delete` and `bucket key create`/`bucket key list` need a bucket id, and `bucket key delete` needs both a bucket id and a key id. The nextActions point at `bucket list` (or `bucket key list`) to find the ids. Meta: none. ## CLI [#cli] ### CLI.ABORTED [#CLI.ABORTED] The run's abort signal fired before the command completed — a thrown abort error is recognized in settlement and reported as this code rather than as a bug. When the abort came from a delivered SIGINT/SIGTERM the run exits 130/143; an abort with no recorded signal (an engine-internal abort) exits 3. Meta: none. ### CLI.AUTH_SERVICE_ERROR [#CLI.AUTH_SERVICE_ERROR] The authentication service failed transiently while refreshing a stored OAuth session; the stored credentials are left untouched, and the guidance is to retry rather than sign in again, because the credentials themselves were not rejected. `prisma auth whoami` does not fail with this code: it answers from the credential's own claims and reports `verified: false`. Meta: none. ### CLI.BROWSER_WAIT_TIMEOUT [#CLI.BROWSER_WAIT_TIMEOUT] A `ctx.prompt.browserWait` flow (the command opened a URL and polled for the user to finish there) reached its timeout before the poll succeeded. `prisma git connect` catches this code from its GitHub-app install wait and rethrows a command-specific error, so consumers usually see it from other browserWait flows. Meta: `url`, `timeoutMs`. ### CLI.CHILD_PROCESS_FAILED [#CLI.CHILD_PROCESS_FAILED] Emitted only as a json-mode error envelope when a command that handed the terminal to a child process (`exitWithChildStatus`) saw that child exit non-zero or die on a signal; the run's exit code is the child's own status verbatim, not the CLI's usual 2. Meta: `exitCode`, `signal`. ### CLI.COMMAND_MOVED [#CLI.COMMAND_MOVED] The user typed a retired command path, or a retired flag on a surviving command, that the redirect table claims; instead of failing as unknown, the run names the replacement invocation as a run-command next action, with the retirement reason in `why` when one is recorded. Exits 2. Meta: none. ### CLI.CONFIG_MISSING_MARKER [#CLI.CONFIG_MISSING_MARKER] The evaluated `prisma.config.ts` default export carries no `$prismaConfig` version marker — most likely a Prisma ORM 7 config, which uses the same filename — so the loader stops rather than misread it; the fix is to wrap the exported object in `definePrismaConfig`. Raised by the config loader for any command with a `needs.config` section. The file's absolute path is in `where.path`. Meta: none. ### CLI.CONFIG_NOT_FOUND [#CLI.CONFIG_NOT_FOUND] The file `--config` named does not exist. Only an explicitly named file is an error — an absent `prisma.config.ts` found by discovery is fine, because section validators own absence and supply defaults. The path is in `where.path`. Meta: none. ### CLI.CONFIG_PARENT_CYCLE [#CLI.CONFIG_PARENT_CYCLE] A config file's explicit `parent` names a file that is already on the config chain, which would loop forever. Raised by the config loader while following the chain; the declaring file's absolute path is in `where.path` and the summary names both files. The fix is to point `parent` elsewhere or set it to `false`. Meta: none. ### CLI.CONFIG_PARENT_INVALID [#CLI.CONFIG_PARENT_INVALID] A config file declares `parent` with a value that is neither `false` nor a path string. Raised by the config loader while following the chain; the declaring file's absolute path is in `where.path`. Meta: none. ### CLI.CONFIG_PARENT_NOT_FOUND [#CLI.CONFIG_PARENT_NOT_FOUND] A config file's explicit `parent` names a file that does not exist. Naming a parent is deliberate, so its absence is an error — unlike discovery, where finding no file is fine. Raised by the config loader while following the chain; the declaring file's absolute path is in `where.path` and the summary names the missing target. Meta: none. ### CLI.CONFIG_FIELD_INVALID [#CLI.CONFIG_FIELD_INVALID] One field of a config section declared by schema failed that schema: the wrong type, a missing required field, or a value outside the declared set. The summary names the section and the field with arktype's description of the problem; `where.path` is the config file that declared the field's top-level key (so the file to fix on a chain), and `meta.section` and `meta.field` carry the names. Travels as an accompanying diagnostic under `CLI.CONFIG_SECTION_INVALID`. Raised by the engine's schema validation before the handler runs. Meta: `section`, `field`. ### CLI.CONFIG_SECTION_INVALID [#CLI.CONFIG_SECTION_INVALID] The config section a command declared in `needs.config` failed its validator; the individual problems travel as accompanying diagnostics on the envelope, and the summary names the section and the config file actually read (respecting `--config`). Raised by the engine's needs check before the handler runs. Meta: none. ### CLI.CONFIG_UNKNOWN_SECTION [#CLI.CONFIG_UNKNOWN_SECTION] The config file has a top-level key that is not a section any mounted command or command family declares; the set of section names is closed, so an unrecognized key is a typo or leftover the CLI refuses to silently ignore. The `why` lists the recognized section names, and the file path is in `where.path`. Raised by the engine's needs check, deliberately outside the host-replaceable loader. Meta: none. ### CLI.CONFIG_UNREADABLE [#CLI.CONFIG_UNREADABLE] Evaluating `prisma.config.ts` threw. Two variants share the code: when the error chain shows the `prisma/config` entry point could not be resolved (the prisma package missing from the project, or too old), the guidance is to install the prisma package matching the CLI's version; otherwise the summary carries the first line of the evaluation error and the fix is to repair the file. The path is in `where.path`. Meta: none. ### CLI.CONFIG_VERSION_UNSUPPORTED [#CLI.CONFIG_VERSION_UNSUPPORTED] The config file's `$prismaConfig` marker declares a version other than the one this CLI supports; the fix is to regenerate the config with a matching `definePrismaConfig` or update the CLI. The path is in `where.path`. Meta: none. ### CLI.CONSENT_REQUIRED [#CLI.CONSENT_REQUIRED] A consent prompt was reached under `--yes` or in a non-interactive session. Consent has no default answer and `--yes` does not grant it, so there is nothing for the run to assume. When the consent declares a token, the message and next action say to pass `--confirm `, and the token travels in meta; without a token, the only path is running the command interactively. Meta: `consentToken` (only when the consent declares a token). A statement prompt (`ctx.prompt.statement` or `ctx.prompt.statements`) raises the same code when no statement flag on the command line answers it. One error lists every question still unanswered: the summary names the subjects, `why` carries the questions, and the next actions give one flag to pass per verb, such as `--delete Legacy` or `--rename 'Legacy:'`. `why` also lists every given statement flag that names none of the questions' subjects, and any `--confirm` token, which answers no statement, so a misspelled flag is reported before anyone answers a prompt. Meta: `unanswered` (a list of `{ subject, verbs }`), plus `subject` and `verbs` when exactly one question is unanswered; `unmatched` (a list of `{ verb, values }`) and `confirm` (the tokens) when any. ### CLI.CONSENT_UNUSED [#CLI.CONSENT_UNUSED] A consent flag was given but answered nothing: a statement flag such as `--delete Legacy`, or a `--confirm` token. The summary says why for each flag: no statement prompt asked about that subject and no `ctx.statements.take` took it (usually a mistyped subject), the question about it was already answered by another flag (a flag given twice, or two verbs for one subject), or no consent in the run asked for that `--confirm` token. The `--confirm` case applies only to a command that declares statements, where such a token is certainly a mistake; elsewhere a leftover `--confirm` is still ignored until [prisma/prisma-cli#339](https://github.com/prisma/prisma-cli/issues/339) lands. `why` lists the subjects the run asked about. Raised when the handler returns from a run that would otherwise have succeeded, so a run that failed for another reason reports that reason only; or earlier, as soon as `ctx.prompt.statements(questions, { last: true })` has answered its questions, before the command acts. Exits 2. Meta: `unused` (a list of `{ verb, values }`), `confirm` (the unused `--confirm` tokens, when any), `asked` (the subjects asked about, when any). ### CLI.CREDENTIALS_LOCKED [#CLI.CREDENTIALS_LOCKED] The advisory lock on the stored-credentials file was held by another prisma process for longer than the wait timeout, so this run's credential mutation gave up; the fix is to wait for the other command and retry. Raised by the auth state file's lock helper in `packages/cli`. Meta: none. ### CLI.CREDENTIALS_REQUIRED [#CLI.CREDENTIALS_REQUIRED] The command needs a signed-in credential and none is usable. One constructor covers five reasons: not signed in at all, an expired session, a session expiring too soon for a command that hands credentials to a child process (which cannot refresh them), a workspace session that ended mid-run, and workspace sessions held with none selected as current. Raised identically by the engine's needs check, `ctx.activeCredential`, and the request path; next actions point at signing in or `prisma auth workspace use`. When `prisma auth whoami` meets this code during its identity lookup it reports `authenticated: false` with exit `0` instead of failing. Meta: none. ### CLI.CREDENTIALS_UNREADABLE [#CLI.CREDENTIALS_UNREADABLE] The stored-credentials file exists but could not be read (any read failure other than the file being absent, which yields empty state instead); the guidance is to check the file's permissions. The underlying error is attached as `cause`. Meta: none. ### CLI.INTERACTION_REQUIRED [#CLI.INTERACTION_REQUIRED] The session is not interactive (no TTY stdin, CI, or `--no-interactive`) and the command cannot proceed without a person. Two raise sites: the engine's needs check for a command declaring `needs.interaction`, and `ctx.prompt.browserWait`, which refuses to start a browser wait it could never finish — in that case the URL travels in the error so the user can finish there manually. Meta: `url` (browserWait raise only; none from the needs check). ### CLI.INTERNAL_ERROR [#CLI.INTERNAL_ERROR] A bug, not a user error: a non-structured throw from a handler, an engine invariant violation (undocumented exit code, malformed result), or a stricli internal failure that never settled. The summary is the first line of the underlying error message. Exits 1, the taxonomy's bug code, rather than the usual 2. Meta: none. ### CLI.INVALID_ARGUMENTS [#CLI.INVALID_ARGUMENTS] The invocation's arguments did not parse or contradict each other. Raise sites: stricli's argument-parse failure mapped at the adapter boundary (its usage text becomes summary and `why`), `--config=` given an empty value, a statement flag (such as `--delete`) given the wrong number of values for its declared arity or an empty value, `prisma init --skills` given `none` combined with agent names or an unknown agent name, and `prisma skills sync` given both `--disable` and `--enable`. Exits 2 as a usage error. Meta: none. ### CLI.MISSING_DEPENDENCY [#CLI.MISSING_DEPENDENCY] A command declared an optional peer dependency in `needs.dependencies` that does not resolve from the project; the engine probes with `require.resolve` and phrases the install command for the package manager it detected. Meta: `specifier`, `installCommand`. ### CLI.PACKAGE_MANAGER_FAILED [#CLI.PACKAGE_MANAGER_FAILED] A `ctx.packages` operation (an install, or running a package through the manager) exited non-zero — or nothing ran at all because the host wires no package-manager runner, recorded in `meta.reason`. The redacted command line is offered as a run-command next action so the user can run it themselves. Meta: `form`, `manager`, `command`, `exitCode`, `stderrTail`, `reason` (only when the runner is unavailable). ### CLI.PROMPT_CANCELLED [#CLI.PROMPT_CANCELLED] The user cancelled a prompt: EOF on stdin at a line-rendered prompt, a clack cancel (Ctrl-C at the prompt UI), a SIGINT or SIGTERM delivered while a prompt waits for input, an abort during a browserWait poll, Ctrl-C at the `prisma auth login` paste prompt, or — via the service commands' `userCancelledError` — consent declined interactively. Settles with exit 3, the cancellation code, instead of 2; a SIGTERM that cancels a waiting prompt settles 143 instead, because it ends the run as a delivered signal, while a SIGINT is the user declining, like Ctrl-C. After a signal has cancelled a prompt, every later prompt in the run is cancelled at once and a further signal force-exits. Meta: none. ### CLI.PROMPT_INVALID [#CLI.PROMPT_INVALID] An answer could not be interpreted: not a yes/no for a confirm, not one of a select's options with no default to fall back to, a consent token typed wrong where re-prompting is impossible (scripted answers or piped stdin — the interactive clack renderer re-prompts instead), or a statement answer the command rejected. A statement answer is rejected when a verb flag's value fails the command's check (re-prompting cannot correct a flag), or when a typed answer does not start with one of the verbs or fails the check where re-prompting is impossible; the summary carries the command's reason. Meta: `consentToken` (token-mismatch raise only). ### CLI.PROMPT_REQUIRED [#CLI.PROMPT_REQUIRED] A prompt with no declared default was reached where it cannot be shown — under `--yes` or in a non-interactive session — so the run halts; the fix is to run from an interactive terminal or pass a flag that answers the prompt. Meta: none. ### CLI.SPAWN_FAILED [#CLI.SPAWN_FAILED] `ctx.spawn` could not start the requested program, or the child's lifecycle promise rejected; the first line of the underlying failure is in `why`, and the guidance is to check the program is installed and on PATH. Meta: `command`. ### CLI.TELEMETRY_PREFERENCE_UNAVAILABLE [#CLI.TELEMETRY_PREFERENCE_UNAVAILABLE] The `prisma telemetry status|enable|disable` commands could not resolve the user-level config directory because none of XDG_CONFIG_HOME, HOME, APPDATA, or USERPROFILE is set; unreachable in production, where HOME or USERPROFILE is always set. Meta: none. ### CLI.UNKNOWN_COMMAND [#CLI.UNKNOWN_COMMAND] The typed path routed to no command (stricli's route failure, mapped at the adapter boundary) and no redirect claims it; next actions carry up to three "did you mean" suggestions ranked by edit distance over command paths and their prefixes, plus a pointer to `--help`. Exits 2. Meta: none. ### CLI.V7_COMMAND [#CLI.V7_COMMAND] The user typed a Prisma ORM 7 command path that Prisma ORM does not have, such as `prisma bootstrap` or `prisma postgres link`; instead of failing as unknown, the redirect table settles it with the summary "`prisma ` is a Prisma ORM 7 command and is not available in Prisma ORM". `why` says what the suggested Prisma ORM commands do and what they do not cover, and ends with how to install and run Prisma ORM 7's CLI: "To keep using Prisma ORM 7, install its CLI with `npm install --save-dev @prisma/prisma7@7` and run `prisma7 `." The `prisma7` command line in that sentence has a placeholder for every argument Prisma ORM 7 requires, such as `prisma7 complete `. The ORM's `migrate dev`, `migrate deploy`, `migrate status`, `migrate reset` and `migrate resolve` entries end with a conditional form instead: "While Prisma ORM 7 still owns this project's migrations, install its CLI with `npm install --save-dev @prisma/prisma7@7` and run `prisma7 ` instead." Next actions, in order: the replacement commands as run-command actions (labelled "Use the replacement" for one, "Step 1", "Step 2", … for several), a run-command pointing at the suggested command's `--help`, and an open-url action to the CLI docs when Prisma ORM has no equivalent. Each command family declares the Prisma ORM 7 paths that relate to its own commands. Exits 2. Meta: none. ### CLI.V7_FLAG [#CLI.V7_FLAG] The user passed a Prisma ORM 7 flag that the same-named Prisma ORM command does not accept, such as `--datasource-provider` on `prisma init`; instead of failing as an unknown flag, the redirect table settles it with the summary "`--` on `prisma ` is a Prisma ORM 7 flag and is not available in Prisma ORM". `why` and the next actions follow `CLI.V7_COMMAND`; the closing install sentence names `prisma7 --`, plus a placeholder when the flag takes a value, such as `prisma7 init --db` or `prisma7 init --url `. Exits 2. Meta: none. ## CONFIG [#config] These codes come from Composer, the command family behind `prisma dev` and `prisma deploy`. They report a problem with the `composer` section of `prisma.config.ts`, or with what its `config` and `secrets` adapters return, and are raised before Composer starts the app. ### CONFIG.ADAPTER_FAILED [#CONFIG.ADAPTER_FAILED] An adapter in `composer.config` or `composer.secrets` threw while reading the values for the environment. `why` carries the adapter's own error message, and `where.path` is the `prisma.config.ts` that lists it. The fix is to fix the adapter, or to remove it from the list. Meta: `field` (the list and index, such as `secrets[0]`). ### CONFIG.ADAPTER_INVALID [#CONFIG.ADAPTER_INVALID] An adapter in `composer.config` or `composer.secrets` returned something other than an object of values: a function (usually an adapter factory listed without calling it, such as `dotenv` instead of `dotenv()`), a non-object, or, in `secrets`, a value that is not text. The fix is to return an object whose keys are the value names and, for secrets, whose values are strings. `where.path` is the `prisma.config.ts` that lists the adapter. Meta: `field` (the list and index, such as `config[1]`). ### CONFIG.DESCRIPTOR_KIND_MISMATCH [#CONFIG.DESCRIPTOR_KIND_MISMATCH] A configured extension has a descriptor for a node type the app uses, but it is the wrong kind of descriptor for the step that needs it. The message names the step that needs the descriptor and the kind it needs. Meta: `extension`, `type`, `kind` (the kind the descriptor has). ### CONFIG.DESCRIPTOR_MISSING [#CONFIG.DESCRIPTOR_MISSING] A configured extension has no descriptor for a node type the app uses. `why` lists the node types the extension does know. Meta: `extension`, `type`. ### CONFIG.ENTRY_MISSING [#CONFIG.ENTRY_MISSING] No entry module is set, so there is no app to load. The entry is the module whose default export is the app root, built with `module(...)`. The fix is to set `entry: './module.ts'` in the `composer` section of `prisma.config.ts`, or to pass `--entry `. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.EXTENSION_DUPLICATE [#CONFIG.EXTENSION_DUPLICATE] The same extension is listed more than once in `composer.extensions`. The fix is to remove the repeated entry. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.EXTENSION_MISSING [#CONFIG.EXTENSION_MISSING] The app uses a node from an extension that is not listed in `composer.extensions`. The fix is to import the extension's `/control` entry in `prisma.config.ts` and add its descriptor to `extensions`. Meta: `extension`, `type`. ### CONFIG.FIELD_INVALID [#CONFIG.FIELD_INVALID] A field of the `composer` section has the wrong shape, for example an `entry` that is not a non-empty string, a `state` that is not a state descriptor, or an extension entry whose `nodes` is not an object. The summary names the field and the shape it must have. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.FIELD_RETIRED [#CONFIG.FIELD_RETIRED] The `composer` section uses a field Composer no longer reads, such as `configPath`, which pointed at the retired `prisma-composer.config.ts`. The fix is to move what that field pointed at into the `composer` section itself. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.FIELD_UNKNOWN [#CONFIG.FIELD_UNKNOWN] The `composer` section has a field Composer does not know. The section takes only `entry`, `extensions`, `state`, `config` and `secrets`. The fix is to remove the field, or, when the field is `composer`, to pass the `composer` property of the config export rather than the whole export. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.FILE_MISSING [#CONFIG.FILE_MISSING] The config file Composer was given does not exist. The fix is to pass the path of the `prisma.config.ts` that declares the `composer` section. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.FILE_RETIRED [#CONFIG.FILE_RETIRED] A `prisma-composer.config.*` file sits beside `prisma.config.ts`. Composer no longer reads that file, so its settings would be ignored without notice. The fix is to move its settings into the `composer` section of `prisma.config.ts` and delete the file. Meta: `field` (the field at fault, when there is one), `findings` (every problem the check found; the envelope reports the first). ### CONFIG.SECRET_AS_PLAIN_VALUE [#CONFIG.SECRET_AS_PLAIN_VALUE] A plain value would hold the value of a secret that an `envSecret()` in the app reads: either a field of the root input or a configuration key. Composer writes every plain value it read to a file for the app's process and never writes a secret to a file, so it refuses. The message names where the value is and which secret, never the value. The fix is to read the secret with `envSecret('')` where it is used, or to give the plain value text that does not contain the secret. Meta: none. ## DEPLOY [#deploy] These codes come from Composer, the command family behind `prisma deploy`, `prisma deploy list`, and the `deploy` and `destroy` operations of `@prisma/composer/control`. The deploy and destroy operations share a pipeline that loads the config and app, assembles each service, connects to the deploy target, runs each extension's preflight (on the Prisma Cloud target, the environment-variable check), and hands the generated stack program to the deploy engine (alchemy). ### DEPLOY.ALCHEMY_BIN_MISSING [#DEPLOY.ALCHEMY_BIN_MISSING] Composer starts the deploy engine from the `alchemy` package installed beside `@prisma/composer`, and either `@prisma/composer` itself could not be resolved from the app, or no runnable engine entry could be resolved beside it. Layouts without a `node_modules` directory, such as Yarn Plug'n'Play, are not supported. The fix is to check that the app depends on `@prisma/composer` and to reinstall dependencies so `@prisma/composer` and its `alchemy` dependency sit in a `node_modules` directory. Meta: none. ### DEPLOY.BUILD_REQUIRED [#DEPLOY.BUILD_REQUIRED] Assembling a service failed during a destroy. Destroy evaluates the same stack program as deploy, which packages the built artifacts, so an app must be built before it can be torn down. The fix is to run the build, then retry the destroy. The underlying assemble error rides as the cause. ### DEPLOY.CONTAINER_FAILED [#DEPLOY.CONTAINER_FAILED] Preparing the deploy target's container failed: ensuring it exists on a deploy, or locating it on a destroy or `prisma deploy list`. The underlying error rides as the cause. ### DEPLOY.CONTAINER_REMOVE_FAILED [#DEPLOY.CONTAINER_REMOVE_FAILED] Removing the deploy target's container at the end of a destroy failed. The underlying error rides as the cause. ### DEPLOY.ENGINE_FAILED [#DEPLOY.ENGINE_FAILED] The deploy engine run failed: it could not be spawned, was interrupted by a signal, or exited non-zero. The message carries the engine's own error lines (credentials redacted). `meta.diagnostics` carries the exit code or signal, the path of the generated stack file (`.prisma-composer/alchemy.run.ts`), and a reproduce command that runs the engine directly against that file — running it separates "the framework computed the wrong thing" from "the engine or platform rejected the right thing". Meta: `diagnostics` (`exitCode` or `signal`, `stackFilePath`, `reproduceCommand`, `cwd`); on a non-zero exit also `exitCode`, and `engineCause` when the engine recorded one; `signal` when interrupted. ### DEPLOY.ENVIRONMENT_INVALID [#DEPLOY.ENVIRONMENT_INVALID] `--environment` was given a value that is not a valid git ref name (`git check-ref-format` rejected `refs/heads/`). Names made only of letters, digits, `-` and `_` are always valid and skip the check. The fix is to pass an environment name that is a valid git ref name. Meta: none. ### DEPLOY.ENVIRONMENT_REQUIRED [#DEPLOY.ENVIRONMENT_REQUIRED] The `destroy` operation of `@prisma/composer/control` was called without an `environment`. Destroy never defaults to production, so a call without a name has no target. The fix is to pass `environment`, for example `destroy({ environment: 'staging', config })`. Meta: none. ### DEPLOY.ENVIRONMENT_UNVALIDATABLE [#DEPLOY.ENVIRONMENT_UNVALIDATABLE] `git` is needed to validate an `--environment` name that contains characters other than letters, digits, `-` and `_` (via `git check-ref-format`), and running it failed, for example because git is not installed. The fix is to install git or make it runnable from PATH, or to use a name made only of letters, digits, `-` and `_`. The underlying error rides as the cause. ### DEPLOY.NODE_MISSING [#DEPLOY.NODE_MISSING] Composer starts the deploy engine with Node, and no `node` was found on PATH. The fix is to install Node.js 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer, and put it on PATH, or to run `prisma` under Node. Meta: none. ### DEPLOY.PREFLIGHT_FAILED [#DEPLOY.PREFLIGHT_FAILED] An extension's preflight step failed before the engine ran, or the preflight results could not be composed into the engine's environment. On the Prisma Cloud target the preflight is the environment-variable check against the connected project and branch, so this is the code behind a failed `check environment variables` step. The underlying error's message rides in the envelope. ### DEPLOY.STACK_WRITE_FAILED [#DEPLOY.STACK_WRITE_FAILED] Writing the generated stack module at `.prisma-composer/alchemy.run.ts` failed. The file is regenerated on every run, so the fix is usually to resolve the filesystem problem (permissions, disk space) and retry. The underlying error rides as the cause. ### DEPLOY.TARGET_NOT_FOUND [#DEPLOY.TARGET_NOT_FOUND] A destroy or `prisma deploy list` named an app and environment for which nothing is deployed, so the deploy target's container could not be located. Destroy never creates anything, so the fix is to deploy it first, or to pass the environment that actually exists. Meta: none. ### DEPLOY.TEARDOWN_FAILED [#DEPLOY.TEARDOWN_FAILED] An extension's teardown step failed during a destroy. The underlying error rides as the cause. ### DEPLOY.UNEXPECTED [#DEPLOY.UNEXPECTED] Not raised as an envelope of its own: the code recorded in the deploy report when the pipeline threw a non-structured error. A run that ends with this code is a bug in Composer rather than an expected failure; the original error is rethrown with its own message. ## DEV [#dev] These codes come from Composer, the command family behind `prisma dev`, `prisma dev url`, `prisma dev stop` and `prisma emulator list`. A node is one service, database or bucket in your app; its address is its name in the app, with dots for a nested node (`catalog.database`). Each node runs on a local emulator: a program on this machine that stands in for Prisma Cloud. ### DEV.ADDRESS_UNKNOWN [#DEV.ADDRESS_UNKNOWN] `prisma dev url
` named an address that the app `prisma dev` last ran from this directory does not have. The `why` lists the addresses that are recorded for it. The fix is to pass one of those; a nested node has a dotted address, such as `catalog.database`. Meta: `address`, `known` (the recorded addresses). ### DEV.EMULATOR_FAILED [#DEV.EMULATOR_FAILED] A local emulator answered a request with an error. `prisma dev url`, `prisma dev stop` and `prisma dev` raise it when the emulator that runs a node fails a request. In `prisma emulator list` it is not a failure of the command: the emulator is listed with this code and the emulator's message instead of its instances, and the command still exits `0`. Meta: none. ### DEV.EMULATOR_UNREACHABLE [#DEV.EMULATOR_UNREACHABLE] A local emulator could not be reached. `prisma dev url` raises it when the emulator that runs the node is not running; the fix is to run `prisma dev ` in this directory, which starts the emulators the app needs. It is also raised when an emulator is registered and its process is alive but it did not accept the connection; the fix then is to run the command again, and if it keeps failing, to end the emulator's process so the next `prisma dev` starts a new one. Meta: `address` and `kind` (the node's address and kind) when the emulator is not running; `url` (the emulator's address) when it did not accept the connection. ### DEV.EMULATORS_DIR_INVALID [#DEV.EMULATORS_DIR_INVALID] Any command that reaches the local emulators (`prisma dev`, `prisma dev url`, `prisma dev stop`, `prisma emulator list`) found the `PRISMA_COMPOSER_EMULATORS_DIR` environment variable set to a relative path. Every process that starts or reaches the local emulators resolves this directory, and a relative path would name a different directory in each working directory. The fix is to set it to an absolute path (`~` is not expanded) or to unset it, which uses `~/.prisma-composer/emulators`. Meta: `variable`, `value`. ### DEV.NOT_RUNNING [#DEV.NOT_RUNNING] `prisma dev url` named a node that is not running, so it has no URL that answers. The `why` says which of three cases applies: the node is stopped (`prisma dev stop`, `prisma dev` ending, and running another app in this directory all stop an app's services and database servers; the fix is to run `prisma dev ` in this directory); the node exited after it started and is being restarted or was held after repeated crashes (the fix is to read its log, whose path is in the `fix` and `meta.logPath` when known, fix the cause and rebuild); or the emulator no longer has it, for example because a Composer upgrade discarded the emulator's state (running `prisma dev ` creates it again, empty). Meta: `address`, `kind`, `state`, and `logPath` when known. ### DEV.NOT_STARTED_HERE [#DEV.NOT_STARTED_HERE] `prisma dev url` or `prisma dev stop` ran in a directory where `prisma dev` has not run. An app's local services, databases and buckets are recorded in the directory `prisma dev` runs from, and there is no such record here. The fix is to run `prisma dev ` in this directory, or to run the command from the directory where `prisma dev` ran. Meta: `cwd`. ## FEEDBACK [#feedback] ### FEEDBACK.EMAIL_INVALID [#FEEDBACK.EMAIL_INVALID] `prisma feedback --email` was given a value that fails the CLI's local check (a basic address pattern, at most 320 characters), which mirrors the feedback service's own limit so the refusal happens before any network round trip. The suggested actions are to pass a valid address or drop the flag to send anonymously. Meta: none. ### FEEDBACK.MESSAGE_REQUIRED [#FEEDBACK.MESSAGE_REQUIRED] `prisma feedback` was run with a message that is empty after trimming. The fix is to pass a non-empty message. Meta: none. ### FEEDBACK.MESSAGE_TOO_LONG [#FEEDBACK.MESSAGE_TOO_LONG] The `prisma feedback` message exceeds 4000 characters, the feedback service's limit, checked locally before the network round trip; the actual length and the limit are stated in `why`. The fix is to shorten the message. Meta: none. ### FEEDBACK.SEND_FAILED [#FEEDBACK.SEND_FAILED] `prisma feedback` could not deliver the submission: the feedback endpoint was unreachable (or timed out), the service answered a non-OK HTTP status (the status and any service-supplied error message go into `why`), or the response body could not be read; a body that arrived but was not JSON is treated as success, and a user cancellation is rethrown rather than wrapped. The suggested action is to check the network and rerun. Meta: none. ## GIT [#git] ### GIT.REPO_ALREADY_CONNECTED [#GIT.REPO_ALREADY_CONNECTED] `prisma git connect` found the resolved project already connected to a different GitHub repository than the one requested (reconnecting the same repository is idempotent and succeeds). The fix is to run `prisma git disconnect` first. Meta: `repository`. ### GIT.REPO_CONNECTION_FAILED [#GIT.REPO_CONNECTION_FAILED] A management API call in the `prisma git connect`/`disconnect` flow failed — creating the install intent, listing installations or repositories, reading or writing the source-repository connection, or a pagination cursor that stopped advancing; the API's message and hint, when present, become `why` and the suggested fix, and a 401/403 is routed to the auth error path instead. Meta: `status`, `apiCode` (when the API supplied one). ### GIT.REPO_INSTALLATION_REQUIRED [#GIT.REPO_INSTALLATION_REQUIRED] `prisma git connect` waited for a GitHub App installation but the wait ended (timeout or final poll) with the workspace still holding no inspectable installation that could link the repository. The fix is to finish installing the GitHub App at the install URL, then rerun `prisma git connect`; the URL is also offered as an open-url next action. Meta: `repository`, `installUrl`. ### GIT.REPO_NOT_ACCESSIBLE [#GIT.REPO_NOT_ACCESSIBLE] `prisma git connect` waited for repository access but the wait ended with the workspace's existing GitHub App installations still not exposing the requested repository — the same install wait as `GIT.REPO_INSTALLATION_REQUIRED`, distinguished by at least one inspectable installation existing. The fix is to grant the App access to this repository at the install URL, then rerun `prisma git connect`. Meta: `repository`, `installUrl`. ### GIT.REPO_NOT_CONNECTED [#GIT.REPO_NOT_CONNECTED] `prisma git disconnect` found no active GitHub repository connection on the resolved project, so there is nothing to disconnect. The fix is to run `prisma git connect` first. Meta: none. ### GIT.REPO_PROVIDER_UNSUPPORTED [#GIT.REPO_PROVIDER_UNSUPPORTED] The URL given to `prisma git connect` (or read from the local `origin` remote) did not parse as a GitHub repository URL; repository connection supports GitHub only. The fix is to pass a GitHub repository URL. Meta: none. ### GIT.USAGE_ERROR [#GIT.USAGE_ERROR] `prisma git connect` was run with no repository URL argument and the local repository has no `origin` remote to fall back on. The fix is to pass a GitHub repository URL or add a GitHub `origin` remote and rerun. Meta: none. ## INIT [#init] ### INIT.CONFIG_KEPT [#INIT.CONFIG_KEPT] A warn diagnostic from `prisma init`: a `prisma.config.ts` already exists that does not configure `skills.agents`, and init never edits an existing config, so it was left untouched. The nextAction carries the exact `skills: { agents: [...] }` snippet to add to the `definePrismaConfig` call; a config that already sets `skills.agents` produces no diagnostic at all. Meta: none. ### INIT.CONFIG_UNWRITABLE [#INIT.CONFIG_UNWRITABLE] A warn diagnostic from `prisma init`: writing the scaffolded `prisma.config.ts` failed, so the config step was skipped. The nextAction asks the user to create the file themselves with the intended `skills: { agents: [...] }` section. Meta: none. ### INIT.DEV_DEPENDENCIES_NOT_AN_OBJECT [#INIT.DEV_DEPENDENCIES_NOT_AN_OBJECT] A warn diagnostic from `prisma init`: the `devDependencies` field in package.json is not an object, so init did not add the `prisma` dev dependency (the postinstall-hook edit still proceeds when its own field is fine). The nextAction is to fix the field, add `"prisma": ""` by hand, and run the package manager's install. Meta: none. ### INIT.NO_PACKAGE_JSON [#INIT.NO_PACKAGE_JSON] A warn diagnostic from `prisma init`: there is no package.json in the current directory, so neither the skills-sync postinstall hook nor the `prisma` dev dependency was added. The nextActions are to rerun init from the directory that holds package.json, or to add the dependency by hand. Meta: none. ### INIT.PACKAGE_JSON_UNREADABLE [#INIT.PACKAGE_JSON_UNREADABLE] A warn diagnostic from `prisma init`: package.json exists but could not be parsed as JSON, so the postinstall hook and the `prisma` dev dependency were not added. The nextActions give the exact postinstall script and dependency entry to add by hand. Meta: none. ### INIT.PACKAGE_JSON_UNWRITABLE [#INIT.PACKAGE_JSON_UNWRITABLE] A warn diagnostic from `prisma init`: the manifest edit was prepared but writing package.json back failed, so the file was left unchanged. The nextActions cover only what the failed write would have added — the postinstall script, the dev dependency, or both. Meta: none. ### INIT.POSTINSTALL_KEPT [#INIT.POSTINSTALL_KEPT] A warn diagnostic from `prisma init`: package.json already has a postinstall script that is not the CLI's own, and init never overwrites a user's script, so it was left alone. The nextAction is to append `prisma skills sync || exit 0` to the existing script yourself so skills resync on every install. Meta: none. ### INIT.SCRIPTS_NOT_AN_OBJECT [#INIT.SCRIPTS_NOT_AN_OBJECT] A warn diagnostic from `prisma init`: the `scripts` field in package.json is not an object, so init left the manifest untouched instead of adding the postinstall hook (which also skips adding the dev dependency, since the manifest is not edited at all). The nextAction gives the postinstall script to add by hand. Meta: none. ### INIT.SKILLS_SYNC_FAILED [#INIT.SKILLS_SYNC_FAILED] A warn diagnostic from `prisma init`: the final step, syncing the agent skills from installed Prisma packages, threw; the cause's message is appended to the summary. The nextAction is to retry with `prisma skills sync` on its own. Meta: none. ## POSTGRES [#postgres] ### POSTGRES.AMBIGUOUS [#POSTGRES.AMBIGUOUS] A database name passed to a `prisma postgres` subcommand matched more than one database in the resolved project — raised by the shared database resolver (`controllers/database.ts`). The fix is to pass the database id, or `--branch ` to narrow the match; the candidates are carried in meta as `matches`, each with `id`, `name`, and `branchName`. Meta: `matches`. ### POSTGRES.API_ERROR [#POSTGRES.API_ERROR] A database REST API request failed without a more specific code — the generic fallback for every `prisma postgres` operation, raised by the provider (`lib/database/provider.ts`), and also when a database response omits its project id. The `why` carries the API's message or HTTP status, and the fix is the API's hint when it sent one. An HTTP 401 or 403 raises this code too, with a `why` saying the API rejected the request as unauthorized and a `prisma auth login` next action. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). ### POSTGRES.BACKUP_NOT_FOUND [#POSTGRES.BACKUP_NOT_FOUND] `prisma postgres backup restore` got a 404 from the restore endpoint; the source and target databases are resolved before the call, so the 404 identifies the backup id. The fix is to pass a backup id from `prisma postgres backup list `. Meta: none. ### POSTGRES.BACKUPS_UNSUPPORTED [#POSTGRES.BACKUPS_UNSUPPORTED] Listing backups returned a 422 because the platform does not manage backups for this database — for example a remote/BYO database (raised by `prisma postgres backup list`). The fix is to use your own backup tooling for externally managed databases. Meta: none. ### POSTGRES.CONNECTION_MISSING [#POSTGRES.CONNECTION_MISSING] `prisma postgres create` created the database, but the API response did not include the first one-time connection payload. The fix is to create a connection explicitly with `prisma postgres connection create `. Meta: none. ### POSTGRES.CONNECTION_STRING_MISSING [#POSTGRES.CONNECTION_STRING_MISSING] A connection create or rotate succeeded, but the API response did not include the one-time connection string the CLI would show exactly once (raised by `prisma postgres create`, `postgres connection create`, and `postgres connection rotate`). The fix is to rerun the operation, or create a replacement connection and store the returned URL immediately. Meta: none. ### POSTGRES.NOT_FOUND [#POSTGRES.NOT_FOUND] The database a `prisma postgres` subcommand targets could not be resolved: either no database matched the given id or name in the project (and optional `--branch`) scope, or a database that was just listed returned 404 on read because it was removed while the command ran (raised by the shared resolver in `controllers/database.ts`). The fix is to pass an id or name from `prisma postgres list`. Meta: none. ### POSTGRES.PLAN_LIMIT_REACHED [#POSTGRES.PLAN_LIMIT_REACHED] A database operation was blocked because the workspace has used up the operations included in its plan — the API's structured plan-limit discriminator, detected on any `prisma postgres` REST API call; this is a workspace plan restriction, not a Prisma outage. The one nextAction is to upgrade the workspace plan, with the upgrade URL and current plan name when the workspace subscription could be read. Meta: `workspaceId`, `blockedFeature`, `planName`, `usageBlocked`, `upgradeUrl` (each `null` when unavailable). ### POSTGRES.RESTORE_CONFLICT [#POSTGRES.RESTORE_CONFLICT] `prisma postgres backup restore` got a 409 because the target database is provisioning or already recovering. The fix is to wait for the database to become ready — check with `prisma postgres show ` — then retry. Meta: none. ### POSTGRES.USAGE_ERROR [#POSTGRES.USAGE_ERROR] A `prisma postgres` subcommand was called with missing or invalid arguments: `create` without a name, `connection delete`/`connection rotate` without a connection id, `backup restore` without `--backup`, or `usage` with `--from` later than `--to`. The nextActions show the corrected command form. Meta: none. ## PROJECT [#project] ### PROJECT.AMBIGUOUS [#PROJECT.AMBIGUOUS] Project resolution matched more than one project: an explicit project reference (matched by id first, then by name) hit several projects, or the implicit directory context did — raised by any command that resolves a project, including `branch list`. The fix is to pass `--project `, and the next actions include `prisma project link ` with the first match's id verbatim so the user can copy an exact disambiguating reference. Meta: `matches`. ### PROJECT.API_ERROR [#PROJECT.API_ERROR] A REST API project operation (list, rename, delete, or transfer) failed. Listing projects deliberately throws this rather than returning an empty list, so a rejected request is distinguishable from a workspace that genuinely has no projects. The `why` carries the API's message or HTTP status, and the API's own error code, when it sent one, is in `meta.apiCode`. Meta: `status`, `apiCode` (each present only when the response supplied it). ### PROJECT.CREATE_FAILED [#PROJECT.CREATE_FAILED] The platform rejected creating a project — raised by `prisma project create` and by the create-a-new-project path of `prisma project link`. An HTTP 401/403 gets a permissions-focused fix; any other failure surfaces the underlying error message as the `why`. Meta: none. ### PROJECT.DELETE_BLOCKED [#PROJECT.DELETE_BLOCKED] The REST API answered `prisma project delete` with HTTP 400, which typically means the project still has active deployments; the fix is to delete the project's services first (`prisma service delete --service `) and retry. The API's own message replaces the default `why` when present. Meta: none. ### PROJECT.ENV_API_ERROR [#PROJECT.ENV_API_ERROR] A REST API call made by the `prisma project env` commands (reading, writing, or deleting variables, or resolving and creating branches for a scope) failed. The summary names the call that failed, for example "Failed to add STRIPE_KEY". An HTTP 401 or 403 raises this code too, with a `why` saying the API rejected the request as unauthorized and a `prisma auth login` next action. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). ### PROJECT.ENV_BRANCH_CREATE_REQUIRES_DEFAULT_BRANCH [#PROJECT.ENV_BRANCH_CREATE_REQUIRES_DEFAULT_BRANCH] `prisma project env add --branch ` will create a missing preview branch, but the project has no default branch yet, and creating the first branch would make it the default while branch env overrides are preview-only. The fix is to create or deploy the default branch first, for example via `prisma git connect`. Meta: none. ### PROJECT.ENV_BRANCH_NOT_FOUND [#PROJECT.ENV_BRANCH_NOT_FOUND] A `prisma project env` update, list, or delete named a branch scope (`--branch `) that does not exist — only `env add` creates missing branches. The fix is to create the branch by deploying it, or to use `project env add --branch` to create its first override. Meta: none. ### PROJECT.ENV_BRANCH_SCOPE_IS_PRODUCTION [#PROJECT.ENV_BRANCH_SCOPE_IS_PRODUCTION] A `prisma project env` command's `--branch` flag resolved to the project's production branch; production variables are project-level only, and branch overrides apply to preview branches. The fix is to use `--role production` instead. Meta: none. ### PROJECT.ENV_FILE_APPLY_FAILED [#PROJECT.ENV_FILE_APPLY_FAILED] `prisma project env add --file` or `update --file` failed while writing one of the file's keys, after zero or more earlier keys were already written. The `why` names the keys written before the failure and the underlying cause, and the next actions include a retry command scoped to a file of the remaining keys. Meta: `file`, `failedKey`, `writtenKeys`. ### PROJECT.ENV_PREVIEW_DEFAULT_MISSING [#PROJECT.ENV_PREVIEW_DEFAULT_MISSING] Not an error: a warn diagnostic emitted on a successful `prisma project env add` to a branch scope (single key or `--file`) for each key that has no preview-level default, meaning the variable will exist only on that branch. Meta: none. ### PROJECT.ENV_VARIABLE_ALREADY_EXISTS [#PROJECT.ENV_VARIABLE_ALREADY_EXISTS] `prisma project env add` targeted a key (or, in `--file` mode, one or more keys) that already exists in the targeted scope. The single-key fix is to use `prisma project env update`; the file-mode fix is to split the input file and update existing keys separately from adding new ones. Meta: `keys` (file mode only; the single-key form carries no meta). ### PROJECT.ENV_VARIABLE_NOT_FOUND [#PROJECT.ENV_VARIABLE_NOT_FOUND] `prisma project env update` or `env delete` targeted a key (or, in update's `--file` mode, one or more keys) that does not exist in the targeted scope. The fix for update is to create the variable with `env add` (or split a mixed file); for delete it is to list the scope's variables first. Meta: `keys` (file-mode update only; the single-key forms carry no meta). ### PROJECT.LOCAL_STATE_STALE [#PROJECT.LOCAL_STATE_STALE] The local project binding in `.prisma/local.json` is unusable: the pinned project is no longer in the selected workspace's project list, or the pin file is invalid JSON or has an invalid shape — raised by any command that resolves the project implicitly through the pin. The fix is to delete the pin file and choose a project explicitly. Meta: `pinPath`. ### PROJECT.LOCAL_STATE_WRITE_FAILED [#PROJECT.LOCAL_STATE_WRITE_FAILED] `prisma project link` or `project create` could not save the local binding: writing `.prisma/local.json` failed, or updating `.gitignore` to keep the binding out of git failed — the fix is to check directory permissions and retry. The same code is also emitted as a warn diagnostic (not an error) by `project delete` and `project transfer` when the operation itself succeeded but the now-stale local pin could not be removed or rewritten. Meta: `pinPath` or `gitignorePath`, plus `operation` (the error form; the diagnostic form carries none). ### PROJECT.LOCAL_WORKSPACE_MISMATCH [#PROJECT.LOCAL_WORKSPACE_MISMATCH] `.prisma/local.json` links the directory to a project in one workspace, but the CLI session's active workspace is a different one — raised by any command that resolves the project through the pin. The fix is to switch to the pinned workspace (`prisma auth workspace use `) or relink the directory to a project in the current workspace. Meta: `pinPath`, `pinnedWorkspaceId`, `pinnedProjectId`, `activeWorkspaceId`, `activeWorkspaceName`. ### PROJECT.NOT_FOUND [#PROJECT.NOT_FOUND] An explicit project reference matched no project in the active workspace, either because it does not exist or because the credential cannot see it — raised during project resolution for any command that accepts one, including `branch list` and the `project link`/`transfer`/`delete` target lookup. The fix is to pass an id or name from `prisma project list`. Service commands raise the same code one step later, when the services API answers "Resource Not Found" for a project that did resolve — the directory binding points at a project that no longer exists or is no longer accessible — and their next actions point at `project show` to inspect the binding and `project link` to fix it. Meta: none. ### PROJECT.RENAME_FAILED [#PROJECT.RENAME_FAILED] The REST API answered `prisma project rename` with HTTP 400 or 422, meaning the platform rejected the new name; the API's message and hint replace the default `why` and fix when present, and the fallback fix is to retry with a different name. Meta: none. ### PROJECT.SETUP_REQUIRED [#PROJECT.SETUP_REQUIRED] A command needed a project but the directory is not linked and no `--project` flag was given; the CLI deliberately refuses to pick a project from package or directory names, treating them as suggestions only. The meta carries the inferred name suggestion and any matching candidate projects, and the next actions walk through choosing between linking an existing project (`prisma project link`) and creating a new one. Meta: `suggestedProjectName`, `suggestedProjectNameSource`, `candidates`, `recoveryCommands`. ### PROJECT.TRANSFER_RECIPIENT_REQUIRED [#PROJECT.TRANSFER_RECIPIENT_REQUIRED] `prisma project transfer` was invoked without naming a receiving workspace: neither `--to-workspace ` (for a locally authenticated workspace) nor `--recipient-token ` (for a cross-account transfer) was passed. Meta: none. ### PROJECT.TRANSFER_RECIPIENT_UNAVAILABLE [#PROJECT.TRANSFER_RECIPIENT_UNAVAILABLE] `prisma project transfer --to-workspace` needs to resolve locally stored OAuth workspace sessions, but `PRISMA_SERVICE_TOKEN` is set and service-token mode does not read them. The fix is to pass `--recipient-token ` for the receiving workspace, or to unset the service token. Meta: none. ### PROJECT.TRANSFER_REJECTED [#PROJECT.TRANSFER_REJECTED] The REST API answered `prisma project transfer` with HTTP 400 — for example because the recipient token is invalid or expired; the API's message replaces the default `why` when present, and the fix is to check the recipient session or token and retry. Meta: none. ### PROJECT.USAGE_ERROR [#PROJECT.USAGE_ERROR] A `project` or `branch` group command was invoked with unusable arguments — for example a `project env` write without an explicit `--role` or `--branch` scope, `project transfer` with both recipient flags at once, `project create` with an empty name, or an interactive `project link` whose selection was cancelled. Usage errors exit 2. Meta: none. ## SERVICE [#service] ### SERVICE.BRANCH_INVALID [#SERVICE.BRANCH_INVALID] A `--branch` flag was passed with an empty or whitespace-only value to a service command; the check runs before any resolution because a blank value must never fall through to the default-branch behavior of omitting the flag. The fix is to pass a non-empty branch name, or omit `--branch` to target the default branch. Meta: none. ### SERVICE.DELETE_FAILED [#SERVICE.DELETE_FAILED] `service delete` called the platform's app-teardown API and it rejected; the underlying error's message becomes `why` and the original error is carried in `cause`. Next actions point at `service show` and `service version list` for the service. Meta: none. ### SERVICE.DEPLOY_FAILED [#SERVICE.DEPLOY_FAILED] The general "REST API call failed" wrapper for the `service` command family — despite the name there is no deploy command here: it wraps failures to create a service, list services or versions, show/promote/roll back/delete/start/stop a version, resolve a service URL, and unrecognized custom-domain API failures. The underlying error's message becomes `why` and the original error is carried in `cause`; each raise site attaches its own next actions. On the domain fallback path only, a `DomainApiError` adds debug meta. Meta: `status`, `apiCode`, `hint` (domain fallback path only; otherwise none). ### SERVICE.DOMAIN_ALREADY_REGISTERED [#SERVICE.DOMAIN_ALREADY_REGISTERED] `service domain add` got HTTP 409 from the domain API because the hostname is already registered, to this or another service. The fix is to delete the domain on the service that owns it, or contact Prisma support if that service is not accessible. Meta: `status`, `apiCode`, `hint`. ### SERVICE.DOMAIN_DNS_NOT_CONFIGURED [#SERVICE.DOMAIN_DNS_NOT_CONFIGURED] `service domain add` got HTTP 400 or 422 whose message the CLI recognizes as a DNS problem (no CNAME, DNS verification failed, and similar). When the API's text names a `*.prisma.build` target, the CLI composes the exact CNAME record to add and carries it in `meta.dnsRecord` and in the advice action; without a target it advises rerunning with `--log-level verbose` to see the API response. Meta: `status`, `apiCode`, `hint`, `dnsRecord` (when the DNS target could be extracted). ### SERVICE.DOMAIN_HOSTNAME_INVALID [#SERVICE.DOMAIN_HOSTNAME_INVALID] The hostname given to a `service domain` command is not a usable custom domain — raised either by local validation before any API call (protocol, path, port, wildcard, single label, or bad DNS labels) or when `service domain add` gets a plain HTTP 400 rejection from the domain API. The fix is to pass a bare hostname such as `shop.acme.com`. Meta: `status`, `apiCode`, `hint` (API-rejection path only; none for local validation). ### SERVICE.DOMAIN_OWNERSHIP_REQUIRED [#SERVICE.DOMAIN_OWNERSHIP_REQUIRED] The API could not find the TXT record proving that this workspace may attach the hostname. Add the exact name and value in the API hint, keep the TXT record for future attachments in this workspace, and rerun the suggested command. Recovery preserves the selected service, project, and branch. This does not mean that the service needs another deployment. Meta: `status`, `apiCode`, `hint`. ### SERVICE.DOMAIN_CLOUDFLARE_PROXY [#SERVICE.DOMAIN_CLOUDFLARE_PROXY] The API found Cloudflare proxy addresses while the hostname's routing check failed. Set that DNS record to DNS only (gray cloud) and rerun the suggested command. After the domain is Active, Proxied can be enabled again with Full (strict) SSL/TLS. Keep `/.well-known/acme-challenge/*` accessible without caching or security challenges so Prisma can renew the certificate. Meta: `status`, `apiCode`, `hint`. ### SERVICE.DOMAIN_NOT_FOUND [#SERVICE.DOMAIN_NOT_FOUND] A `service domain` command targeted a hostname that is not attached to the resolved service — raised when the service's domain listing has no matching hostname, or when a show/delete/retry/wait call gets HTTP 404. The fix is to check the hostname and service, or add the domain first. Meta: none. ### SERVICE.DOMAIN_QUOTA_EXCEEDED [#SERVICE.DOMAIN_QUOTA_EXCEEDED] `service domain add` was refused because the custom-domain quota is reached — HTTP 429, or a 409 whose text mentions a quota, maximum, or limit. The CLI uses the API's recovery hint when supplied, including waiting for an hourly creation budget. Without a hint, it advises deleting an existing custom domain before adding another. Meta: `status`, `apiCode`, `hint`. ### SERVICE.DOMAIN_RETRY_NOT_ELIGIBLE [#SERVICE.DOMAIN_RETRY_NOT_ELIGIBLE] `service domain retry` got HTTP 409: the domain is not in a state that can be retried, typically because a verification or TLS step is still in progress. The fix is to wait for the current step to finish and retry only if the domain then fails. Meta: `status`, `apiCode`, `hint`. ### SERVICE.DOMAIN_VERIFICATION_FAILED [#SERVICE.DOMAIN_VERIFICATION_FAILED] `service domain wait` observed the domain reach the terminal `failed` status; `why` carries the platform's failure category and reason when reported, and a failure-specific fix line is attached when the CLI can derive one from the domain record. Next actions point at `service domain show` and `service domain retry`. Meta: none. ### SERVICE.DOMAIN_VERIFICATION_TIMEOUT [#SERVICE.DOMAIN_VERIFICATION_TIMEOUT] `service domain wait` ran out of time (default 15m, or `--timeout 0` for a single check) before the domain became active; `why` reports the status the domain was last seen in. The fix is to inspect the domain with `service domain show` or rerun the wait with a longer `--timeout`. Meta: none. ### SERVICE.FEATURE_UNAVAILABLE [#SERVICE.FEATURE_UNAVAILABLE] `service open` found a live version but the provider does not expose a stable live service URL for this service yet, so there is nothing to open. The next action is to inspect the service state with `service show`. Meta: none. ### SERVICE.LIVE_VERSION_UNKNOWN [#SERVICE.LIVE_VERSION_UNKNOWN] `service version rollback` without `--to` needs to know which version is live, because the default rollback target is defined relative to it, and the service record names no live version — the CLI refuses rather than guess what production is serving. The fix is to pass `--to ` explicitly. Meta: none. ### SERVICE.LOGS_FAILED [#SERVICE.LOGS_FAILED] `service logs` could not read the log — either the logs endpoint answered with a non-OK HTTP status (other than 404, which becomes SERVICE.VERSION_NOT_FOUND), or a page's closing terminal record reported `kind: "error"`, meaning the platform itself says the log read failed. The meta differs by path: the HTTP path carries `status`; the terminal-record path carries the platform's error `code`, `retryable`, and the resume `cursor` when present (in `--follow` mode one retryable terminal error is retried once before this settles the run). Meta: `status` (HTTP path) or `code`, `retryable`, `cursor` (stream path). ### SERVICE.LOGS_INCOMPLETE [#SERVICE.LOGS_INCOMPLETE] A `service logs` response body ended without the terminal record that closes a page, so the read was truncated and the lines already printed may be only part of the page; the run must not settle as if it had read the whole page. Distinct from SERVICE.LOGS_NO_CURSOR, which is a properly closed page with nothing to resume from. The fix is to rerun the command. Meta: none. ### SERVICE.LOGS_NO_CURSOR [#SERVICE.LOGS_NO_CURSOR] `service logs --follow` needs a resume cursor from each page to fetch the next one, and the page ended without one — continuing would re-request the default tail and silently print the same lines every interval, so the run stops and says why. It settles as an error rather than a clean end because `--follow` has no successful ending. The fix is to rerun without `--follow`, or retry if the version is still starting. Meta: none. ### SERVICE.LOGS_RANGE_CONFLICT [#SERVICE.LOGS_RANGE_CONFLICT] `service logs` was invoked with both `--tail` and `--from-start`, which ask for opposite ends of the log; the run is refused before any work. The fix is to pass `--tail ` for the last n lines or `--from-start` for the whole log, not both. Meta: none. ### SERVICE.NAME_REQUIRED [#SERVICE.NAME_REQUIRED] `service create` received an empty or whitespace-only name positional; the check runs before any resolution. The fix is to pass a name, as in `service create my-service`. Meta: none. ### SERVICE.NO_PREVIOUS_VERSION [#SERVICE.NO_PREVIOUS_VERSION] `service version rollback` without `--to` found no earlier version to switch back to — the service has no versions at all, or every version is the live one. The fix is to deploy a second version first, or pass `--to ` for a specific version. Meta: none. ### SERVICE.NO_VERSIONS [#SERVICE.NO_VERSIONS] The resolved service has no usable version for the command — raised by `service open` when the service has no versions, by `service logs` when it has no live version, and by `service domain add` when the API answers 422 because the selected service has no promoted version that can receive a custom domain. The fix on the domain path is to promote a version on the selected branch first, then add the domain again. Meta: `status`, `apiCode`, `hint` (domain-add path only; otherwise none). ### SERVICE.SELECTION_INVALID [#SERVICE.SELECTION_INVALID] The named service could not be found among the resolved project branch's services — the match tries the stable platform id first, then the name. The fix is to pass the id or name of an existing service; the suggested command is `service list`, deliberately not `service version list`, which itself has to resolve a service and would fail the same way. Meta: none. ### SERVICE.TARGET_REQUIRED [#SERVICE.TARGET_REQUIRED] A service command that acts on an existing service was run without naming one; service commands act only on an explicitly named target — nothing is inferred, remembered, or prompted for. The fix is to pass the service id or name as the first argument, with `service list` to find one. Meta: none. ### SERVICE.TIMEOUT_INVALID [#SERVICE.TIMEOUT_INVALID] The `--timeout` value passed to `service domain wait` is not a duration the parser accepts (`0`, or an integer with `ms`/`s`/`m`/`h`, such as `30s` or `15m`). Meta: none. ### SERVICE.VERSION_ALREADY_LIVE [#SERVICE.VERSION_ALREADY_LIVE] Not an error: a warn-severity diagnostic attached by `service version promote` and `service version rollback` when the selected version is already live for the service — the command skips the promote call, still reports the result, and exits 0. Meta: none. ### SERVICE.VERSION_ALREADY_RUNNING [#SERVICE.VERSION_ALREADY_RUNNING] Not an error: a warn-severity diagnostic attached by `service version start` when the selected version already reports `running` status — the start call is skipped, the result carries `alreadyInState: true`, and the run exits 0. Meta: none. ### SERVICE.VERSION_ALREADY_STOPPED [#SERVICE.VERSION_ALREADY_STOPPED] Not an error: a warn-severity diagnostic attached by `service version stop` when the selected version already reports `stopped` status — the stop call is skipped, the result carries `alreadyInState: true`, and the run exits 0. Meta: none. ### SERVICE.VERSION_DETACHED [#SERVICE.VERSION_DETACHED] A version was resolved by its globally-unique id but the REST API returned it without an owning service, so there is nothing to report or act on it as. The next action shows the version with `service version show`. Meta: none. ### SERVICE.VERSION_NOT_FOUND [#SERVICE.VERSION_NOT_FOUND] The requested service version does not exist or is not available — raised when resolving a version by its globally-unique id finds nothing (including a 404 from the logs endpoint), and, in the "for service" variant used by rollback and logs `--version-id`, when the id exists but does not belong to the resolved service. The fix is to pick an id from `service version list`. Meta: none. ### SERVICE.WORKSPACE_REQUIRED [#SERVICE.WORKSPACE_REQUIRED] A service command ran without a credential that names a workspace — either no authenticated session, or an environment token whose claims carry no workspace, which cannot scope these commands and is treated the same as having no credential. The fix is `auth login`. Meta: none. ## SKILLS [#skills] ### SKILLS.CONFIG_INVALID [#SKILLS.CONFIG_INVALID] An error diagnostic from validating the `skills` section of `prisma.config.ts`, surfaced by the commands that consume it (`init`, `skills sync`, `skills list`): the section is not an object, `skills.check` is not a boolean, `skills.agents` is not an array of strings, or an agent name is one this CLI does not know. Each variant's nextAction says what to write instead; code that reads the config outside a command handler (the staleness check, the post-login tip) treats an invalid config as absent and falls back to the default agent set rather than silencing the check. Meta: none. ### SKILLS.UNMANAGED_DIRECTORY [#SKILLS.UNMANAGED_DIRECTORY] A warn diagnostic from the skills sync (`skills sync`, and the sync step of `init`): a target agent skill directory already holds a skill this CLI does not manage, so sync left it untouched instead of installing the packaged skill there. The nextAction is to move or remove the unmanaged directory and rerun `skills sync`. Meta: none. ### SKILLS.VERSION_CONFLICT [#SKILLS.VERSION_CONFLICT] A warn diagnostic from the skills sync (`skills sync`, and the sync step of `init`): workspace members install different versions of the same skill-bearing Prisma package, so the skills for the highest version were installed and the members pinning a lower version get a skill describing a version they did not install. The nextAction is to pin one version of the package across the workspace. Meta: none. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # feedback (/docs/cli/feedback) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Send feedback to the Prisma CLI team. Location: CLI > feedback `feedback` sends feedback to the Prisma CLI team, straight from the terminal. ## Usage [#usage] #### bun ```bash bunx prisma feedback "The service logs command saved my afternoon" ``` #### pnpm ```bash pnpm prisma feedback "The service logs command saved my afternoon" ``` #### yarn ```bash yarn prisma feedback "The service logs command saved my afternoon" ``` #### npm ```bash npx prisma feedback "The service logs command saved my afternoon" ``` The message can be up to 4000 characters. Feedback is anonymous unless you add `--email
` so the team can reply. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # git (/docs/cli/git) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Connect a GitHub repository for push-to-deploy. Location: CLI > git Use `git` commands to manage the GitHub repository connection. Connecting enables the OIDC credential exchange for GitHub Actions deploys and the branch lifecycle automation. See [GitHub integration](https://www.prisma.io/docs/compute/github) and [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push). ## Usage [#usage] #### bun ```bash bunx prisma git connect ``` #### pnpm ```bash pnpm prisma git connect ``` #### yarn ```bash yarn prisma git connect ``` #### npm ```bash npx prisma git connect ``` Run it from a [linked](https://www.prisma.io/docs/cli/project) project directory. The command needs an interactive terminal: it opens the browser to install the GitHub App when needed and waits for the install. With `--no-interactive` it fails with `CLI.INTERACTION_REQUIRED`. Connecting from the CLI does not add a deploy workflow to the repository. [Add it yourself](https://www.prisma.io/docs/compute/deploy-on-push#4-add-the-deploy-workflow), or connect through the [Console](https://pris.ly/pdp), which opens a pull request with the workflow. ## Commands [#commands] | Command | Description | | ----------------------- | ----------------------------------------------------------------------------------------------- | | `git connect [git-url]` | Connect the linked project to a GitHub repository. Starts the GitHub App install flow if needed | | `git disconnect` | Stop the credential exchange and branch automation. Keeps the project and existing branches | ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # Global flags (/docs/cli/global-flags) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Flags accepted by every command in the unified Prisma CLI. Location: CLI > Global flags All commands in the unified Prisma CLI accept these flags. | Flag | What it does | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `--json` | Print machine-readable output (shorthand for `--format json`). Use this in CI and scripts. | | `--format ` | Output format: `human`, `json`, or `markdown`. | | `--log-level ` | Commentary verbosity: `error`, `warn`, `info`, or `verbose`. | | `-q`, `--quiet` | Suppress nonessential output (shorthand for `--log-level error`). | | `-v`, `--verbose` | Print more detail (shorthand for `--log-level verbose`). | | `--color` / `--no-color` | Force colored output on or off. | | `--interactive` / `--no-interactive` | Force prompts on or off. | | `-y`, `--yes` | Accept prompt defaults without asking. | | `--confirm ` | Grant a consent prompt in advance by giving its token, so the command does not ask (repeatable). Works in scripts and in an interactive terminal. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `-h`, `--help` | Print the manual for a command: what it does, its options, a workflow where one applies, and examples. | | `--version` | Print the CLI version and exit. | ## Output formats [#output-formats] Without `--format` or `--json`, every run uses `human` output, whether standard output is a terminal, a pipe, or a file. JSON and Markdown are never chosen for you; pass `--json` or `--format markdown` to get them. In `human` output, the formatted result, progress, and errors go to standard error. Standard output gets only the command's data lines: plain values with no labels or color, which `cut`, `xargs`, and `$(...)` can take directly. * A list prints one line per item, with its fields separated by tabs, in the order the table shows them. * A command that returns one value, such as a URL or the id of a created resource, prints that value alone. * A command whose only result is that it succeeded, such as a delete or a stop, writes nothing to standard output. Its exit code is the result, and its message goes to standard error. ```bash npx prisma project list | cut -f2 curl "$(npx prisma dev url my-app.gateway)" ``` In a terminal you see only the formatted result, because it already shows the same values. The data lines appear when standard output is piped, redirected to a file, or captured by `$(...)`. A script that needs more than the data lines uses `--json`. `prisma deploy` does not write data lines yet, so a script reads its result with `--json`. The data lines of each Prisma ORM command are listed in [Data lines of Prisma ORM commands](#data-lines-of-prisma-orm-commands). A pipe got JSON before `8.0.0-rc.24` of the `prisma` CLI for the commands that manage projects, databases and deploys, and before `8.0.0-rc.20` of `@prisma/orm-postgres` and `@prisma/orm-mongo` for the Prisma ORM commands `contract`, `db`, `migration` and `orm init`. If an older script reads JSON from a pipe, add `--json` to it. The [upgrade recipe](https://github.com/prisma/orm/blob/v8.0.0-rc.20/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/) lists the places to look. `markdown` is for AI agents that read command output as text rather than parsing JSON. It prints the same content as `human`, as plain Markdown: a summary line, `label: value` lines, pipe tables, bullet lists, and fenced code, followed by a `### Next` section with the suggested next commands and a `### Diagnostics` section with any findings. There is no padding, alignment, or color, and no JSON envelope. Everything the command produces, including errors, help, `--version`, and progress, goes to stdout, so an agent reads one stream. ## Data lines of Prisma ORM commands [#data-lines-of-prisma-orm-commands] Data lines are the plain values a command writes to standard output when it runs without `--json`. They are a stable interface, like `--json`: * Fields are separated by a tab and come in the order the table below shows. * A field whose JSON value is null or absent is an empty field. * A backslash, tab, newline or carriage return inside a value is written as `\\`, `\t`, `\n` or `\r`. * Paths are relative to the working directory. * New fields are only added at the end of a line. A field is never changed, removed or moved. | Command | Data lines | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `migration list` | `space`, `name`, `from`, `to`, `operations` per migration | | `migration status` | `space`, `name`, `from`, `to`, `operations`, `status` per migration; `status` is `applied`, `pending`, or empty when the JSON status is null | | `migration log` | `applied at`, `space`, `name`, `from`, `to`, `operations` per applied migration | | `migration graph` | `space`, `name`, `from`, `to` per migration; with `--dot`, the DOT text | | `migration show` | `keyvalue` lines, then `operationidclasslabel` per operation | | `migration check` | `space`, `code`, `where` (the path the failure is about) per failure | | `migration new`, `migration plan` | the directories written, each once, the baseline first | | `migration ref list` | `name`, `hash`, `invariants` (comma-separated) per ref | | `migration ref set` | the contract hash the ref now points at | | `db migrate` | `space`, `name`, `from`, `to`, `operations` per applied migration | | `db migrate --show` | `space`, `name`, `from`, `to` per migration that will run; there is no operation count before the run | | `db sign` | `space`, `status`, `storage hash` per space; `status` is the JSON status (`created`, `updated`, `unchanged`, `conflict` or `failed`) | | `orm init` | the paths of the files written | | `contract emit` | the paths of `contract.json` and `contract.d.ts` | | `contract print` | the PSL, when not written with `--output` | | `contract infer` | the path of the PSL file written | | `contract format` | the paths of the files formatted | The fields mean: * `space`: `app` for your own migrations, or the name of an extension that ships migrations, such as `pgvector`. * `from` and `to`: the contract hashes before and after the migration. * `operations`: the number of operations in the migration. * `invariants`: the ids of the data migrations (`dataTransform` operations with an `invariantId`) that must have run on a database that reaches the ref. * `storage hash`: the storage hash of the contract that `db sign` signed the space with. Some of these commands have no page of their own. `migration list` lists the migrations on disk. `migration log` lists the migrations the database has applied, in order. `migration graph` draws the migration graph. `migration check` checks that the migration files and the graph are consistent. `contract format` formats your PSL files in place. Two commands print a document instead of data lines: `contract print` prints the PSL and `migration graph --dot` prints the DOT text. Each is printed as it is, without escaping. ```bash npx prisma migration list | cut -f2 npx prisma migration status | awk -F'\t' '$6 == "pending" { print $2 }' ``` These commands print nothing on standard output. Their exit code is the result, and `--json` carries the document: * `db init` and `db update`: the exit code says whether the database was changed to match the contract. * `db verify`: the exit code says whether the database matches the contract. * `migration ref delete`: the exit code says whether the ref was deleted. `db schema` also prints nothing on standard output. It prints the schema as a tree on standard error, and `--json` gives the schema as a document. An error in a pipe is human text on standard error, with the same exit code as with `--json`. Use `npx prisma --help` when you need the exact command help from the installed version. The output modes and the JSON envelope these flags select are documented on [Configuration](https://www.prisma.io/docs/cli/configuration#output-modes). ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # Overview (/docs/cli) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Prisma CLI reference Location: Overview Prisma ORM ships with a unified Prisma CLI. One binary contains the ORM commands and the platform commands for [Prisma Composer](https://www.prisma.io/docs/composer), [Prisma Compute](https://www.prisma.io/docs/compute), Prisma Postgres, and object-store buckets. > [!NOTE] > Prisma ORM 7 users > > Prisma ORM 8 is a release candidate. Prisma ORM 7 remains fully supported; its docs live at [/orm/v7](https://www.prisma.io/docs/orm/v7) and its setup paths at [/v7/getting-started](https://www.prisma.io/docs/v7/getting-started). > > For what release candidate means, when the final release is expected, and how to stay on version 7, see [Release status](https://www.prisma.io/docs/orm/release-status). For the Prisma ORM 8 name of every Prisma ORM 7 API, see [Coming from Prisma ORM 7](https://www.prisma.io/docs/orm/coming-from-prisma-orm-7). The Prisma ORM CLI ships in the `prisma` package. Run it without installing: #### bun ```bash bunx prisma --help bunx prisma contract emit ``` #### pnpm ```bash pnpm prisma --help pnpm prisma contract emit ``` #### yarn ```bash yarn prisma --help yarn prisma contract emit ``` #### npm ```bash npx prisma --help npx prisma contract emit ``` With `prisma` installed in your project, these commands become plain `prisma contract emit` and so on. For a full app scaffold, follow [Create a new app with PostgreSQL](https://www.prisma.io/docs/prisma-orm/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. ## Platform commands [#platform-commands] The platform commands manage the services, databases, and buckets your app runs on. With [`deploy`](https://www.prisma.io/docs/cli/deploy) and [`dev`](https://www.prisma.io/docs/cli/dev) you deploy a [Prisma Composer](https://www.prisma.io/docs/composer) app to [Prisma Compute](https://www.prisma.io/docs/compute) and run it locally; with [`service`](https://www.prisma.io/docs/cli/service) and [`git`](https://www.prisma.io/docs/cli/git) you manage services, their versions, logs, and domains, and the repository connection. With [`postgres`](https://www.prisma.io/docs/cli/postgres) you spin up and manage [Prisma Postgres](https://www.prisma.io/docs/postgres) databases. With [`bucket`](https://www.prisma.io/docs/cli/bucket) you create blob-storage buckets and their access keys. [`auth`](https://www.prisma.io/docs/cli/auth), [`project`](https://www.prisma.io/docs/cli/project), and [`branch`](https://www.prisma.io/docs/cli/branch) handle the account, project, and branch plumbing around them. Each command group has its own page in this section. Deployments are created by `deploy`, by a git push once you [set up deploy on push](https://www.prisma.io/docs/compute/deploy-on-push), or from the [Console](https://pris.ly/pdp), and each deploy produces a service **version**. ## Common workflows [#common-workflows] Platform users deploy apps, create databases, and provision buckets with the [platform commands](#platform-commands), while ORM users manage their schema, contracts, and migrations with the ORM and migration commands. ### Deploy an app [#deploy-an-app] Sign in, then build and deploy a [Prisma Composer](https://www.prisma.io/docs/composer) app. `deploy` creates the project on its first run, and a new project needs a region, set in the deploy config or as `PRISMA_REGION`; see [`deploy`](https://www.prisma.io/docs/cli/deploy). #### bun ```bash bunx prisma auth login bun run build bunx prisma deploy ``` #### pnpm ```bash pnpm prisma auth login pnpm run build pnpm prisma deploy ``` #### yarn ```bash yarn prisma auth login yarn build yarn prisma deploy ``` #### npm ```bash npx prisma auth login npm run build npx prisma deploy ``` To deploy on every push, also connect the repository with [`git connect`](https://www.prisma.io/docs/cli/git) and add the deploy workflow; see [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push). Follow a deploy with [`service logs`](https://www.prisma.io/docs/cli/service) and manage the result with the [`service` commands](https://www.prisma.io/docs/cli/service). ### Create a database [#create-a-database] #### bun ```bash bunx prisma postgres create mydb bunx prisma postgres connection create mydb ``` #### pnpm ```bash pnpm prisma postgres create mydb pnpm prisma postgres connection create mydb ``` #### yarn ```bash yarn prisma postgres create mydb yarn prisma postgres connection create mydb ``` #### npm ```bash npx prisma postgres create mydb npx prisma postgres connection create mydb ``` `postgres create` prints a one-time connection URL; `postgres connection create` mints another when you need one. See [`postgres`](https://www.prisma.io/docs/cli/postgres). ### Create a bucket [#create-a-bucket] #### bun ```bash bunx prisma bucket create --name my-bucket bunx prisma bucket key create ``` #### pnpm ```bash pnpm prisma bucket create --name my-bucket pnpm prisma bucket key create ``` #### yarn ```bash yarn prisma bucket create --name my-bucket yarn prisma bucket key create ``` #### npm ```bash npx prisma bucket create --name my-bucket npx prisma bucket key create ``` `bucket key create` prints the key's one-time credentials. See [`bucket`](https://www.prisma.io/docs/cli/bucket). ### Start in an existing project [#start-in-an-existing-project] #### bun ```bash bunx prisma@latest orm init --target postgres --authoring psl bunx prisma contract emit bunx prisma db init --db "$DATABASE_URL" --advance-ref db ``` #### pnpm ```bash pnpm dlx prisma@latest orm init --target postgres --authoring psl pnpm prisma contract emit pnpm prisma db init --db "$DATABASE_URL" --advance-ref db ``` #### yarn ```bash yarn dlx prisma@latest orm init --target postgres --authoring psl yarn prisma contract emit yarn prisma db init --db "$DATABASE_URL" --advance-ref db ``` #### npm ```bash npx prisma@latest orm init --target postgres --authoring psl npx prisma contract emit npx prisma db init --db "$DATABASE_URL" --advance-ref db ``` `db init` and `db update` advance the [ref](https://www.prisma.io/docs/cli/migration-ref) named `db` on their own when you leave `--db` off and let the connection come from `prisma.config.ts`. Passing `--db` suppresses that, so add `--advance-ref db` to keep the ref current. Without it, `--db` leaves any existing `db` ref where it was, and a later [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) starts from that stale contract; if the ref was never created, `migration plan` refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` as soon as migrations exist on disk. ### Adopt an existing database [#adopt-an-existing-database] #### bun ```bash bunx prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma bunx prisma contract emit bunx prisma db sign --db "$DATABASE_URL" bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma pnpm prisma contract emit pnpm prisma db sign --db "$DATABASE_URL" pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma yarn prisma contract emit yarn prisma db sign --db "$DATABASE_URL" yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract infer --db "$DATABASE_URL" --output ./prisma/contract.prisma npx prisma contract emit npx prisma db sign --db "$DATABASE_URL" npx prisma db verify --db "$DATABASE_URL" ``` `db sign` also sets the `db` ref to the signed contract, so the next `migration plan` starts from the database you adopted. Pass `--no-advance-ref` to sign without moving a ref. ### Use checked-in migrations [#use-checked-in-migrations] #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_users bunx prisma migration status --db "$DATABASE_URL" bunx prisma db migrate --db "$DATABASE_URL" --advance-ref db bunx prisma db verify --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_users pnpm prisma migration status --db "$DATABASE_URL" pnpm prisma db migrate --db "$DATABASE_URL" --advance-ref db pnpm prisma db verify --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_users yarn prisma migration status --db "$DATABASE_URL" yarn prisma db migrate --db "$DATABASE_URL" --advance-ref db yarn prisma db verify --db "$DATABASE_URL" ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_users npx prisma migration status --db "$DATABASE_URL" npx prisma db migrate --db "$DATABASE_URL" --advance-ref db npx prisma db verify --db "$DATABASE_URL" ``` Plain `db migrate` never moves a ref; `--advance-ref db` is what keeps the next `migration plan` incremental. Leave it off in deploy and CI applies, where a repository ref should not move. ## Agent skills [#agent-skills] Prisma packages ship [agent skills](https://www.prisma.io/docs/ai/tools/skills): instructions that teach AI coding agents the installed version's commands and APIs. [`init`](https://www.prisma.io/docs/cli/init) prepares a repository once, and [`skills sync`](https://www.prisma.io/docs/cli/skills) keeps the installed copies matching your package versions. Install after `init`, so the `prisma` dev dependency it adds is in `node_modules`: #### bun ```bash bunx --bun prisma@latest init bun install bunx prisma skills sync ``` #### pnpm ```bash pnpm dlx prisma@latest init pnpm install pnpm prisma skills sync ``` #### yarn ```bash yarn dlx prisma@latest init yarn install yarn prisma skills sync ``` #### npm ```bash npx prisma@latest init npm install npx prisma skills sync ``` ## Other commands [#other-commands] A few commands ship without dedicated pages yet. `contract format` formats your PSL contract source in place, including a Prisma ORM 7 schema read through `prisma7Schema`, and `lsp` starts the Prisma ORM language server (spawned by editors, not run interactively; see [Editor support](https://www.prisma.io/docs/orm/contract-authoring/editor-support)). The `migration` group also has read-only inspection commands: `migration list` (on-disk migrations per [contract space](https://www.prisma.io/docs/orm/migrations/the-migration-graph#terms-used-on-this-page); `--space`, `--ascii`, `--legend`), `migration log` (executed history from the database ledger; `--db`, `--utc`, `--ascii`), `migration graph` (the chain of migrations; `--space`, `--dot` for Graphviz output, `--ascii`, `--legend`), and `migration check [target]` (artifact and graph integrity; `--space`). Run any of them with `--help` for the details. ## Global flags [#global-flags] Every command accepts the same set of output, prompt, and config flags. They are documented on [Global flags](https://www.prisma.io/docs/cli/global-flags). ## Related pages - [`Choose a Prisma ORM setup path`](https://www.prisma.io/docs/getting-started): Choose the fastest path to try Prisma ORM in a new or existing project. - [`Console`](https://www.prisma.io/docs/console): Learn how to use the Console to manage and integrate Prisma products into your application. - [`Introduction to Prisma ORM`](https://www.prisma.io/docs/prisma-orm): Prisma ORM 8 is a release candidate. - [`Local development`](https://www.prisma.io/docs/local-development): Run the whole Prisma stack on your machine, with your app on Bun, a local Prisma Postgres database, and local object storage. - [`Overview`](https://www.prisma.io/docs/guides): Practical, step-by-step guides for building with Prisma ORM and deploying to Prisma Compute, each one run end to end before it ships. # init (/docs/cli/init) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Prepare a repository for Prisma development. Location: CLI > init `init` prepares the current directory for Prisma development. It runs locally and calls no platform API. It does not scaffold the ORM: use [`orm init`](https://www.prisma.io/docs/cli/orm-init) to add the Prisma ORM config, contract, and runtime files to a project. `init` does four things: 1. Adds a `postinstall` script to `package.json` (`prisma skills sync || exit 0`), so the [Prisma agent skills](https://www.prisma.io/docs/cli/skills) resync on every install and upgrade. 2. Adds `prisma` to `devDependencies` in `package.json`, pinned to the CLI's version, unless it is already listed. It does not install it. 3. Scaffolds a `prisma.config.ts` recording which agents to install skills for, in the [`skills` config section](https://www.prisma.io/docs/cli/configuration#agent-skills). 4. Runs [`skills sync`](https://www.prisma.io/docs/cli/skills) once. It never prompts, always exits 0, and is safe to rerun: each step reports what is already done. A `prisma.config.ts`, `postinstall` script, or `prisma` entry that already exists is never edited. If `package.json` already has a different `postinstall` script, `init` reports it and tells you what to append instead of chaining or replacing it. ## Usage [#usage] #### bun ```bash bunx --bun prisma@latest init bun install ``` #### pnpm ```bash pnpm dlx prisma@latest init pnpm install ``` #### yarn ```bash yarn dlx prisma@latest init yarn install ``` #### npm ```bash npx prisma@latest init npm install ``` If `init` added `prisma`, run the install straight after, so the package is in `node_modules`. ## Options [#options] | Option | What it does | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--skills ` | Agents to install skills for, comma-separated: `claude`, `cursor`, `agents`, `devin`. Pass `none` to record that no agent skills are wanted. Default: all of them. | | `--postinstall`/`--no-postinstall` | Add the skills-sync `postinstall` hook. `--no-postinstall` skips that step. | ## Examples [#examples] #### bun ```bash bunx --bun prisma@latest init bunx --bun prisma@latest init --skills=claude,cursor bunx --bun prisma@latest init --skills=none bunx --bun prisma@latest init --no-postinstall ``` #### pnpm ```bash pnpm dlx prisma@latest init pnpm dlx prisma@latest init --skills=claude,cursor pnpm dlx prisma@latest init --skills=none pnpm dlx prisma@latest init --no-postinstall ``` #### yarn ```bash yarn dlx prisma@latest init yarn dlx prisma@latest init --skills=claude,cursor yarn dlx prisma@latest init --skills=none yarn dlx prisma@latest init --no-postinstall ``` #### npm ```bash npx prisma@latest init npx prisma@latest init --skills=claude,cursor npx prisma@latest init --skills=none npx prisma@latest init --no-postinstall ``` ## The scaffolded config [#the-scaffolded-config] `init` writes a minimal `prisma.config.ts` when none exists: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; export default definePrismaConfig({ skills: { agents: ["claude", "cursor", "agents", "devin"], }, }); ``` The `prisma/config` import resolves from your project's `node_modules`. Until `prisma` is installed, commands that read this file stop at `CLI.CONFIG_UNREADABLE`. See [Configuration](https://www.prisma.io/docs/cli/configuration). Only `init` writes the `postinstall` hook. [`orm init`](https://www.prisma.io/docs/cli/orm-init) also adds `prisma` to `devDependencies`. [`skills sync`](https://www.prisma.io/docs/cli/skills) never touches `package.json`. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # migration new (/docs/cli/migration-new) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Scaffold a Prisma ORM migration package for manual authoring. Location: CLI > migration new `migration new` creates a migration package with a `migration.ts` file for manual authoring. Use it when the generated plan is not enough and you want to write the migration operations yourself. The command is offline. It does not consult the database. ## Usage [#usage] #### bun ```bash bunx prisma migration new --name split-name ``` #### pnpm ```bash pnpm prisma migration new --name split-name ``` #### yarn ```bash yarn prisma migration new --name split-name ``` #### npm ```bash npx prisma migration new --name split-name ``` ## Options [#options] | Option | What it does | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--name ` | Sets the migration directory name suffix. | | `--from ` | Starts from the contract state an existing migration ends at: the `to` hash in that migration's `migration.json`, or a unique prefix of it. Without it, see [Where it starts](#where-it-starts). | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | `migration new --from` takes only a hash or a unique prefix of one. Unlike [`migration plan --from`](https://www.prisma.io/docs/cli/migration-plan#options), it does not accept a migration directory name or a ref name. It refuses `--from` when `migrations/app/` has no migrations, and refuses a prefix that matches more than one migration. Run `npx prisma migration list` to see the hashes of your migrations. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) compares it with the other commands. ## Where it starts [#where-it-starts] Without `--from`, `migration new` picks its starting point the way [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) does. The result depends on whether the [`db` ref](https://www.prisma.io/docs/cli/migration-ref#the-db-ref) exists and whether `migrations/app/` has migrations. The `db` ref is the file `migrations/app/refs/db.json`, which records the contract state you expect your local database to match. `migrations/app/` is the folder for your application's own migrations, and each extension package that ships migrations has its own folder beside it. * When the `db` ref exists and `migrations/app/` has migrations, it starts from the `db` ref. If the contract has not changed since that state, it refuses with `MIGRATION.NO_CHANGES`; to create a migration that holds only SQL or data changes on the current contract, pass `--from` with the `to` hash of your newest migration. * When there are no migrations and no `db` ref, it starts from an empty database. * When migrations exist but there is no `db` ref, it refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN`. Pass `--from` with the `to` hash of the migration to build on, or point the `db` ref at the state your database is on. To find that state, run `npx prisma migration status --db "$DATABASE_URL" --json`: the `currentContract` of the `app` entry in `result.spaces` is the hash of the contract state your database matches. Then run `npx prisma migration ref set db `, where `` is that hash or the directory name of the migration that ends at it. * When the `db` ref exists but there are no migrations, it refuses with `MIGRATION.HASH_NOT_IN_GRAPH`, because there is no migration yet that ends at the state the `db` ref names. Run `migration plan` first. It writes a [baseline migration](https://www.prisma.io/docs/orm/migrations/the-migration-graph#baselines), a migration from an empty database to that state, and then `migration new` can start from it. `migration plan` reads that state from the copy saved under `migrations/snapshots/` by the command that set the `db` ref, and if the copy is missing, it fails and asks you to restore `migrations/snapshots/` from version control. Before `8.0.0-rc.12`, `migration new` started from the newest migration. Scripts that relied on that should pass `--from` with the newest migration's `to` hash. ## Examples [#examples] #### bun ```bash bunx prisma migration new --name split-name bunx prisma migration new --name custom-fk --from abc123 ``` #### pnpm ```bash pnpm prisma migration new --name split-name pnpm prisma migration new --name custom-fk --from abc123 ``` #### yarn ```bash yarn prisma migration new --name split-name yarn prisma migration new --name custom-fk --from abc123 ``` #### npm ```bash npx prisma migration new --name split-name npx prisma migration new --name custom-fk --from abc123 ``` ## Data lines [#data-lines] Without `--json`, standard output gets one line: the directory the command wrote. So a script can open the new `migration.ts`: ```bash dir="$(npx prisma migration new --name split-name)" && "$EDITOR" "$dir/migration.ts" ``` [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ## After scaffolding [#after-scaffolding] Write the migration body in `migration.ts`, then run the file with Node so it emits `ops.json` and attests the package: ```bash node migration.ts ``` Inspect the result: #### bun ```bash bunx prisma migration show ``` #### pnpm ```bash pnpm prisma migration show ``` #### yarn ```bash yarn prisma migration show ``` #### npm ```bash npx prisma migration show ``` Apply the migration only after review: #### bun ```bash bunx prisma db migrate --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db migrate --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma db migrate --db "$DATABASE_URL" ``` #### npm ```bash npx prisma db migrate --db "$DATABASE_URL" ``` Manual migrations should still end at a contract state that matches the emitted contract. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # migration plan (/docs/cli/migration-plan) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Plan an on-disk migration from Prisma ORM contract changes. Location: CLI > migration plan `migration plan` compares the emitted contract against a starting contract and produces a new migration package with the required operations. The starting contract is whatever `--from` names, or the [ref](https://www.prisma.io/docs/cli/migration-ref) named `db` when `--from` is absent. With neither, what happens depends on the migrations already on disk: * **`migrations/app/` is empty.** The plan starts from an empty database and contains the full `CREATE` operations for the whole contract. This is the first migration in a new project. The command says so under its summary (`No db ref set — planning from an empty database`), and `--json` output carries `fromDefaulted: true`, so a plan that recreates a database you already have is easy to spot. If a database already exists, run `db init`, `db update`, or `db sign` first. * **Migrations already exist.** The command refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` rather than write a full-create package that no real database could apply. The error names the three exits: `migration ref set db ` to point the ref at the state your database is on, `--from ` to name the origin for this one plan, or `--from @empty` to plan from an empty database deliberately. Keep the `db` ref current and you never see the refusal. [`db init`](https://www.prisma.io/docs/cli/db-init) and [`db update`](https://www.prisma.io/docs/cli/db-update) advance it for you when you run them without `--db`; with `--db` you have to add `--advance-ref db`. [`db sign`](https://www.prisma.io/docs/cli/db-sign) advances it whenever it signs, `--db` or not. [`db migrate`](https://www.prisma.io/docs/cli/db-migrate) advances nothing unless you pass `--advance-ref db`. ### The automatic baseline [#the-automatic-baseline] Say `migrations/app/` has no migrations yet, the `db` ref is set, and `migrations/snapshots/` holds a copy of the contract the ref points at. Then `migration plan` writes a baseline: a migration from an empty database to the ref's contract. If your emitted contract has changed since then, the same run also writes a second migration with those changes. Expect one or two new directories in `git status`. `db migrate` never applies the baseline to a database that already records which contract it matches, such as one you ran `db sign` on. It applies only the migrations after the contract that database records. The baseline only creates things, because it is planned from an empty database, so it never removes data. The second migration can remove data, and `migration plan` asks about it before it writes either one, as [Renames and data loss](#renames-and-data-loss) describes. If a migration already starts from the contract the `db` ref points at, `migration plan` writes a second migration that starts from the same contract, so the [migration history](https://www.prisma.io/docs/orm/migrations/the-migration-graph) splits into two branches. This happens, for example, after `db migrate` without `--advance-ref db`, which applies migrations but leaves the `db` ref where it was. `migration plan` still writes the migration and prints a warning. A database that has already run the existing migration then has no migration leading to your new contract, so `db migrate` on that database fails with `MIGRATION.PATH_UNREACHABLE`. To build on the newest migration instead, delete the directory this run wrote and plan again with `--from` set to the newest migration's directory name. The command is offline, so it does not need a database connection. ## Usage [#usage] #### bun ```bash bunx prisma migration plan --name add_users_table ``` #### pnpm ```bash pnpm prisma migration plan --name add_users_table ``` #### yarn ```bash yarn prisma migration plan --name add_users_table ``` #### npm ```bash npx prisma migration plan --name add_users_table ``` ## Options [#options] | Option | What it does | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--name ` | Sets the migration directory name suffix. | | `--from ` | Uses a specific starting contract state instead of the `db` ref. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, [`^`](#contract-references), or [`@empty`](#contract-references). `@db` is not accepted here, because `migration plan` is offline and cannot read a database. `@contract` is not accepted either. | | `--to ` | Sets the destination contract state. Defaults to the emitted contract. Accepts the same forms as `--from`, except `@empty`, which is refused as a destination. | | `--rename :` | Renames a namespace, a model or a field and keeps its rows, instead of dropping and creating it, or moves a model to another namespace. On PostgreSQL and SQLite, also renames an enum value in the rows that hold it, as in `--rename Status.ARCHIVED:Status.RETIRED`, a field of a value object, as in `--rename GeoPoint.lat:GeoPoint.latitude`, and a variant. Repeatable. See [Renames and data loss](#renames-and-data-loss). | | `--delete ` | Lets the migration lose the data of a model, a field, a table no model stores, every model of a namespace the contract removed, or, on PostgreSQL and SQLite, an enum value the contract removed, a field of a value object, or the rows of a variant. For a type change, accepts the database's own cast. Repeatable. | | `--convert ` | For a type change that can lose values, writes an `alterColumnType` whose conversion you fill in. On PostgreSQL and SQLite, `--convert ` rewrites the stored discriminator value of a variant whose value changed. Repeatable. See [Type changes and required fields](#type-changes-and-required-fields). | | `--backfill ` | For a new required field or a field made required, writes a backfill step you fill in, instead of a temporary value. On PostgreSQL and SQLite, also takes a field of a value object, as in `--backfill GeoPoint.country`. Repeatable. See [Type changes and required fields](#type-changes-and-required-fields). | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ### Contract references [#contract-references] A ref name is a name you gave a contract state with [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref), such as `prod`. `^` is a migration directory name followed by `^`, and it names the contract state before that migration, while the directory name alone names the state after it. `@empty` names the empty database, before any migration. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) lists the forms for every command. ## Renames and data loss [#renames-and-data-loss] When the migration would lose data, because it drops a model, a field, a table or a collection, or changes a field's type in a way that can change values, `migration plan` asks you what to do before it writes anything. Answer each question on the command line: * `--delete ` lets the data go. A subject is `Model`, `Model.field`, or, for data no model stores, its storage name. * `--rename :` keeps the data. The migration renames the table or column, and the constraints and indexes named after it, instead of dropping and creating it. Each side is `Model`, `namespace.Model`, `Model.field` or `namespace.Model.field`, and a field's model is named as the new contract names it: `--rename Profile:User --rename User.name:User.fullName`. A rename on the command line is planned from the start, so the drop it replaces is never asked about. * `--convert ` answers a type change that can lose values: the migration gets a `placeholder(...)` call that you replace with your own conversion code. #### bun ```bash bunx prisma migration plan --name rename_full_name --rename User.name:User.fullName ``` #### pnpm ```bash pnpm prisma migration plan --name rename_full_name --rename User.name:User.fullName ``` #### yarn ```bash yarn prisma migration plan --name rename_full_name --rename User.name:User.fullName ``` #### npm ```bash npx prisma migration plan --name rename_full_name --rename User.name:User.fullName ``` In a terminal, the command asks the questions you did not answer with a flag. With `--yes`, in a CI job, or with `--no-interactive`, where it cannot ask, it fails with `CLI.CONSENT_REQUIRED` instead. The error lists each question, and its next actions give the flags to add. `--rename` is offered only for a model or field the new contract no longer has, so a field whose type changes is answered with `--convert` or `--delete`. `--confirm` answers none of these questions. Dropping an index, a unique or foreign-key constraint, a check, a default or a native enum type, and setting `NOT NULL`, lose no data, so the command asks nothing about them. On PostgreSQL, a changed `onDelete` or `onUpdate` on a relation is planned as dropping the foreign key and adding it back with the new actions. A changed or removed primary key is planned the same way, and because PostgreSQL does not drop a primary key while a foreign key points at it, the migration first drops every foreign key that points at the old key, then adds back each one the new contract still declares. A foreign key the new contract leaves out stays dropped. When such a foreign key is on a table the migration must not change, such as a table whose model has an [`@@control(...)`](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#control-policy) value other than `managed`, or a table in a schema the contract no longer declares, the command refuses and names that foreign key. Before `8.0.0-rc.20`, both changes failed with `MIGRATION.PLANNING_FAILED`. On PostgreSQL, a namespace is renamed, moved or removed with the same flags. `--rename billing:finance` renames the schema, and everything in it stays in it. `--rename public.Invoice:billing.Invoice` moves the model's table to another schema with its rows, constraints, indexes and policies, and creates the schema first when the database does not have it. Namespace renames run before the other renames, whatever order you give them in. `public` and a schema another contract space declares are not renamed. A namespace is a PostgreSQL schema that your contract declares with a `namespace` block. When you remove that block, the command asks about each model in the namespace, as it asks about any removed model. Answer with the flag that matches what you meant: * If you renamed the namespace, answer with `--rename billing:finance`. Nothing is dropped. * To keep one model's data, move it to a namespace the contract keeps, as in `--rename billing.Invoice:public.Invoice`. * To drop the namespace, answer with `--delete billing`. The migration drops each of its tables and then the schema. `migration plan` does not read the database, so it cannot see a table, view or function in that schema that no contract declares. If the schema holds one, `db migrate` fails before it drops the schema, and the error names the object. Drop or move it yourself, then run `db migrate` again. The command leaves alone a schema that no contract declared, such as Supabase's `auth`, and a namespace that only another contract space declares. Before `8.0.0-rc.20`, the command did not ask about a removed namespace and left its tables in place. On PostgreSQL and SQLite, removing a member from an `enum` block, or changing the value a member stores, is asked about too, because rows may hold the old value. The command asks once for each value, however many columns hold it: * If you renamed the member, answer with `--rename Status.ARCHIVED:Status.RETIRED`. The migration changes the stored value in every column and list that holds it. * To let the value go, answer with `--delete Status.ARCHIVED`. Optional columns that hold it are set to `NULL`, and lists lose it. A required column cannot take `NULL`, so while any of its rows hold the value, the apply fails with `MIGRATION.PRECHECK_FAILED` before it changes anything. The error counts those rows and says how to keep them. A member you rename while keeping its stored value, such as `RETIRED = "archived"` in place of `ARCHIVED = "archived"`, changes no rows, so nothing is asked. A member that keeps its name but stores a new value, and two members that swap their stored values, can only be answered with `--delete`. To keep those rows, the question names the `this.removeStoredValue(...)` call in the planned `migration.ts` to replace with `this.replaceStoredValue(...)` calls, and the `node migration.ts` command that runs it. [Stored enum values](https://www.prisma.io/docs/orm/reference/migration-api#stored-enum-values) in the migration API reference shows both calls. Native PostgreSQL enums (`pg.enum(...)`) are not affected. Before `8.0.0-rc.21`, PostgreSQL failed at apply when a row held the removed value, and SQLite planned nothing. On PostgreSQL and SQLite, a field of a [value object](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#value-objects) is asked about too when the contract renames it, removes it, or makes it required. Name the field through its value object, such as `GeoPoint.lat`, not through a model. Each statement acts on every column that holds the value object, including lists of it and value objects nested in another: * `--rename GeoPoint.lat:GeoPoint.latitude` renames the key in every stored object. * `--delete GeoPoint.lng` removes the key from every stored object. * An enum value inside a value object is asked about as the enum value. `--rename Status.ARCHIVED:Status.RETIRED` rewrites it wherever it is stored, and `--delete Status.DRAFT` sets an optional field that holds it to JSON `null` and takes it out of a list. * `--backfill GeoPoint.country` fills a field that becomes required. The migration gets a `fillStoredKey` step whose value is `placeholder('GeoPoint.country:value')`. Replace the placeholder with one JSON value, then run `node migration.ts`. `db migrate` refuses the migration while the placeholder is left. Without `--backfill`, the command refuses and names the flag. A [variant](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#base-models-and-variants) whose discriminator value changes, or that the contract removes, is asked about as a model: * `--convert Bug` rewrites the old value to the new one in the base table's discriminator column. * `--rename Bug:Defect` of a variant whose value also changed rewrites the value in the same way. * `--delete Bug` deletes the rows that hold the old value, then drops a removed variant's own table or the columns only it used. On MongoDB, `--rename` of a value object field or of a variant whose discriminator value changes is refused, and so are `--convert` of a variant and `--backfill` of a value object field. On MongoDB, a model rename renames its collection and keeps its documents, indexes and validator, and a field rename renames the field in every document that holds it. Removing a field from a model removes it from every document that holds it, so the command asks about it as it asks about a dropped collection: answer with `--delete User.nickname` or `--rename User.nickname:User.`. The planner refuses a rename of the field stored as `_id`, of a field whose stored name contains `.` or starts with `$`, of a time-series collection, and of a variant whose discriminator value changes, and says what to do instead. On MongoDB, `--rename` and `--delete` name fields by their names in the schema, not by the names they are stored under. For a field `id ObjectId @id @map("_id")`, write `--rename User.id:User.userId`, not `User._id`. The first MongoDB migration you plan after upgrading from a release before `8.0.0-rc.19` is the exception. The [upgrade instructions](https://github.com/prisma/orm/blob/v8.0.0-rc.19/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/) include a script that rewrites the copies of your old contract under `migrations/`, and those copies name each field by its stored name. That first migration starts from such a copy, so in it you name the old field by its stored name and the new field by its schema name. For a field that was `name String @map("display_name")` and is now `title String`, write `--rename User.display_name:User.title`. From the next migration on, use schema names only. ## Type changes and required fields [#type-changes-and-required-fields] On PostgreSQL and SQLite, a type change that can lose values, such as `String` to `Int` or a longer `varchar` to a shorter one, is a question like a drop. Answer it in one of two ways: * `--convert ` writes an `alterColumnType` with `using: placeholder(':convert')`. Replace the placeholder with the conversion as SQL over the column, such as `using: '"age"::integer'`, then run `node migration.ts`. On SQLite the slot is the column's copy expression in `recreateTable`, such as `copyExpressions: { age: 'CAST("age" AS INTEGER)' }`. * `--delete ` lets the database's own cast run. It may cut or round values, and a value it cannot cast fails the apply. A new required field on a table with rows gets a temporary value in the existing rows, such as `''` for text or `0` for a number, and the command's output names it. An optional field made required is tightened directly, so the apply fails while any row holds `NULL`, with a message that counts those rows. To fill the rows yourself, pass `--backfill `: the migration gets a `dataTransform` step with `check` and `run` placeholders to fill in, as [Editing a migration](https://www.prisma.io/docs/orm/migrations/editing-a-migration) shows. A new unique, primary-key or foreign-key field has no temporary value, so use `--backfill` when the table has rows. #### bun ```bash bunx prisma migration plan --name age_to_int --convert User.age --backfill User.displayName ``` #### pnpm ```bash pnpm prisma migration plan --name age_to_int --convert User.age --backfill User.displayName ``` #### yarn ```bash yarn prisma migration plan --name age_to_int --convert User.age --backfill User.displayName ``` #### npm ```bash npx prisma migration plan --name age_to_int --convert User.age --backfill User.displayName ``` ## When nothing in the database changes [#no-database-change] If the storage part of the contract did not change, `migration plan` writes nothing and reports `No changes detected between contracts`. That is not an error, and there is nothing to do. If the storage part changed but the database needs no change, `migration plan` writes nothing and fails with `MIGRATION.PLANNING_FAILED`. This happens after a Prisma upgrade that changes how `contract.json` records values, after you change how a field's values are written in `contract.json` while its database type stays the same, or after you change a control policy. In that case the message gives the next step: * If you deploy with migrations, run `prisma migration new --from `, with the hash from the message, to write a migration with no operations, then `prisma db migrate`. * If you manage the database with `db init` or `db update`, run [`prisma db sign`](https://www.prisma.io/docs/cli/db-sign) on each database instead. If you expected the database to change, report it with the output of `prisma migration plan --json`. ## Recommended flow [#recommended-flow] #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_users_table bunx prisma migration show ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_users_table pnpm prisma migration show ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_users_table yarn prisma migration show ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_users_table npx prisma migration show ``` Review the generated migration package before applying it with [`db migrate`](https://www.prisma.io/docs/cli/db-migrate). ## Planning a rollback [#planning-a-rollback] Because `--to` accepts `^` (the source contract of a migration), you can plan a migration that walks back a change: #### bun ```bash bunx prisma migration plan --to ^ --name rollback ``` #### pnpm ```bash pnpm prisma migration plan --to ^ --name rollback ``` #### yarn ```bash yarn prisma migration plan --to ^ --name rollback ``` #### npm ```bash npx prisma migration plan --to ^ --name rollback ``` ## Data lines [#data-lines] Without `--json`, standard output gets one line per directory the command wrote, each once: the [automatic baseline](#the-automatic-baseline) first when the command wrote one, then the new migration, then any migration it wrote for an extension's contract space. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ## When to use migration plan [#when-to-use-migration-plan] Use `migration plan` when your team wants database changes reviewed in version control. For local prototypes where review is not needed, [`db update`](https://www.prisma.io/docs/cli/db-update) is usually faster. If the generated migration is not the migration you want, use [`migration new`](https://www.prisma.io/docs/cli/migration-new) and author the migration manually. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # migration ref (/docs/cli/migration-ref) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Manage named Prisma ORM refs that point at contracts. Location: CLI > migration ref A ref is a name, such as `staging` or `production`, for the contract state an environment should match. The contract is your schema as [`contract emit`](https://www.prisma.io/docs/cli/contract-emit) writes it to `contract.json`, and each version of it has a hash. Use refs when an environment should be migrated to a state you choose instead of to your latest migration. Other commands then take the name in place of a contract hash: [`db migrate --to production`](https://www.prisma.io/docs/cli/db-migrate), [`db update --to production`](https://www.prisma.io/docs/cli/db-update), or [`db sign production`](https://www.prisma.io/docs/cli/db-sign). `migration ref set` accepts only a contract that one of your migrations produces, so plan a migration for a change before you set a ref to it. `db init`, `db update`, and `db sign` can update a ref to a contract that no migration produces. Each ref is a file in your migrations folder, by default `migrations/app/refs/.json`, so commit it with your migrations. The `migration ref` commands change only these files and never connect to a database. ## The db ref [#the-db-ref] The `db` ref records the contract state you expect your local database to match. When you run [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) without `--from`, it plans from the `db` ref, so as long as the ref is up to date, each plan contains only your latest change. These commands update the `db` ref for you: * [`db init`](https://www.prisma.io/docs/cli/db-init) and [`db update`](https://www.prisma.io/docs/cli/db-update) update it when they take the connection from `prisma.config.ts`. When you pass `--db`, they update it only if you also pass `--advance-ref db`. With `--advance-ref `, they update that ref instead. * [`db sign`](https://www.prisma.io/docs/cli/db-sign) updates it after it succeeds, with or without `--db`. Pass `--no-advance-ref` to stop it, or `--advance-ref ` to update that ref instead. * [`db migrate`](https://www.prisma.io/docs/cli/db-migrate) updates it only when you pass `--advance-ref db`. Without that flag it never changes the file, so a deploy or CI run leaves your repository unchanged. In CI, run `db init` and `db update` with `--db` for the same reason. You can also set it yourself with `migration ref set db `. ## Usage [#usage] #### bun ```bash bunx prisma migration ref set production 4cb4256 bunx prisma migration ref list bunx prisma migration ref delete production ``` #### pnpm ```bash pnpm prisma migration ref set production 4cb4256 pnpm prisma migration ref list pnpm prisma migration ref delete production ``` #### yarn ```bash yarn prisma migration ref set production 4cb4256 yarn prisma migration ref list yarn prisma migration ref delete production ``` #### npm ```bash npx prisma migration ref set production 4cb4256 npx prisma migration ref list npx prisma migration ref delete production ``` ## Subcommands [#subcommands] | Subcommand | What it does | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `set ` | Points a ref at a contract, and replaces its target without asking if the ref already exists. The contract is a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash or the start of one, another ref name, a migration directory name, or `^` for the state before that migration. | | `list` | Lists every ref with the contract hash it points at. | | `delete ` | Deletes a ref. The contract it pointed at is untouched. | ## Ref names [#ref-names] A ref name is made of parts separated by forward slashes. Each part uses lowercase letters, digits, and hyphens, and starts and ends with a letter or digit. So `staging`, `prod-2`, and `staging/eu` are valid, and `Prod`, `prod_2`, `release.1`, `x-`, and `a//b` are refused. ## When a subcommand refuses [#when-a-subcommand-refuses] A refused subcommand changes nothing and exits with code `2`. The error code is printed in square brackets on standard error, and with `--json`, standard output gets one line whose `envelope.error.code` holds it: | You ran | Error code | What to do | | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | `set` or `delete` with a name that breaks the rules above | [`MIGRATION.INVALID_REF_NAME`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.INVALID_REF_NAME) | Choose a name that follows the rules. | | `set` with a contract reference that matches nothing | [`MIGRATION.REF_NOT_FOUND`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.REF_NOT_FOUND) | Check the hash, or the names in `migration ref list`. | | `set` with a hash that no migration produces, such as the hash of a change you have not planned yet | [`MIGRATION.HASH_NOT_IN_GRAPH`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.HASH_NOT_IN_GRAPH) | Run [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) first, or pass the name of an existing migration. | | `set` with `@db`, which means the live database | [`MIGRATION.HASH_NOT_IN_GRAPH`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.HASH_NOT_IN_GRAPH) | Pass a hash or a migration directory name, because `migration ref` never reads the database. | | `set` with `@empty`, or with `^` for your first migration, which both mean an empty database | [`MIGRATION.REF_SET_EMPTY_SENTINEL`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.REF_SET_EMPTY_SENTINEL) | Point the ref at a migration. | | `delete` with a ref that does not exist | [`MIGRATION.UNKNOWN_REF`](https://www.prisma.io/docs/orm/reference/error-reference#MIGRATION.UNKNOWN_REF) | Check the names in `migration ref list`. | To delete a ref only if it exists, check the list first. Reading the list into a variable makes the script stop if `list` itself fails: ```bash set -e refs=$(npx prisma migration ref list) if printf '%s\n' "$refs" | cut -f1 | grep -qx staging; then npx prisma migration ref delete staging fi ``` ## Data lines [#data-lines] Without `--json`, the subcommands print these data lines on standard output: * `list`: one line per ref, with three fields separated by tabs: `name`, `hash`, and `invariants`. `invariants` lists the ids of the data operations that migrating to the ref must run, separated by commas, and is empty when there are none. * `set`: one line, the contract hash the ref now points at. * `delete`: nothing. It exits with code `0` when it deleted the ref. ```bash npx prisma migration ref list | cut -f1 ``` [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ## Example workflow [#example-workflow] #### bun ```bash bunx prisma migration ref set production 20260101T1000_add_user bunx prisma migration status --db "$DATABASE_URL" --to production bunx prisma db migrate --db "$DATABASE_URL" --to production ``` #### pnpm ```bash pnpm prisma migration ref set production 20260101T1000_add_user pnpm prisma migration status --db "$DATABASE_URL" --to production pnpm prisma db migrate --db "$DATABASE_URL" --to production ``` #### yarn ```bash yarn prisma migration ref set production 20260101T1000_add_user yarn prisma migration status --db "$DATABASE_URL" --to production yarn prisma db migrate --db "$DATABASE_URL" --to production ``` #### npm ```bash npx prisma migration ref set production 20260101T1000_add_user npx prisma migration status --db "$DATABASE_URL" --to production npx prisma db migrate --db "$DATABASE_URL" --to production ``` If you pass `--advance-ref ` to a command that changes the database, that command also points the ref at the state it applied, once it succeeds. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # migration show (/docs/cli/migration-show) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Inspect a Prisma ORM migration package. Location: CLI > migration show `migration show` displays the operations, statement preview, and metadata for one migration package. Use this command during review before applying a migration package. The command is offline. It does not consult the database. ## Usage [#usage] #### bun ```bash bunx prisma migration show ``` #### pnpm ```bash pnpm prisma migration show ``` #### yarn ```bash yarn prisma migration show ``` #### npm ```bash npx prisma migration show ``` ## Options [#options] | Argument or option | What it does | | ------------------ | ------------------------------------------------------------------------------------ | | `` | The migration to inspect: a directory name, a hash or hash prefix, a ref, or a path. | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ## Examples [#examples] #### bun ```bash bunx prisma migration show 20260101_100000_add_user bunx prisma migration show a1b2c3 bunx prisma migration show migrations/app/20260101_100000_add_user bunx prisma migration show 20260101_100000_add_user --json ``` #### pnpm ```bash pnpm prisma migration show 20260101_100000_add_user pnpm prisma migration show a1b2c3 pnpm prisma migration show migrations/app/20260101_100000_add_user pnpm prisma migration show 20260101_100000_add_user --json ``` #### yarn ```bash yarn prisma migration show 20260101_100000_add_user yarn prisma migration show a1b2c3 yarn prisma migration show migrations/app/20260101_100000_add_user yarn prisma migration show 20260101_100000_add_user --json ``` #### npm ```bash npx prisma migration show 20260101_100000_add_user npx prisma migration show a1b2c3 npx prisma migration show migrations/app/20260101_100000_add_user npx prisma migration show 20260101_100000_add_user --json ``` ## Data lines [#data-lines] Without `--json`, standard output gets one `keyvalue` line for each of `name`, `space`, `from`, `to`, `hash` and `created`, in that order. A key whose value is absent has no line. Then it gets one line per operation, with four fields separated by tabs: the word `operation`, the operation's id, its class, and its label. The class says what kind of change the operation makes: `additive`, `widening`, `destructive` or `data`. The label is the one-line description the CLI prints for the operation. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ```bash npx prisma migration show 20260101_100000_add_user | awk -F'\t' '$1 == "to" { print $2 }' ``` ## What to check [#what-to-check] Before applying, review: * the source and destination contract hashes * the planned operations * generated SQL statements or operation payloads * the migration's metadata ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # migration status (/docs/cli/migration-status) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Show the Prisma ORM migration path and pending status. Location: CLI > migration status The database stores a marker, a row that says which version of your contract it currently matches. `migration status` compares that marker with a target version and lists the migrations in between. The target is the contract you last ran `contract emit` on, unless `--to` names another. Use it before and after [`db migrate`](https://www.prisma.io/docs/cli/db-migrate), and when debugging why an environment is not at the expected contract state. ## Usage [#usage] #### bun ```bash bunx prisma migration status --db "$DATABASE_URL" ``` #### pnpm ```bash pnpm prisma migration status --db "$DATABASE_URL" ``` #### yarn ```bash yarn prisma migration status --db "$DATABASE_URL" ``` #### npm ```bash npx prisma migration status --db "$DATABASE_URL" ``` ## Options [#options] | Option | What it does | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--db ` | Connects to the database. | | `--space ` | Narrows output to a single [contract space](#contract-spaces), named by its directory under `migrations/`. | | `--to ` | Sets the target contract state. Accepts a [contract reference](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms): a hash, a hash prefix, a [ref name](#contract-references), a migration directory name, [`^`](#contract-references), [`@contract`](#contract-references), [`@db`](#contract-references), or [`@empty`](#contract-references). | | `--from ` | Sets the origin contract state, and accepts the same forms as `--to`. With `--from`, the command computes the path offline and does not need a database. It needs one when `--from` or `--to` is `@db`, because it then reads the marker from the database. | | `--legend` | Prints a key to the symbols in the rows (`○`, the arrows, `✓`, `⧗`, `∅`) and to the labels. | | `--ascii` | Uses ASCII glyphs (pipe-friendly). | | `--config ` | Read this config file instead of `./prisma.config.ts`. | | `--json` | Prints a machine-readable result. | ### Contract spaces [#contract-spaces] Prisma ORM keeps one migration history for your own models, called the `app` space, in `migrations/app/`, and one for each [extension package](https://www.prisma.io/docs/orm/extensions/using-extensions) that ships its own migrations, such as pgvector. Each of these histories is a [contract space](https://www.prisma.io/docs/orm/migrations/the-migration-graph#terms-used-on-this-page). Pass `--space app` to see only your own migrations. ### Contract references [#contract-references] A ref name is a name you gave a contract state with [`migration ref set`](https://www.prisma.io/docs/cli/migration-ref), such as `prod`. `^` is a migration directory name followed by `^`, and it names the contract state before that migration, while the directory name alone names the state after it. `@contract` names the contract in `contract.json`, which `contract emit` writes. `@db` names the contract state that the database's marker records. `@empty` names the empty database, before any migration. [Contract references each command accepts](https://www.prisma.io/docs/orm/migrations/the-migration-graph#contract-reference-forms) lists the forms for every command. ## Examples [#examples] #### bun ```bash bunx prisma migration status --db "$DATABASE_URL" bunx prisma migration status --to production bunx prisma migration status --from abc123 --to production bunx prisma migration status --ascii ``` #### pnpm ```bash pnpm prisma migration status --db "$DATABASE_URL" pnpm prisma migration status --to production pnpm prisma migration status --from abc123 --to production pnpm prisma migration status --ascii ``` #### yarn ```bash yarn prisma migration status --db "$DATABASE_URL" yarn prisma migration status --to production yarn prisma migration status --from abc123 --to production yarn prisma migration status --ascii ``` #### npm ```bash npx prisma migration status --db "$DATABASE_URL" npx prisma migration status --to production npx prisma migration status --from abc123 --to production npx prisma migration status --ascii ``` ## Reading the result [#reading-the-result] ### Sample output [#sample-output] When you do not pass `--db`, the command connects to `db.connection` in `prisma.config.ts`. With one migration applied and one pending, `npx prisma migration status` prints: ```text │ migrations: migrations │ database: postgresql://****@localhost:54329/gaps ○ a4c3fa7 @contract │↑ 20260929T1558_add_user_phone 91e7f9f → a4c3fa7 1 ops ⧗ pending ○ 91e7f9f @db (db) │↑ 20260929T1558_baseline ∅ → 91e7f9f 6 ops ✓ applied ○ ∅ ⚠ 1 pending — run `prisma db migrate --to a4c3fa7fc3b2` ``` Read the drawing from the bottom up, because the earliest state is the bottom row. `∅` is the empty database, before any migration. `@contract` marks the contract in `contract.json`. `@db` marks the contract state that the database's marker records. `(db)` is the `db` [ref](https://www.prisma.io/docs/cli/migration-ref), the file `migrations/app/refs/db.json`, which records the contract state your development database is at. [`db init`](https://www.prisma.io/docs/cli/db-init) writes that file, and so does `db migrate --advance-ref db`. In this output `@db` and `(db)` are on the same row, because the marker and the `db` ref name the same state. [Check before, preview, then apply](https://www.prisma.io/docs/orm/migrations/applying-a-migration#check-before-preview-then-apply) explains each row and each label in more detail. The last line suggests the command to run next. It names the pending state by the first 12 characters of its hash, `a4c3fa7fc3b2`, which is the same hash the drawing shortens to 7 characters, `a4c3fa7`. With `--db`, status reads the marker from the database and compares it with the target. With `--from`, it starts from the state you name instead. It then needs no database, unless `--from` or `--to` is `@db`. ### Warnings [#warnings] When the command warns with `MIGRATION.MARKER_NOT_IN_HISTORY`, the marker in the database records a contract state that is not in your migration history. This is one kind of drift, and the next `db migrate` on that database fails with `MIGRATION.MARKER_MISMATCH`. To fix it, see [Drift](https://www.prisma.io/docs/orm/migrations/rollbacks-and-recovery#drift-when-the-database-isnt-where-migrations-left-it). ### Data lines [#data-lines] The drawing goes to standard error. Without `--json`, standard output gets one line per migration on disk, with these fields separated by tabs: `space`, `name`, `from`, `to`, the number of operations, and `status`. `status` is `applied`, `pending`, or empty when the migration is not on the way to the target. [Global flags](https://www.prisma.io/docs/cli/global-flags#data-lines-of-prisma-orm-commands) lists the rules data lines follow. ```bash npx prisma migration status --db "$DATABASE_URL" | awk -F'\t' '$6 == "pending" { print $2 }' ``` ### JSON output [#json-output] With `--json`, the command prints one `"kind": "result"` line. Inside its `envelope`: * `result.summary` is the sentence the human output ends with, such as `Up to date` or a count of pending migrations. * `result.spaces[].migrations[]` lists each migration on disk with a `status`: `pending` (on the way to the target, not yet applied), `applied` (on the way to the target, already applied), or `null` (not on the way to the target). * `diagnostics[]`, beside `result` rather than inside it, lists each problem found. Each entry has a `code`, for example `MIGRATION.MARKER_NOT_IN_HISTORY`, a `summary`, and a `severity`, which this command always sets to `warn`. The exit code is 0 even when `diagnostics` is not empty. A non-zero exit code means the command itself failed, for example with `MIGRATION.REF_NOT_FOUND` when `--to` names a ref that does not exist. ## Related commands [#related-commands] The `migration` group has three more read-only views: `migration graph` draws the chain of migrations, `migration log` lists what has run, and `migration list` lists the migrations on disk. Run each with `--help` for details. Use [`db verify`](https://www.prisma.io/docs/cli/db-verify) after applying migrations to check the final database shape against the emitted contract. ## Related pages - [`auth`](https://www.prisma.io/docs/cli/auth): Sign in to your Prisma account from the CLI, sign out, and manage workspace sessions. - [`branch`](https://www.prisma.io/docs/cli/branch): List platform branches for a project. - [`bucket`](https://www.prisma.io/docs/cli/bucket): Create and manage object-store buckets. - [`Configuration`](https://www.prisma.io/docs/cli/configuration): Configure Prisma ORM CLI commands with prisma.config.ts and global flags. - [`contract emit`](https://www.prisma.io/docs/cli/contract-emit): Emit Prisma ORM contract artifacts. # orm init (/docs/cli/orm-init) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Initialize Prisma ORM files in a project. Location: CLI > orm init `orm init` scaffolds the Prisma ORM config, contract source, and runtime files inside an existing project, installs dependencies, and emits the contract. It gets you from zero to typed queries in one step. Follow [Create a new app with PostgreSQL](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql) when you want a complete new application template. Use `orm init` when you already have a project and want to add the lower-level Prisma ORM files. ## Usage [#usage] Run it interactively for a guided setup: #### bun ```bash bunx prisma@latest orm init ``` #### pnpm ```bash pnpm dlx prisma@latest orm init ``` #### yarn ```bash yarn dlx prisma@latest orm init ``` #### npm ```bash npx prisma@latest orm init ``` Or supply `--target` and `--authoring` for a fully scriptable run (CI, AI coding agents, automation): #### bun ```bash bunx prisma@latest orm init --yes --target postgres --authoring psl ``` #### pnpm ```bash pnpm dlx prisma@latest orm init --yes --target postgres --authoring psl ``` #### yarn ```bash yarn dlx prisma@latest orm init --yes --target postgres --authoring psl ``` #### npm ```bash npx prisma@latest orm init --yes --target postgres --authoring psl ``` ## Options [#options] | Option | What it does | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--target ` | Sets the database target. Use `postgres` or `mongodb`. | | `--authoring ``` Replace the home page and add the other two pages: ```astro title="src/pages/index.astro" --- import Base from "../layouts/Base.astro"; ---

Ship faster with Acme

Everything your team needs to go from idea to production.

See pricing ``` ```astro title="src/pages/pricing.astro" --- import Base from "../layouts/Base.astro"; const plans = [ { name: "Starter", price: "$0", blurb: "For side projects." }, { name: "Team", price: "$29", blurb: "For growing teams." }, ]; ---

Pricing

    {plans.map((plan) => (
  • {plan.name} {plan.price}/month: {plan.blurb}
  • ))}
``` ```astro title="src/pages/about.astro" --- import Base from "../layouts/Base.astro"; ---

About Acme

We build tools for teams that ship.

``` Run `npm run dev` and open [http://localhost:4321](http://localhost:4321) to check the pages, then stop the dev server. ## 3. Add the Node adapter [#3-add-the-node-adapter] Compute needs a server entrypoint to run. A plain Astro build only produces HTML files, so add the Node adapter in standalone mode: #### bun ```bash bunx astro add node --yes ``` #### pnpm ```bash pnpm dlx astro add node --yes ``` #### yarn ```bash yarn dlx astro add node --yes ``` #### npm ```bash npx astro add node --yes ``` ```js title="astro.config.mjs" // @ts-check import { defineConfig } from 'astro/config'; import node from '@astrojs/node'; // https://astro.build/config export default defineConfig({ adapter: node({ mode: 'standalone' }) }); ``` Leave `output` unset. It defaults to `"static"`, so every page is still rendered at build time. The adapter adds a server that serves those files. Build to confirm: #### bun ```bash bun run build ``` #### pnpm ```bash pnpm run build ``` #### yarn ```bash yarn build ``` #### npm ```bash npm run build ``` ```text no-copy [build] output: "static" [build] mode: "server" [build] adapter: @astrojs/node [build] Building server entrypoints... prerendering static routes ├─ /about/index.html (+7ms) ├─ /pricing/index.html (+3ms) ├─ /index.html (+4ms) ✓ Completed in 50ms. [build] Server built in 815ms [build] Complete! ``` The pages land in `dist/client/` and the server lands in `dist/server/entry.mjs`. Compute runs that server. ## 4. Declare the app with Prisma Composer [#4-declare-the-app-with-prisma-composer] [Prisma Composer](https://www.prisma.io/docs/composer) describes what to deploy. Install it, plus the Prisma CLI as a dev dependency: #### bun ```bash bun add @prisma/composer @prisma/composer-prisma-cloud bun add --dev prisma ``` #### pnpm ```bash pnpm add @prisma/composer @prisma/composer-prisma-cloud pnpm add -D prisma ``` #### yarn ```bash yarn add @prisma/composer @prisma/composer-prisma-cloud yarn add --dev prisma ``` #### npm ```bash npm install @prisma/composer @prisma/composer-prisma-cloud npm install -D prisma ``` Declare the service and point it at the Astro server entry. `dir` is the build output directory, and `entry` is the server file inside it: ```ts title="service.ts" import node from "@prisma/composer/node"; import { compute } from "@prisma/composer-prisma-cloud"; export default compute({ name: "web", deps: {}, build: node({ module: import.meta.url, dir: "./dist", entry: "server/entry.mjs", dependencies: "external", }), }); ``` Keep `dependencies: "external"`. The Astro build leaves some packages as imports instead of bundling them into `dist/server/`, and this option ships those packages from `node_modules` with the deploy. Without it, the deploy succeeds and every request returns a 502. The root module is the app. Its name becomes the project name on Compute: ```ts title="module.ts" import { module } from "@prisma/composer"; import web from "./service.ts"; export default module("marketing-site", ({ provision }) => { provision(web); }); ``` The deploy config tells the CLI where to deploy. The `region` applies when the first deploy creates the project: ```ts title="prisma.config.ts" import { defineConfig as composer } from "@prisma/composer/config"; import { nodeBuild } from "@prisma/composer/node/control"; import { prismaCloud, prismaState } from "@prisma/composer-prisma-cloud/control"; import { definePrismaConfig } from "prisma/config"; export default definePrismaConfig({ composer: composer({ entry: "./module.ts", extensions: [prismaCloud({ region: "us-east-1" }), nodeBuild()], state: prismaState(), }), }); ``` Composer writes local state to `.alchemy/` and `.prisma-composer/`. Add both to `.gitignore`: ```bash title=".gitignore" /.alchemy /.prisma-composer ``` ## 5. Run it locally [#5-run-it-locally] Run the built site the way Compute will. No account is needed: #### bun ```bash bun run build bunx prisma dev ``` #### pnpm ```bash pnpm run build pnpm prisma dev ``` #### yarn ```bash yarn build yarn prisma dev ``` #### npm ```bash npm run build npx prisma dev ``` ```text no-copy dev: ready marketing-site.web: http://localhost:3000 ``` `dev` keeps running. From a second terminal in the same directory, check each route. `prisma dev url marketing-site.web` prints the URL of the `web` service, whichever port it got: ```bash curl -s -o /dev/null -w "%{http_code}\n" "$(npx prisma dev url marketing-site.web)/pricing" ``` ```text no-copy 200 ``` Composer hands the server its port, so you do not set `PORT` or `HOST` yourself. Stop `dev` with `Ctrl+C`. ## 6. Deploy to Prisma Compute [#6-deploy-to-prisma-compute] Sign in once. It opens your browser: #### bun ```bash bunx prisma auth login ``` #### pnpm ```bash pnpm prisma auth login ``` #### yarn ```bash yarn prisma auth login ``` #### npm ```bash npx prisma auth login ``` Then build and deploy: #### bun ```bash bun run build bunx prisma deploy ``` #### pnpm ```bash pnpm run build pnpm prisma deploy ``` #### yarn ```bash yarn build yarn prisma deploy ``` #### npm ```bash npm run build npx prisma deploy ``` ```text no-copy Plan: 4 to create, 1 tasks ... marketing-site └─ web compute-service cps_abc123 https://abc123.ewr.prisma.build ... Done: 5 succeeded (16.8s) ``` The deploy creates a project named `marketing-site` in your workspace and prints the live URL. If a project with that name already exists and its deploy state cannot be verified, the deploy stops with `HostedStateBootstrapError`; rename the module in `module.ts` or pass `--name `. Verify the live site: ```bash curl -s https://abc123.ewr.prisma.build/ | grep -o '

.*

' ``` ```text no-copy

Ship faster with Acme

``` ## 7. Ship a change [#7-ship-a-change] Edit a page, then build and deploy again: ```astro title="src/pages/index.astro"

Ship faster with Acme

// [!code --]

Ship faster with Acme, now on Prisma Compute

// [!code ++] ``` #### bun ```bash bun run build bunx prisma deploy ``` #### pnpm ```bash pnpm run build pnpm prisma deploy ``` #### yarn ```bash yarn build yarn prisma deploy ``` #### npm ```bash npm run build npx prisma deploy ``` ```text no-copy Plan: 2 to update, 1 to replace, 1 tasks ... marketing-site └─ web compute-service cps_abc123 https://abc123.ewr.prisma.build ``` The deploy reuses the project and keeps the URL. Fetch it again and you get the new heading. To deploy on every push instead of from your terminal, see [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push). ## Common gotchas [#common-gotchas] **`ASSEMBLE.BUILD_FAILED`: no built entry at `dist/server/entry.mjs`.** Either the Node adapter is missing, so the build only wrote HTML files, or you ran `dev` or `deploy` before `npm run build`. Add the adapter (step 3), build, and run the command again. Composer never runs your build for you, so always build before `deploy`; otherwise it ships whatever is already in `dist/`. **The deploy succeeds, then every route returns a 502.** The server crashed on start because a package it imports was not shipped. Run `npx prisma service logs marketing-site.web --project marketing-site` and look for `Cannot find module` or `Cannot find package`. Add `dependencies: "external"` to `node({...})` in `service.ts` (step 4), build, and deploy again. `prisma dev` does not catch this, because the local server still reads packages from your project's `node_modules`. **Setting `output: "server"`.** You don't need it for a marketing site. It renders every page per request instead of serving prebuilt HTML. Leave `output` at its static default, and opt a single page into request-time rendering with `export const prerender = false` when you need one. ## Use with your agent [#use-with-your-agent] To delegate this guide to your coding agent, copy the prompt below and hand it over: ```text Build a static Astro marketing site and deploy it to Prisma Compute. Follow https://www.prisma.io/docs/guides/compute/astro-marketing-site.md. 1. Scaffold: `npm create astro@latest -- marketing-site --template minimal --install --no-git --yes`, then work in `marketing-site`. 2. Build the pages I describe (default: a shared layout in `src/layouts/Base.astro` plus home, pricing, and about pages). Keep every page static; do not set `output: "server"`. 3. Run `npx astro add node --yes` so `astro.config.mjs` uses `node({ mode: "standalone" })`. Run `npm run build` and confirm `dist/server/entry.mjs` exists. 4. Install `@prisma/composer` and `@prisma/composer-prisma-cloud`, and `prisma` as a dev dependency. Add `service.ts`, `module.ts`, and `prisma.config.ts` exactly as the guide shows, including `dependencies: "external"` in `service.ts`, and add `/.alchemy` and `/.prisma-composer` to `.gitignore`. 5. Run `npx prisma dev --detach`, curl each page under `$(npx prisma dev url marketing-site.web)` and confirm a 200, then run `npx prisma dev stop`. 6. Deploy: check `npx prisma auth whoami`; if I am not signed in, stop and ask me to run `npx prisma auth login`. Then run `npm run build` followed by `npx prisma deploy`, and curl the printed URL to confirm the home page renders. ``` Install the [Prisma Compute agent skill](https://www.prisma.io/docs/ai/tools/skills) so your agent knows the deploy workflow: #### 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 ``` Prompts that map to this guide: * "Add a blog to my Astro marketing site and redeploy it to Prisma Compute." * "Put my Prisma Compute site on a custom domain." * "Set up deploy on push for this site." ## Next steps [#next-steps] * [Add a custom domain](https://www.prisma.io/docs/compute/domains) to the deployed site. * [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push) so every Git push deploys, with a preview for every branch other than the default one. * [Use Prisma ORM with Astro](https://www.prisma.io/docs/guides/frameworks/astro) when the site needs data, like a waitlist form backed by Prisma Postgres. ## Related pages - [`Deploy an existing app on Prisma Compute`](https://www.prisma.io/docs/guides/compute/deploy-existing-app): Use when a Node.js server already on Prisma 8 with PostgreSQL should deploy on Prisma Compute from GitHub, with a Prisma Postgres database for each branch # Deploy an existing app on Prisma Compute (/docs/guides/compute/deploy-existing-app) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Use when a Node.js server already on Prisma 8 with PostgreSQL should deploy on Prisma Compute from GitHub, with a Prisma Postgres database for each branch Location: Guides > Build on Compute > Deploy an existing app on Prisma Compute > [!NOTE] > Not for an app on Prisma ORM 6 or 7, or for a new app > > Prisma Compute runs only Prisma 8. To upgrade an app on Prisma ORM 6 or 7 first, start at [Upgrade to Prisma 8](https://www.prisma.io/docs/guides/upgrade-prisma-orm). To start a new app on Compute, follow [Getting started](https://www.prisma.io/docs/compute/getting-started). This guide takes an Express, Fastify, Hono or other Node.js server that already runs Prisma 8 on PostgreSQL and deploys it on [Prisma Compute](https://www.prisma.io/docs/compute) from its GitHub repository. At the end, every push deploys the app: the default branch to production, and every other branch to a preview with its own Prisma Postgres database. The examples continue the feedback board from [Prisma ORM 6 or 7 to 8 (PostgreSQL)](https://www.prisma.io/docs/guides/upgrade-prisma-orm/postgresql): Express 4, EJS views, compiled with `tsc` to `dist/` and started with `node dist/server.js`. If you use a coding agent, the `prisma-compute` skill follows this guide: #### 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 ``` ## Prerequisites [#prerequisites] * **Node.js 24.11 or newer.** `prisma dev`, which runs the app locally the way Compute runs it, refuses older versions. * **A Prisma 8 app on PostgreSQL** at `prisma@8.0.0-rc.27` and `@prisma/orm-postgres@8.0.0-rc.20`, with its client created by `postgres({ contract, url })`, the emitted contract in `src/prisma/`, and its migrations in `migrations/app/`. These are the versions the Console's setup works with today; newer ones do not yet deploy. * **The app in a GitHub repository**, with a committed lockfile, and a [Prisma Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=guides) workspace you can connect it to. ## How the app changes on Compute [#how-the-app-changes-on-compute] On Prisma Compute, the app does not read `DATABASE_URL`. The deploy creates a Prisma Postgres database for each branch, applies `migrations/app/` to it, and hands the app a client connected to it. `DATABASE_URL` is a reserved variable that holds the placeholder `-`, so an app that keeps reading it deploys and then fails every query with `P1001` and `host: "base"`. Two more changes follow from that. Compute ships only what your build writes to `dist/`, so the files the server reads at runtime have to be in it. And because the client comes from [Prisma Composer](https://www.prisma.io/docs/composer), the part of Compute that runs your app, `npm start` stops working: locally, the app runs under `prisma dev` instead. ## 1. Connect the repository in the Console [#1-connect-the-repository-in-the-console] Push your work, then in the [Console](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=guides) create a project and connect the repository to it. [GitHub](https://www.prisma.io/docs/compute/github) describes the connection. The project's region is set when it is created and cannot change later, so pick the one nearest your users. To set up deploys without the Console, skip to [Without the Console](#without-the-console). The Console opens a pull request, **Set up Prisma Cloud deploys**, on a branch named `prisma-cloud/setup`. It adds: * `.github/workflows/prisma-deploy.yml`, which deploys every push: the default branch to production, and every other branch to its own preview. * `module.mjs`, which declares the app and its Prisma Postgres database for Composer. * `service.mjs`, which declares your server as a service with `deps: { db: postgres(dataContract(contractJson)) }`, the database it needs. * A `composer` section in `prisma.config.ts`, and the Composer packages in `package.json`. The setup keeps the `prisma` and `@prisma/orm-postgres` versions your `package.json` declares. Because the workflow runs on every push, the setup branch deploys as a preview. Make the changes below on that branch, and merge the pull request only after its preview works, because merging deploys production. ## 2. Move the service declaration into your build [#2-move-the-service-declaration-into-your-build] A Compute service runs the files your build produces, here `dist/`, and nothing outside them. Your server code imports the service declaration to get its database, so the declaration has to be part of the build. Check out the setup branch, then move `service.mjs` into `src/` as a TypeScript ES module: ```bash git switch prisma-cloud/setup git rm service.mjs ``` ```typescript title="src/service.mts" import node from "@prisma/composer/node"; import { compute } from "@prisma/composer-prisma-cloud"; import { postgres, dataContract } from "@prisma/composer-prisma-cloud/orm"; import type { Contract } from "./prisma/contract.js"; import contractJson from "./prisma/contract.json" with { type: "json" }; export const data = dataContract(contractJson); export default compute({ name: "feedback-board", deps: { db: postgres(data) }, build: node({ module: import.meta.url, dir: ".", entry: "server.js", dependencies: "external" }), }); ``` Keep the `name` the setup wrote. `tsc` compiles this file to `dist/service.mjs`, so `dir: "."` is `dist/` and `entry` is the file in it that starts your server, the one `npm start` runs. Check it, because the setup guesses the entry from your repository and can get it wrong. `dependencies: "external"` ships the packages in `node_modules` that the entry imports, since `tsc` does not bundle them. `dataContract(...)` gives the client the types from `contract.d.ts`. In `module.mjs`, import the compiled service instead of the deleted file: ```javascript title="module.mjs" import feedbackBoardService from "./service.mjs"; // [!code --] import feedbackBoardService from "./dist/service.mjs"; // [!code ++] ``` The deploy workflow runs `npm run build` before it reads `module.mjs`, so `dist/service.mjs` exists by then. ## 3. Take the client from the service [#3-take-the-client-from-the-service] Change `src/db.ts` to use the client Composer connects to the branch's database: #### Prisma Compute ```typescript title="src/db.ts" import service from "./service.mjs"; export const db = service.load().db.client; ``` #### Before ```typescript title="src/db.ts" import "dotenv/config"; import postgres from "@prisma/orm-postgres/runtime"; import { contractFromJson } from "@prisma/orm-postgres/static"; import type { Contract } from "./prisma/contract.d"; import contractJson from "./prisma/contract.json"; export const db = postgres({ contract: contractFromJson(contractJson), url: process.env["DATABASE_URL"]!, }); ``` `db.client` has the same type as the client you had, so the rest of your code does not change. `service.load().db` also has `url`, the raw connection string, for a library that needs one. `src/db.ts` stays CommonJS and loads the ES module through `require`, which Node.js 22.12 and newer support. Have the server listen on `service.port()` and `"0.0.0.0"` instead of `process.env.PORT`. Outside a Composer run, `service.load()` throws `missing required config param "url"`, so `npm start`, a `tsx` dev script and a `Procfile` stop working. Run the app locally under `prisma dev`, which starts a local Prisma Postgres, applies `migrations/app/` to it, and runs the service the way Compute does: #### bun ```bash bun run build bunx prisma dev module.mjs ``` #### pnpm ```bash pnpm run build pnpm prisma dev module.mjs ``` #### yarn ```bash yarn build yarn prisma dev module.mjs ``` #### npm ```bash npm run build npx prisma dev module.mjs ``` **Expected result:** `dev: ready` and the service's local URL, such as `feedbackboard: http://localhost:3000`. The local database starts empty. Make `npm run build && npx prisma dev module.mjs` your `dev` script. A seed script must not import `src/db.ts`: keep its own `postgres({ contract, url })` client, and run it against the local database with `DATABASE_URL="$(npx prisma dev url database)" npx tsx prisma/seed.ts`. ## 4. Ship files the server reads at runtime [#4-ship-files-the-server-reads-at-runtime] Only `dist/` reaches Compute, so if your server reads other files at runtime, such as EJS views in `views/` or static files in `public/`, copy them into `dist/` in the build, and read them from next to the compiled code: ```json title="package.json (excerpt)" { "scripts": { "build": "tsc", // [!code --] "build": "tsc && cp -R views public dist/" // [!code ++] } } ``` ```typescript title="src/server.ts (excerpt)" app.set("views", path.join(__dirname, "..", "views")); // [!code --] app.set("views", path.join(__dirname, "views")); // [!code ++] app.use(express.static(path.join(__dirname, "..", "public"))); // [!code --] app.use(express.static(path.join(__dirname, "public"))); // [!code ++] ``` Without this, the app starts and every page it renders fails with `Failed to lookup view`. ## 5. Set your other environment variables [#5-set-your-other-environment-variables] Compute sets the database and the port. Pass every other variable your app reads to the service as a [service input](https://www.prisma.io/docs/composer/service-input), which reads the same value on Compute and under `prisma dev`. Declare the input in the service: ```typescript title="src/service.mts (excerpt)" import { type } from "arktype"; import { secretString } from "@prisma/composer/arktype"; export default compute({ name: "feedback-board", deps: { db: postgres(data) }, input: type({ sessionSecret: secretString() }), // [!code ++] build: node({ module: import.meta.url, dir: ".", entry: "server.js", dependencies: "external" }), }); ``` Add `arktype` as a direct dependency, at the version `@prisma/composer` already uses, which `npm ls arktype` prints. Then fill the input from a project environment variable where `module.mjs` provisions the service, and read it in the server: ```javascript title="module.mjs (excerpt)" import { envSecret } from "@prisma/composer-prisma-cloud"; provision(feedbackBoardService, { deps: { db: database }, input: { sessionSecret: envSecret("SESSION_SECRET") }, // [!code ++] }); ``` ```typescript title="src/server.ts (excerpt)" const SESSION_SECRET = process.env.SESSION_SECRET!; // [!code --] const SESSION_SECRET = service.input().sessionSecret.expose(); // [!code ++] ``` Set each value for production and for previews. `read -rs` asks for the value without showing it, and given only the variable's name, `project env add` reads the value from your environment, so the secret stays off the command line and out of your shell history: ```bash read -rs SESSION_SECRET && export SESSION_SECRET # type the production value, then press Enter npx prisma project env add SESSION_SECRET --role production read -rs SESSION_SECRET && export SESSION_SECRET # type the preview value, then press Enter npx prisma project env add SESSION_SECRET --role preview unset SESSION_SECRET ``` Run these from a directory linked to the project, or add `--project `. Set them before you push, and redeploy after you change one. [Environment variables](https://www.prisma.io/docs/compute/environment-variables) covers scopes and branch overrides. ## 6. Push and check the preview [#6-push-and-check-the-preview] ```bash git add -A git commit -m "Deploy on Prisma Compute" git push ``` The push runs the deploy workflow for the setup branch. Find the preview's URL: #### bun ```bash bunx prisma service list --branch prisma-cloud/setup ``` #### pnpm ```bash pnpm prisma service list --branch prisma-cloud/setup ``` #### yarn ```bash yarn prisma service list --branch prisma-cloud/setup ``` #### npm ```bash npx prisma service list --branch prisma-cloud/setup ``` **Expected result:** the request you use as a health check succeeds against that URL, for example `curl https:///healthz` returns `{"ok":true}`, and pages that read and write the database work. The preview database starts empty, with your schema from `migrations/app/` and no data. When the preview works, merge the pull request. The merge deploys production the same way, with its own database. ## Without the Console [#without-the-console] To set up deploys yourself, write the files the setup pull request adds, make the changes from steps 2 to 5, deploy once from your machine, and then connect the repository. Start with the Composer packages, at the version that matches `@prisma/orm-postgres@8.0.0-rc.20`, because the latest Composer release does not work with it: #### bun ```bash bun add --exact @prisma/composer@0.34.0 @prisma/composer-prisma-cloud@0.34.0 ``` #### pnpm ```bash pnpm add --save-exact @prisma/composer@0.34.0 @prisma/composer-prisma-cloud@0.34.0 ``` #### yarn ```bash yarn add --exact @prisma/composer@0.34.0 @prisma/composer-prisma-cloud@0.34.0 ``` #### npm ```bash npm install --save-exact @prisma/composer@0.34.0 @prisma/composer-prisma-cloud@0.34.0 ``` Add a `composer` section to `prisma.config.ts`, with the region for the project the first deploy creates. Keep the `orm` section you have; the one below is from the upgrade guide: ```typescript title="prisma.config.ts" import "dotenv/config"; import { definePrismaConfig } from "prisma/config"; import { defineConfig, prisma7Schema } from "@prisma/orm-postgres/config"; import { defineConfig as composer } from "@prisma/composer/config"; // [!code ++] import { nodeBuild } from "@prisma/composer/node/control"; // [!code ++] import { prismaCloud, prismaState } from "@prisma/composer-prisma-cloud/control"; // [!code ++] export default definePrismaConfig({ orm: defineConfig({ contract: prisma7Schema("prisma/schema.prisma"), output: "src/prisma", db: { connection: process.env["DATABASE_URL"], }, }), composer: composer({ // [!code ++] extensions: [prismaCloud({ region: "eu-central-1" }), nodeBuild()], // [!code ++] state: prismaState(), // [!code ++] }), // [!code ++] }); ``` The region cannot change after the first deploy creates the project. [Limitations](https://www.prisma.io/docs/compute/limitations#runtime) lists the ones you can choose. Declare the app and its database in `module.mjs`, from the same contract the service in step 2 exports: ```javascript title="module.mjs" import { module } from "@prisma/composer"; import { postgres } from "@prisma/composer-prisma-cloud/orm"; import feedbackBoardService, { data } from "./dist/service.mjs"; export default module("feedback-board", ({ provision }) => { const database = provision(postgres({ name: "database", contract: data, config: "prisma.config.ts" })); provision(feedbackBoardService, { deps: { db: database } }); }); ``` Composer writes local state to `.prisma/`, `.prisma-composer/` and `.alchemy/`, so add those folders to `.gitignore`. Then make the changes from steps 2 to 5, and deploy production once from your machine. The deploy creates the project, and the commands after it link this directory to the project and connect the repository: #### bun ```bash bun run build bunx prisma deploy --entry module.mjs bunx prisma project link feedback-board bunx prisma git connect ``` #### pnpm ```bash pnpm run build pnpm prisma deploy --entry module.mjs pnpm prisma project link feedback-board pnpm prisma git connect ``` #### yarn ```bash yarn build yarn prisma deploy --entry module.mjs yarn prisma project link feedback-board yarn prisma git connect ``` #### npm ```bash npm run build npx prisma deploy --entry module.mjs npx prisma project link feedback-board npx prisma git connect ``` `git connect` opens the browser so you can install the Prisma GitHub app, and it does not add a deploy workflow. Add the workflow from [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push#4-add-the-deploy-workflow), with `module: module.mjs` in the action's inputs, because the action looks for `module.ts` by default: ```yaml title=".github/workflows/prisma-deploy.yml (excerpt)" - uses: prisma/cloud-deploy-action@v1 with: build-command: npm run build module: module.mjs ``` Push a branch other than the default one, and check its preview as in step 6. ## Next steps [#next-steps] * [Deploy on push](https://www.prisma.io/docs/compute/deploy-on-push): how previews, production and branch cleanup work once the workflow is in place. * [Databases in Prisma Composer](https://www.prisma.io/docs/composer/databases): the `postgres()` database, its client, and how the deploy migrates it. ## Related pages - [`Build a marketing site with Astro`](https://www.prisma.io/docs/guides/compute/astro-marketing-site): Build a static marketing site with Astro, serve it from a Node server, and deploy it to Prisma Compute with Prisma Composer. # Expand-and-contract migrations (/docs/guides/database/data-migration) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Replace a column without downtime using the expand and contract pattern, with the data backfill inside a Prisma ORM migration. Location: Guides > Database > Expand-and-contract migrations ## Introduction [#introduction] When you change a production schema, you want the data to stay consistent and the app to keep running. The expand and contract pattern gets you there in two reviewable steps: first add the new column and copy the data across (expand), then remove the old column once nothing reads it (contract). In this guide you replace a `published` boolean on a `Post` model with a `status` enum. In Prisma ORM the data move is not a separate script. A migration is a TypeScript file, and the backfill is one more operation in it, a `dataTransform` that runs in the same transaction as the schema change. Every command and output below was run against a local PostgreSQL database. > [!NOTE] > Using Prisma ORM 7? > > Prisma ORM 8 is a [release candidate](https://www.prisma.io/docs/orm/release-status). Prisma ORM 7 remains fully supported; the Prisma ORM 7 version of this guide is at [/guides/v7/database/data-migration](https://www.prisma.io/docs/guides/v7/database/data-migration). ## Prerequisites [#prerequisites] * [Node.js](https://nodejs.org) 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer (24 recommended) * A PostgreSQL connection string for a development database, and one for the database you deploy to * Git, for the branch-per-migration workflow ## Use with your agent [#use-with-your-agent] To delegate this guide to your coding agent, copy the prompt below and hand it over: ```text Perform an expand-and-contract migration with Prisma ORM, following https://www.prisma.io/docs/guides/database/data-migration.md. 1. In a project with a `Post` model that has a `published Boolean @default(false)` field, make sure Prisma ORM is set up (`npx prisma@latest orm init --yes --target postgres --authoring psl` if it is not), `DATABASE_URL` is in `.env`, and the current contract is applied as a migration (`npx prisma contract emit`, `npx prisma migration plan --name init`, `npx prisma db migrate --advance-ref db`). Run `npx prisma@latest init` so the Prisma agent skills are installed, and use them. 2. Expand: add `enum Status { @@type("pg/text@1") Draft = "Draft" InProgress = "InProgress" InReview = "InReview" Published = "Published" }` and `status Status @default(Draft)` to `Post`. Keep `published`. Run `contract emit` and `migration plan --name add_status`. 3. Open the planned `migration.ts` and append a `this.dataTransform(endContract, 'backfill-post-status', { check, run })` operation built with the typed SQL builder against the migration's own end contract: `check` selects `id` from `Post` where `published = true AND status != 'Published'` with `limit(1)`, `run` updates those rows to `status = 'Published'`. Recompile with `node /migration.ts`, confirm `ops.json` contains a `data` operation, then apply with `npx prisma db migrate --advance-ref db`. Verify with a query that every row with `published = true` now has `status = 'Published'`. 4. Update application code to read and write `status` instead of `published`. 5. Contract: remove `published` from the contract, run `contract emit`, `migration plan --name drop_published --delete Post.published`, review the destructive warning, and apply with `npx prisma db migrate --advance-ref db`. 6. For the production database, run `npx prisma db migrate --db "$PRODUCTION_DATABASE_URL"`, adding `--show` first if you want to preview the route. Do not use `db update` against production. ``` ## 1. Set up the project [#1-set-up-the-project] If you already have a Prisma ORM project whose contract is applied through migrations, skip to [step 2](#2-expand-the-contract). This step builds the starting point: a `Post` model with a `published` boolean, an `init` migration, and three rows of data. Create a project and add Prisma ORM to it: ```bash mkdir expand-contract && cd expand-contract ``` #### bun ```bash bun init bunx prisma@latest orm init --yes --target postgres --authoring psl ``` #### pnpm ```bash pnpm init pnpm dlx prisma@latest orm init --yes --target postgres --authoring psl ``` #### yarn ```bash yarn init yarn dlx prisma@latest orm init --yes --target postgres --authoring psl ``` #### npm ```bash npm init npx prisma@latest orm init --yes --target postgres --authoring psl ``` `orm init` writes `prisma.config.ts`, `src/prisma/contract.prisma`, `src/prisma/db.ts`, and `.env.example`, installs `@prisma/orm-postgres` and the `prisma` CLI, and emits the contract once. There is nothing to generate afterwards: the runtime reads the emitted `contract.json` directly, so there is no `prisma generate` step and no client package to install. `npm init -y` sets `"type": "commonjs"`, and `orm init` warns that the generated `db.ts` needs ES modules. Change it to `"type": "module"` in `package.json`. Put your development connection string in `.env`. Both `prisma.config.ts` and `db.ts` load it: ```bash title=".env" DATABASE_URL="postgres://user:password@localhost:5432/expand_contract" ``` Replace the generated contract with the starting model: ```prisma title="src/prisma/contract.prisma" // use prisma-8 model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) } ``` Emit the contract, plan the first migration, and apply it. `--advance-ref db` records where your development database is, so the next `migration plan` knows what to diff against: #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name init bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name init pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name init yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name init npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (2 operation(s)) across 1 contract space(s) App space ├─ Create schema "public" ├─ Create table "Post" └─ marker e8804d8e27d8737475c7be0c538afd9665907df8b82c605bd5cd50926dd73fde ✔ Advanced ref "db" → e8804d8e27d8737475c7be0c538afd9665907df8b82c605bd5cd50926dd73fde ``` Seed a few posts so the migration has data to move. Node.js runs TypeScript directly: ```typescript title="src/seed.ts" import { db } from "./prisma/db.ts"; await db.orm.public.Post.create({ title: "Hello World", content: "First post", published: true }); await db.orm.public.Post.create({ title: "Draft ideas", content: null, published: false }); await db.orm.public.Post.create({ title: "Release notes", content: "v1.0", published: true }); const posts = await db.orm.public.Post.select("id", "title", "published").all(); console.log(posts); await db.close(); ``` ```bash node src/seed.ts ``` ```text no-copy [ { id: 1, title: 'Hello World', published: true }, { id: 2, title: 'Draft ideas', published: false }, { id: 3, title: 'Release notes', published: true } ] ``` ## 2. Expand the contract [#2-expand-the-contract] Create a branch for the expand step: ```bash git checkout -b expand-post-status ``` Add the `Status` enum and a `status` field. Leave `published` in place; the app keeps working against it until the contract step. Prisma ORM stores an enum as `text` with a `CHECK` constraint, and the `@@type` line says so: ```prisma title="src/prisma/contract.prisma" // use prisma-8 model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) status Status @default(Draft) // [!code ++] } enum Status { // [!code ++] @@type("pg/text@1") // [!code ++] Draft = "Draft" // [!code ++] InProgress = "InProgress" // [!code ++] InReview = "InReview" // [!code ++] Published = "Published" // [!code ++] } // [!code ++] ``` Emit the contract and plan the migration. Planning is offline; it diffs the emitted contract against the `db` ref and writes a migration directory: #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_status ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_status ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_status ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_status ``` ```text no-copy ✔ Planned 2 operation(s) migrations/app/20260910T1552_add_status ├─ Add column "status" to "Post" └─ Add check constraint "Post_status_check_eaa35e2a" on "Post" from: e8804d8e27d8737475c7be0c538afd9665907df8b82c605bd5cd50926dd73fde to: 0e9486dcd7f4216d673cbe0ec503edb638520dec9b0a8a22f48bb88edd1442c4 app space: migrations/app/20260910T1552_add_status ℹ DDL preview ALTER TABLE "public"."Post" ADD COLUMN "status" text DEFAULT 'Draft' NOT NULL; ALTER TABLE "public"."Post" ADD CONSTRAINT "Post_status_check_eaa35e2a" CHECK ("status" IN ('Draft', 'InProgress', 'InReview', 'Published')); ``` Your directory name carries your own timestamp. The planner did not ask for a backfill because the column has a default, so every existing row would become `Draft`. That is wrong for posts that are already published. The next step fixes it. ## 3. Add the data migration [#3-add-the-data-migration] Open `migrations/app/_add_status/migration.ts`. It is the file the planner wrote, and you edit it like any other TypeScript. Add the imports that wire up a typed SQL builder against this migration's own end contract, then append a `dataTransform` operation after the two schema operations: ```typescript title="migrations/app/20260910T1552_add_status/migration.ts" #!/usr/bin/env -S node import type { Contract as End } from '../../snapshots/0e9486dcd7f4216d673cbe0ec503edb638520dec9b0a8a22f48bb88edd1442c4/contract'; import endContractJson from '../../snapshots/0e9486dcd7f4216d673cbe0ec503edb638520dec9b0a8a22f48bb88edd1442c4/contract.json' with { type: 'json' }; import type { Contract as Start } from '../../snapshots/e8804d8e27d8737475c7be0c538afd9665907df8b82c605bd5cd50926dd73fde/contract'; import startContract from '../../snapshots/e8804d8e27d8737475c7be0c538afd9665907df8b82c605bd5cd50926dd73fde/contract.json' with { type: 'json' }; import { Migration, MigrationCLI, col, lit } from '@prisma/orm-postgres/migration'; import postgresAdapter from '@prisma/orm-postgres/adapter/runtime'; // [!code ++] import { sql } from '@prisma/orm-postgres/builder/runtime'; // [!code ++] import { createExecutionContext, createSqlExecutionStack } from '@prisma/orm-postgres/family-runtime'; // [!code ++] import postgresTarget, { PostgresContractSerializer } from '@prisma/orm-postgres/target/runtime'; // [!code ++] const endContract = new PostgresContractSerializer().deserializeContract(endContractJson) as End; // [!code ++] const db = sql({ // [!code ++] context: createExecutionContext({ // [!code ++] contract: endContract, // [!code ++] stack: createSqlExecutionStack({ target: postgresTarget, adapter: postgresAdapter }), // [!code ++] }), // [!code ++] rawCodecInferer: postgresAdapter.rawCodecInferer, // [!code ++] }); // [!code ++] export default class M extends Migration { override readonly startContractJson = startContract; override readonly endContractJson = endContractJson; override get operations() { return [ this.addColumn({ schema: 'public', table: 'Post', column: col('status', 'text', { notNull: true, default: lit('Draft'), codecRef: { codecId: 'pg/text@1' }, }), }), this.addCheckConstraint({ schema: 'public', table: 'Post', constraint: 'Post_status_check_eaa35e2a', expression: "\"status\" IN ('Draft', 'InProgress', 'InReview', 'Published')", }), this.dataTransform(endContract, 'backfill-post-status', { // [!code ++] check: () => // [!code ++] db.public.Post // [!code ++] .select('id') // [!code ++] .where((f, fns) => fns.and(fns.eq(f.published, true), fns.ne(f.status, 'Published'))) // [!code ++] .limit(1), // [!code ++] run: () => // [!code ++] db.public.Post // [!code ++] .update({ status: 'Published' }) // [!code ++] .where((f, fns) => fns.and(fns.eq(f.published, true), fns.ne(f.status, 'Published'))), // [!code ++] }), // [!code ++] ]; } } MigrationCLI.run(import.meta.url, M); ``` The snapshot paths in your file carry your own contract hashes; keep the ones the planner wrote. The planner writes the JSON import as `endContract`. Rename that import to `endContractJson`, as the version above does, and bind `endContract` to the deserialized contract, because the builder and `dataTransform` both need the deserialized form. Three things to notice: * `check` is a query that returns a row while work remains. Prisma compiles it twice: as an `EXISTS` precheck that decides whether the step runs, and as a `NOT EXISTS` postcheck that proves the step finished. * `run` is the update. Both closures are typed against the migration's own contract snapshot, which is why `f.status` type-checks even though the column does not exist in the database yet. * There is no `published: false` branch. Those rows take the column default, `Draft`, when `ADD COLUMN` runs. Recompile the migration. Running the file regenerates `ops.json`, the file `db migrate` actually executes, and re-signs `migration.json`: ```bash node migrations/app/20260910T1552_add_status/migration.ts ``` ```text no-copy Wrote ops.json + migration.json to /Users/you/expand-contract/migrations/app/20260910T1552_add_status ``` Review what the backfill compiled to. `migration show` lists the operation, and `ops.json` holds the exact SQL: #### bun ```bash bunx prisma migration show 20260910T1552_add_status ``` #### pnpm ```bash pnpm prisma migration show 20260910T1552_add_status ``` #### yarn ```bash yarn prisma migration show 20260910T1552_add_status ``` #### npm ```bash npx prisma migration show 20260910T1552_add_status ``` ```text no-copy ✔ 20260910T1552_add_status 3 operation(s) ├─ Add column "status" to "Post" ├─ Add check constraint "Post_status_check_eaa35e2a" on "Post" └─ Data transform: backfill-post-status ``` ```json title="migrations/app/20260910T1552_add_status/ops.json (the data operation)" no-copy { "id": "data_migration.backfill-post-status", "operationClass": "data", "precheck": [{ "sql": "SELECT EXISTS (SELECT \"id\" AS \"id\" FROM \"public\".\"Post\" WHERE (\"published\" = $1 AND \"status\" != $2) LIMIT 1) AS ok", "params": [true, "Published"] }], "execute": [{ "sql": "UPDATE \"public\".\"Post\" SET \"status\" = $1 WHERE (\"published\" = $2 AND \"status\" != $3)", "params": ["Published", true, "Published"] }], "postcheck": [{ "sql": "SELECT NOT EXISTS (SELECT \"id\" AS \"id\" FROM \"public\".\"Post\" WHERE (\"published\" = $1 AND \"status\" != $2) LIMIT 1) AS ok", "params": [true, "Published"] }] } ``` Commit `migration.ts`, `ops.json`, and `migration.json` together. Recompiling stores a hash of `ops.json` and `migration.json` inside `migration.json`. If either file changes after that, `db migrate` refuses to run the migration, and `npx prisma migration check` reports the same problem before you commit. ## 4. Apply the expand migration [#4-apply-the-expand-migration] Apply it to your development database. On PostgreSQL the whole run is one transaction, so the column, the constraint, and the backfill land together or not at all: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (3 operation(s)) across 1 contract space(s) App space ├─ Add column "status" to "Post" ├─ Add check constraint "Post_status_check_eaa35e2a" on "Post" ├─ Data transform: backfill-post-status └─ marker 0e9486dcd7f4216d673cbe0ec503edb638520dec9b0a8a22f48bb88edd1442c4 ✔ Advanced ref "db" → 0e9486dcd7f4216d673cbe0ec503edb638520dec9b0a8a22f48bb88edd1442c4 ``` Check the rows. The published posts moved to `Published`, and the draft kept the default: ```typescript title="src/posts.ts" import { db } from "./prisma/db.ts"; const posts = await db.orm.public.Post .select("id", "title", "published", "status") .orderBy((p) => p.id.asc()) .all(); console.log(posts); await db.close(); ``` ```bash node src/posts.ts ``` ```text no-copy [ { id: 1, title: 'Hello World', published: true, status: 'Published' }, { id: 2, title: 'Draft ideas', published: false, status: 'Draft' }, { id: 3, title: 'Release notes', published: true, status: 'Published' } ] ``` Both columns exist now, so this is the moment to move application code from `published` to `status`. The new field is typed as `'Draft' | 'InProgress' | 'InReview' | 'Published'` in the emitted contract: ```typescript const published = await db.orm.public.Post .select("id", "title", "status") .where((p) => p.status.eq("Published")) .orderBy((p) => p.id.asc()) .all(); ``` ```text no-copy [ { id: 1, title: 'Hello World', status: 'Published' }, { id: 3, title: 'Release notes', status: 'Published' } ] ``` Merge the branch and deploy it. Wait until nothing reads or writes `published` before you continue. ## 5. Contract the schema [#5-contract-the-schema] Create a branch for the cleanup: ```bash git checkout -b drop-published-column ``` Remove the old field: ```prisma title="src/prisma/contract.prisma" model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) // [!code --] status Status @default(Draft) } ``` Emit and plan. Dropping the column loses its data, so `migration plan` asks before it writes anything; `--delete Post.published` answers in advance: #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name drop_published --delete Post.published ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name drop_published --delete Post.published ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name drop_published --delete Post.published ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name drop_published --delete Post.published ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1554_drop_published └─ ⚠ Drop column "published" from "Post" ⚠ This migration contains destructive operations that may cause data loss. ℹ DDL preview ALTER TABLE "public"."Post" DROP COLUMN "published"; ``` Nothing to edit this time. Apply it: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (1 operation(s)) across 1 contract space(s) App space ├─ ⚠ Drop column "published" from "Post" └─ marker 79567c619bcb9790bf476efc358730a10317c94fc352e908e19424fc6441350a ``` The data survived the round trip. Drop `published` from the select in `src/posts.ts` and run it again: ```text no-copy [ { id: 1, title: 'Hello World', status: 'Published' }, { id: 2, title: 'Draft ideas', status: 'Draft' }, { id: 3, title: 'Release notes', status: 'Published' } ] ``` `migration log` reads the database's own ledger of what ran: #### bun ```bash bunx prisma migration log ``` #### pnpm ```bash pnpm prisma migration log ``` #### yarn ```bash yarn prisma migration log ``` #### npm ```bash npx prisma migration log ``` ```text no-copy Applied at Migration Change Ops 2026-09-10 17:51:19 +02:00 20260910T1551_init ∅ → e8804d8 2 ops 2026-09-10 17:53:46 +02:00 20260910T1552_add_status e8804d8 → 0e9486d 3 ops 2026-09-10 17:55:39 +02:00 20260910T1554_drop_published 0e9486d → 79567c6 1 ops ``` ## 6. Deploy to production [#6-deploy-to-production] Production runs the same migrations from the same files; only the connection string changes. `db migrate` reads the database's marker, finds the path through the [migration graph](https://www.prisma.io/docs/orm/migrations/the-migration-graph), and applies whatever is pending, backfill included. Your deploy pipeline needs one command: #### bun ```bash bunx prisma db migrate --db "$PRODUCTION_DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db migrate --db "$PRODUCTION_DATABASE_URL" ``` #### yarn ```bash yarn prisma db migrate --db "$PRODUCTION_DATABASE_URL" ``` #### npm ```bash npx prisma db migrate --db "$PRODUCTION_DATABASE_URL" ``` It refuses to run a migration whose `ops.json` or `migration.json` changed after it was compiled. If your pipeline deploys each environment to a ref, as [Applying a migration](https://www.prisma.io/docs/orm/migrations/applying-a-migration) shows, add `--to ` to that command. To see the route before it runs, add `--show`, which previews it without changing anything. Here is that preview against a production database that shipped the `init` migration and holds live rows, followed by the apply: ```text no-copy ℹ The following 2 migrations will run: 20260910T1552_add_status e8804d8 → 0e9486d 20260910T1554_drop_published 0e9486d → 79567c6 ``` ```text no-copy ✔ Applied 2 migration(s) (4 operation(s)) across 1 contract space(s) App space ├─ Add column "status" to "Post" ├─ Add check constraint "Post_status_check_eaa35e2a" on "Post" ├─ Data transform: backfill-post-status ├─ ⚠ Drop column "published" from "Post" └─ marker 79567c619bcb9790bf476efc358730a10317c94fc352e908e19424fc6441350a ``` In practice the two migrations reach production in separate deploys, one per branch, and the app moves from `published` to `status` between them. The commands are the same either way. Production never runs your TypeScript: the runner executes `ops.json`, which is plain data, so no application code runs with production credentials. ## Common gotchas [#common-gotchas] > [!WARNING] > Do not use `db update` for this change. It reconciles the database with the contract directly and does not carry data operations, so the backfill would not run. Use `migration plan` and `db migrate`, which is also what production needs: a reviewed, checked-in migration. > [!NOTE] > If `migration plan` stops with `MIGRATION.PLAN_ORIGIN_UNKNOWN`, the `db` ref is missing. That happens when you applied a migration with plain `db migrate`. Either re-run `npx prisma db migrate --advance-ref db`, or pass `--from ` to the plan. > [!NOTE] > If `db migrate` reports `MIGRATION.HASH_MISMATCH`, the migration's `ops.json` or `migration.json` changed after it was compiled, for example by a hand edit. Restore both files from Git, or move the edit into `migration.ts` and recompile with `node /migration.ts`, then apply again. Never edit `ops.json` by hand. > [!NOTE] > The `check` query must return rows, not a count. Prisma wraps it in `EXISTS` and `NOT EXISTS`; an aggregate always returns one row, so the step would never be skipped and the postcheck would always fail. ## Prompt your coding agent [#prompt-your-coding-agent] Run [`npx prisma@latest init`](https://www.prisma.io/docs/cli/init) once to install the [Prisma ORM skills](https://www.prisma.io/docs/ai/tools/skills#available-skills-for-prisma-8) for your coding agent and keep them matching your installed packages. Prompts that map to this guide: * "Using the prisma-8 skill, add a `dataTransform` to the latest migration that backfills `status` from `published`, recompile it, and show me the compiled SQL in ops.json." * "Plan a migration that drops the `published` column and explain the destructive warning." * "Preview what `db migrate` would run against staging and summarize the operations." ## Next steps [#next-steps] * [Editing a migration](https://www.prisma.io/docs/orm/migrations/editing-a-migration): placeholders, `rawSql`, and the recompile loop in depth. * [Applying a migration](https://www.prisma.io/docs/orm/migrations/applying-a-migration): targets, refs, and what happens when a run fails. * [Rollbacks and recovery](https://www.prisma.io/docs/orm/migrations/rollbacks-and-recovery): a rollback is one more planned migration, and a failed run is safe to retry. * [The migration graph](https://www.prisma.io/docs/orm/migrations/the-migration-graph): why two branches with migrations merge cleanly. ## Related pages - [`Multiple databases`](https://www.prisma.io/docs/guides/database/multiple-databases): Connect one Next.js app to two PostgreSQL databases with Prisma ORM: one contract, config, and client per database, selected with the --config flag. - [`Schema management in teams`](https://www.prisma.io/docs/guides/database/schema-changes): Plan, merge, and apply Prisma ORM migrations when several developers change the schema at the same time. # Multiple databases (/docs/guides/database/multiple-databases) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Connect one Next.js app to two PostgreSQL databases with Prisma ORM: one contract, config, and client per database, selected with the --config flag. Location: Guides > Database > Multiple databases ## Introduction [#introduction] This guide shows you how to use two databases from one [Next.js](https://nextjs.org/) app with Prisma ORM. You give each database its own data contract, its own `prisma.config.ts`, and its own Prisma ORM client, then render data from both on one page. The same layout works for any number of databases and is a good fit for multi-tenant apps or for keeping unrelated data in separate databases. Every command and code block below was run against two local PostgreSQL databases, `users` and `posts`. > [!NOTE] > Using Prisma ORM 7? > > Prisma ORM 8 is a [release candidate](https://www.prisma.io/docs/orm/release-status). Prisma ORM 7 remains fully supported; the Prisma ORM 7 version of this guide is at [/guides/v7/database/multiple-databases](https://www.prisma.io/docs/guides/v7/database/multiple-databases). ## Prerequisites [#prerequisites] * [Node.js](https://nodejs.org) 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer (24 recommended) * Two PostgreSQL connection strings, or nothing at all: `npx create-db@latest` can create a [Prisma Postgres](https://www.prisma.io/docs/postgres) database for you, run it twice for two * A [Vercel](https://vercel.com/) account if you want to deploy at the end ## Use with your agent [#use-with-your-agent] To delegate this guide to your coding agent, copy the prompt below and hand it over: ```text Create a Next.js app that reads from two PostgreSQL databases with Prisma ORM, following https://www.prisma.io/docs/guides/database/multiple-databases.md. 1. Scaffold with `npx create-next-app@latest my-multi-db-app --yes`, then in the project run `npx prisma@latest orm init --yes --target postgres --authoring psl --schema-path ./prisma/users/contract.prisma`. Run `npx prisma@latest init` so the Prisma agent skills are installed, and use them. 2. Rename `prisma.config.ts` to `prisma.users.config.ts`, point it at `USERS_DATABASE_URL` and `./prisma/users/migrations`, and reduce `prisma/users/contract.prisma` to a `User` model. Create the same three files for the posts database: `prisma.posts.config.ts` reading `POSTS_DATABASE_URL`, `prisma/posts/contract.prisma` with a `Post` model that stores `authorId Int` (no relation across databases), and `prisma/posts/db.ts`. Export `usersDb` and `postsDb` from the two `db.ts` files. 3. Put both connection strings in `.env` (use the ones I give you, or create two Prisma Postgres databases with `npx create-db@latest` and show me the claim URLs). Add package scripts that run `prisma contract emit`, `prisma db init`, and `prisma db verify` once per config with `--config`, then run them. 4. Write a seed script that inserts two users and two posts, run it with `node prisma/seed.ts`, and rewrite `app/page.tsx` as a server component that lists users from `usersDb` and posts from `postsDb`, joining authors in application code. 5. Start `npm run dev` in the background, verify http://localhost:3000 renders both lists, stop the server, and confirm `npm run build` passes. ``` ## 1. Set up a Next.js project [#1-set-up-a-nextjs-project] Create a new Next.js app and accept the defaults (TypeScript, Tailwind CSS, App Router, no `src` directory): #### bun ```bash bunx create-next-app@latest my-multi-db-app cd my-multi-db-app ``` #### pnpm ```bash pnpm dlx create-next-app@latest my-multi-db-app cd my-multi-db-app ``` #### yarn ```bash yarn dlx create-next-app@latest my-multi-db-app cd my-multi-db-app ``` #### npm ```bash npx create-next-app@latest my-multi-db-app cd my-multi-db-app ``` This guide starts from `create-next-app` and adds Prisma ORM with `orm init` instead of using the `next` template of `create-prisma`. That template wires a single database and declares it for Prisma Compute; here you want exactly the Prisma files, once per database, and nothing else. ## 2. Add Prisma ORM for the users database [#2-add-prisma-orm-for-the-users-database] Run `orm init` from the project root. The `--schema-path` flag puts the contract in a folder named after the database, and `orm init` places the client file next to it: #### bun ```bash bunx prisma@latest orm init --yes --target postgres --authoring psl --schema-path ./prisma/users/contract.prisma ``` #### pnpm ```bash pnpm dlx prisma@latest orm init --yes --target postgres --authoring psl --schema-path ./prisma/users/contract.prisma ``` #### yarn ```bash yarn dlx prisma@latest orm init --yes --target postgres --authoring psl --schema-path ./prisma/users/contract.prisma ``` #### npm ```bash npx prisma@latest orm init --yes --target postgres --authoring psl --schema-path ./prisma/users/contract.prisma ``` The command installs `@prisma/orm-postgres` and `dotenv`, adds `prisma` as a dev dependency, sets `"type": "module"` in `package.json`, updates `tsconfig.json`, and writes these files: ```text no-copy prisma/users/contract.prisma prisma/users/db.ts prisma.config.ts prisma-8.md .env.example ``` There is no `prisma generate` and no generated client package. The emitted `contract.json` and `contract.d.ts` next to the contract are what the runtime and the type checker read. ### 2.1. Give the config a database-specific name [#21-give-the-config-a-database-specific-name] Prisma ORM commands read `./prisma.config.ts` by default and take a different file with the global [`--config`](https://www.prisma.io/docs/cli/global-flags) flag. Rename the generated config so each database has one: ```bash mv prisma.config.ts prisma.users.config.ts ``` Point it at the users contract, a users-only migrations folder, and a `USERS_DATABASE_URL` variable: ```typescript title="prisma.users.config.ts" import 'dotenv/config'; import { definePrismaConfig } from '@prisma/cli-engine'; import { defineConfig as ormConfig } from '@prisma/orm-postgres/config'; export default definePrismaConfig({ orm: ormConfig({ contract: "./prisma/users/contract.prisma", migrations: { // [!code ++] dir: "./prisma/users/migrations", // [!code ++] }, // [!code ++] db: { connection: process.env.USERS_DATABASE_URL!, // [!code ++] }, }), }); ``` `migrations.dir` matters once you use checked-in migrations: without it both configs would write to the same `./migrations` folder. ### 2.2. Define the users contract [#22-define-the-users-contract] Replace the starter contract with a single `User` model: ```prisma title="prisma/users/contract.prisma" // use prisma-8 model User { id Int @id @default(autoincrement()) email String @unique name String? createdAt TimestamptzString @default(now()) } ``` ### 2.3. Name the client after the database [#23-name-the-client-after-the-database] Change `prisma/users/db.ts` to read `USERS_DATABASE_URL` and export a name you can tell apart from the second client: ```typescript title="prisma/users/db.ts" import 'dotenv/config'; import postgres from '@prisma/orm-postgres/runtime'; import { contractFromJson } from '@prisma/orm-postgres/static'; import type { Contract } from './contract.d'; import contractJson from './contract.json' with { type: 'json' }; export const contract = contractFromJson(contractJson); export const usersDb = postgres({ // [!code ++] contract, url: process.env.USERS_DATABASE_URL!, // [!code ++] }); ``` `contract.d.ts` and `contract.json` do not exist yet; you emit them in step 4. ## 3. Add the posts database [#3-add-the-posts-database] The second database needs the same three files. Create them by hand; running `orm init` again would replace the files from step 2. ```bash mkdir -p prisma/posts ``` ```typescript title="prisma.posts.config.ts" import 'dotenv/config'; import { definePrismaConfig } from '@prisma/cli-engine'; import { defineConfig as ormConfig } from '@prisma/orm-postgres/config'; export default definePrismaConfig({ orm: ormConfig({ contract: "./prisma/posts/contract.prisma", migrations: { dir: "./prisma/posts/migrations", }, db: { connection: process.env.POSTS_DATABASE_URL!, }, }), }); ``` ```prisma title="prisma/posts/contract.prisma" // use prisma-8 model Post { id Int @id @default(autoincrement()) title String content String? authorId Int createdAt TimestamptzString @default(now()) } ``` `authorId` is a plain integer, not a relation. A contract describes one database, and PostgreSQL cannot enforce a foreign key into another database, so the link between a post and its author is resolved in application code in step 5. ```typescript title="prisma/posts/db.ts" import 'dotenv/config'; import postgres from '@prisma/orm-postgres/runtime'; import { contractFromJson } from '@prisma/orm-postgres/static'; import type { Contract } from './contract.d'; import contractJson from './contract.json' with { type: 'json' }; export const contract = contractFromJson(contractJson); export const postsDb = postgres({ contract, url: process.env.POSTS_DATABASE_URL!, }); ``` Now set both connection strings. Both config files and both clients load `.env` through `dotenv/config`, and Next.js loads it as well: ```bash title=".env" USERS_DATABASE_URL="postgres://user:password@localhost:5432/users" POSTS_DATABASE_URL="postgres://user:password@localhost:5432/posts" ``` `orm init` already added `.env` to `.gitignore`. Update `.env.example` with the two variable names so collaborators know what to set. ## 4. Emit the contracts and initialize both databases [#4-emit-the-contracts-and-initialize-both-databases] Each Prisma ORM command works on one config. Add scripts that run every command once per database so you do not have to type `--config` twice: ```json title="package.json" "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "contract:emit": "prisma contract emit --config ./prisma.users.config.ts && prisma contract emit --config ./prisma.posts.config.ts", // [!code ++] "db:init": "prisma db init --config ./prisma.users.config.ts && prisma db init --config ./prisma.posts.config.ts", // [!code ++] "db:verify": "prisma db verify --config ./prisma.users.config.ts && prisma db verify --config ./prisma.posts.config.ts", // [!code ++] "db:update": "prisma db update --config ./prisma.users.config.ts && prisma db update --config ./prisma.posts.config.ts", // [!code ++] "db:seed": "node prisma/seed.ts", // [!code ++] "prebuild": "npm run contract:emit" // [!code ++] } ``` `prebuild` re-emits both contracts before every `next build`, locally and on Vercel, so the build never runs against stale artifacts. Emit the contract artifacts for both databases. This step is offline: #### bun ```bash bun run contract:emit ``` #### pnpm ```bash pnpm run contract:emit ``` #### yarn ```bash yarn contract:emit ``` #### npm ```bash npm run contract:emit ``` ```text no-copy ✔ Emitted contract.json and contract.d.ts │ contract: prisma/users/contract.json │ types: prisma/users/contract.d.ts ✔ Emitted contract.json and contract.d.ts │ contract: prisma/posts/contract.json │ types: prisma/posts/contract.d.ts ``` Create the tables in both databases and sign each one with its contract: #### bun ```bash bun run db:init ``` #### pnpm ```bash pnpm run db:init ``` #### yarn ```bash yarn db:init ``` #### npm ```bash npm run db:init ``` ```text no-copy │ contract: prisma/users/contract.json │ database: postgres://****@localhost:5432/users ✔ Applied 2 operation(s) across 1 contract space App space ├─ Create table "User" ├─ Add unique constraint on "User" (email) └─ marker f340195186d0acf8e9914097e58af0375650e7251358382aa9ad3ed5b724daf7 │ contract: prisma/posts/contract.json │ database: postgres://****@localhost:5432/posts ✔ Applied 1 operation(s) across 1 contract space App space ├─ Create table "Post" └─ marker a0c012793cc392569087d82d7ea41686c8e60586b63c7a131391b99717157804 ``` Each database now carries a marker with the hash of the contract it was initialized from. Confirm both match: #### bun ```bash bun run db:verify ``` #### pnpm ```bash pnpm run db:verify ``` #### yarn ```bash yarn db:verify ``` #### npm ```bash npm run db:verify ``` ```text no-copy │ contract: prisma/users/contract.json │ database: postgres://****@localhost:5432/users ✔ Database marker and schema match contract │ contract: prisma/posts/contract.json │ database: postgres://****@localhost:5432/posts ✔ Database marker and schema match contract ``` The marker is also what protects you from crossing the wires. Verifying the users contract against the posts database stops immediately: #### bun ```bash bunx prisma db verify --config ./prisma.users.config.ts --db "$POSTS_DATABASE_URL" ``` #### pnpm ```bash pnpm prisma db verify --config ./prisma.users.config.ts --db "$POSTS_DATABASE_URL" ``` #### yarn ```bash yarn prisma db verify --config ./prisma.users.config.ts --db "$POSTS_DATABASE_URL" ``` #### npm ```bash npx prisma db verify --config ./prisma.users.config.ts --db "$POSTS_DATABASE_URL" ``` ```text no-copy ✘ [CONTRACT.MARKER_MISMATCH] Hash mismatch why: Contract storageHash does not match database marker ``` ## 5. Query both databases from the app [#5-query-both-databases-from-the-app] ### 5.1. Seed both databases [#51-seed-both-databases] Create a script that writes through both clients. Node.js runs TypeScript directly, so no extra tooling is needed: ```typescript title="prisma/seed.ts" import { usersDb } from "./users/db.ts"; import { postsDb } from "./posts/db.ts"; async function main() { const alice = await usersDb.orm.public.User.create({ email: "alice@prisma.io", name: "Alice", }); const bob = await usersDb.orm.public.User.create({ email: "bob@prisma.io", name: "Bob", }); await postsDb.orm.public.Post.create({ title: "Hello from the posts database", content: "This row lives in the posts database.", authorId: alice.id, }); await postsDb.orm.public.Post.create({ title: "Two databases, one app", content: null, authorId: bob.id, }); console.log("Seeded", alice.email, "and", bob.email, "with one post each."); await usersDb.close(); await postsDb.close(); } main().catch((error) => { console.error(error); process.exit(1); }); ``` The `.ts` extensions in the imports are what Node.js needs to resolve the files. Allow them in `tsconfig.json`, otherwise `next build` fails its type check with `TS5097`: ```json title="tsconfig.json" { "compilerOptions": { "allowImportingTsExtensions": true // [!code ++] } } ``` Run the seed: #### bun ```bash bun run db:seed ``` #### pnpm ```bash pnpm run db:seed ``` #### yarn ```bash yarn db:seed ``` #### npm ```bash npm run db:seed ``` ```text no-copy Seeded alice@prisma.io and bob@prisma.io with one post each. ``` Both clients open their connection pool on the first query. The script closes them at the end so the process can exit. ### 5.2. Render data from both databases [#52-render-data-from-both-databases] Replace `app/page.tsx` with a server component that queries each client and joins posts to their authors in memory: ```tsx title="app/page.tsx" import { usersDb } from "@/prisma/users/db"; import { postsDb } from "@/prisma/posts/db"; export const dynamic = "force-dynamic"; export default async function Home() { const users = await usersDb.orm.public.User.select("id", "email", "name").all(); const posts = await postsDb.orm.public.Post .select("id", "title", "authorId") .orderBy((p) => p.id.asc()) .all(); const authorById = new Map(users.map((u) => [u.id, u])); return (

Multi-database showcase

Users come from one PostgreSQL database, posts from another.

Users

    {users.map((user) => (
  • {user.name} ({user.email})
  • ))}

Posts

    {posts.map((post) => (
  • {post.title}, by {authorById.get(post.authorId)?.name ?? "unknown"}
  • ))}
); } ``` Each client is typed by its own `contract.d.ts`: `usersDb.orm.public` only knows `User`, `postsDb.orm.public` only knows `Post`, and mixing them up is a type error. `force-dynamic` keeps Next.js from trying to render the page at build time, when no database is reachable. ### 5.3. Run the development server [#53-run-the-development-server] #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm run dev ``` ```text no-copy ▲ Next.js 16.3.4 (Turbopack) - Local: http://localhost:3000 - Environments: .env ✓ Ready in 894ms ``` Open [http://localhost:3000](http://localhost:3000). The page lists Alice and Bob under **Users** and the two posts under **Posts**, each attributed to its author. One request, two databases, no adapter or extra client package in between. Finally, confirm the production build passes. `prebuild` emits both contracts first: #### bun ```bash bun run build ``` #### pnpm ```bash pnpm run build ``` #### yarn ```bash yarn build ``` #### npm ```bash npm run build ``` ```text no-copy > prisma contract emit --config ./prisma.users.config.ts && prisma contract emit --config ./prisma.posts.config.ts ... ✓ Compiled successfully ``` ## 6. Deploy to Vercel [#6-deploy-to-vercel] The app needs two environment variables in production and nothing else that is Prisma-specific: `prebuild` runs on Vercel, and there is no client to generate and no engine binary to ship. 1. Push the project to a GitHub repository. If you do not have one yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository), then run: ```bash git add . git commit -m "Next.js app with two Prisma 8 databases" git branch -M main git remote add origin https://github.com//.git git push -u origin main ``` 2. In the [Vercel dashboard](https://vercel.com/), follow [Import an existing project](https://vercel.com/docs/getting-started-with-vercel/import) and stop at the step where you configure the project, before clicking **Deploy**. 3. Expand **Environment variables** and add both connection strings: * **Key**: `USERS_DATABASE_URL`, **Value**: the users database connection string from your `.env` * **Key**: `POSTS_DATABASE_URL`, **Value**: the posts database connection string from your `.env` 4. Click **Deploy**. Vercel runs `npm run build`, which emits both contracts and builds the app. > [!WARNING] > Set both variables before the first deploy. Each config file reads its variable with a non-null assertion, and a missing one fails the first request to the page. Open the live URL. The page renders the same two lists from the same two databases. The Vercel deploy was not run while validating this guide; the `npm run build` it executes is the one from step 5. ## Common gotchas [#common-gotchas] > [!WARNING] > Commands without `--config` fail once the default config is gone. Running `npx prisma contract emit` with no `./prisma.config.ts` (or with one that has no `orm` section) stops with `[CONFIG.FILE_NOT_FOUND]` and a hint that the `orm` config section is absent. Use the package scripts from step 4, or pass `--config` explicitly. * **No relations across databases.** A contract covers one database. Keep a plain id column such as `authorId` on the side that references the other database, and join in application code. * **`npx prisma@latest init` writes a third config.** It creates a `prisma.config.ts` that holds only the `skills` section for agent skills. That is expected; the database commands keep using `--config` with the two database configs. * **Do not close a client per request.** In `page.tsx` and route handlers, never call `usersDb.close()`. The pools are shared across requests and close when the process exits. Only scripts such as `prisma/seed.ts` close them. * **`orm init` picks the package manager from your lockfile.** Run it after `create-next-app` has written `package-lock.json`, `pnpm-lock.yaml`, or `bun.lock`, or it may install with a different package manager than the one you use. ## Prompt your coding agent [#prompt-your-coding-agent] Run [`npx prisma@latest init`](https://www.prisma.io/docs/cli/init) once to install the [Prisma ORM skills](https://www.prisma.io/docs/ai/tools/skills#available-skills-for-prisma-8) for your coding agent and keep them matching your installed packages. Prompts that map to this guide: * "Using the prisma-8 skill, add a `Comment` model to `prisma/posts/contract.prisma`, emit with `--config ./prisma.posts.config.ts`, and update the posts database." * "Add a third database for billing following the same layout: `prisma.billing.config.ts`, `prisma/billing/contract.prisma`, `prisma/billing/db.ts`, and extend the package scripts." * "Write a route handler that creates a post for the signed-in user, validating that the `authorId` exists in the users database first." ## Next steps [#next-steps] * Change a contract, then run `npm run contract:emit` and `npm run db:update` to apply the change to both databases in development. For checked-in migrations, run [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) and [`db migrate`](https://www.prisma.io/docs/cli/db-migrate) with the `--config` of the database you changed; each writes to its own `migrations.dir`. * [Learn the fundamentals](https://www.prisma.io/docs/orm/fundamentals/reading-data): filtering, sorting, pagination, and writes. * [CLI configuration](https://www.prisma.io/docs/cli/configuration) covers everything `prisma.config.ts` can hold. * Splitting the app itself into packages? See [pnpm workspaces](https://www.prisma.io/docs/guides/deployment/pnpm-workspaces) and [Turborepo](https://www.prisma.io/docs/guides/deployment/turborepo). ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/database/data-migration): Replace a column without downtime using the expand and contract pattern, with the data backfill inside a Prisma ORM migration. - [`Schema management in teams`](https://www.prisma.io/docs/guides/database/schema-changes): Plan, merge, and apply Prisma ORM migrations when several developers change the schema at the same time. # Schema management in teams (/docs/guides/database/schema-changes) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Plan, merge, and apply Prisma ORM migrations when several developers change the schema at the same time. Location: Guides > Database > Schema management in teams ## Introduction [#introduction] When a team works on one schema, two people change it at the same time. In Prisma ORM, migrations form a graph rather than a numbered list, so parallel changes do not force anyone to rename files or rebuild history. This guide shows how that works day to day: what to commit, how to incorporate a teammate's migration, and how to resolve the case where two branches planned a migration from the same starting point and both merged. Every command and every output below was run against a Git repository with three checkouts (two teammates and you), each with its own local PostgreSQL database. > [!NOTE] > Using Prisma ORM 7? > > Prisma ORM 8 is a [release candidate](https://www.prisma.io/docs/orm/release-status). Prisma ORM 7 remains fully supported; the Prisma ORM 7 version of this guide is at [/guides/v7/database/schema-changes](https://www.prisma.io/docs/guides/v7/database/schema-changes). ## Prerequisites [#prerequisites] * [Node.js](https://nodejs.org) 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer (24 recommended) * A Prisma ORM project with a contract and at least one migration ([Create a new app with PostgreSQL](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql) gives you one) * A PostgreSQL database per developer, reachable as `DATABASE_URL` * Basic familiarity with Git branches and merges * The [migration loop](https://www.prisma.io/docs/orm/migrations/how-migrations-work): `contract emit`, `migration plan`, `db migrate` ## Use with your agent [#use-with-your-agent] To delegate the pull-and-apply part of this guide to your coding agent, copy the prompt below and hand it over: ```text Bring my local database up to date with the migrations on this branch using Prisma ORM, following https://www.prisma.io/docs/guides/database/schema-changes.md. 1. Run `npx prisma migration status` and tell me what is pending. If it reports "Up to date", stop. 2. If it warns that there is no migration path from the database state to the contract, the graph has two branch tips. Run `npx prisma migration graph`, then plan one merge migration from each tip with `npx prisma migration plan --from --name merge_`, and show me both DDL previews before continuing. 3. Apply with `npx prisma db migrate --advance-ref db`, then run `npx prisma migration check` and `npx prisma db verify`. 4. If `migration plan` fails with MIGRATION.PLAN_ORIGIN_UNKNOWN, do not delete any migration directory. Find the contract state the database is on in the `npx prisma migration status` output, pass that hash with `--from`, and show me the error text. If you cannot tell which state the database is on, stop and ask me. ``` ## 1. Understand migration basics [#1-understand-migration-basics] ### 1.1. Migrations form a graph [#11-migrations-form-a-graph] Each migration directory records the contract state it starts `from` and the state it ends at, `to`, as hashes in its `migration.json`. Those links are the migration history. The timestamp in the directory name is for humans; nothing depends on it. That is why two developers can plan migrations from the same state on separate branches and merge without renaming anything. [The migration graph](https://www.prisma.io/docs/orm/migrations/the-migration-graph) explains the model in full. Three commands answer the questions a team asks most: | Question | Command | Needs a database? | | ---------------------------------------------------- | ----------------------------- | ----------------- | | What does the history look like? | `npx prisma migration graph` | No | | Where is my database, and what is pending? | `npx prisma migration status` | Yes | | Do the migration files on this branch hold together? | `npx prisma migration check` | No | ### 1.2. Commit these files [#12-commit-these-files] Commit everything Prisma ORM needs to rebuild a database from scratch: * `src/prisma/contract.prisma`, the schema you author * `src/prisma/contract.json` and `src/prisma/contract.d.ts`, the emitted contract (generated, but committed; `orm init` marks them `linguist-generated` in `.gitattributes`) * `migrations/app/`, every migration directory: `migration.ts`, `ops.json`, and `migration.json` together * `migrations/snapshots/`, the contract snapshots migrations are typed against * `migrations/app/refs/`, named refs, including the `db` ref described next * `prisma.config.ts` Do not commit `.env`. `orm init` already lists it in `.gitignore`. ### 1.3. Where a plan starts [#13-where-a-plan-starts] `migration plan` is offline. It never asks the database which contract state it matches, so you have to tell it which state to plan from. It resolves the origin in this order: an explicit `--from`, otherwise the ref named `db` in `migrations/app/refs/db.json`, otherwise the empty database. Keep the `db` ref pointing at the state your local database matches by applying with `--advance-ref db`: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` Do that every time you apply, and every plan chains from the right place without flags. Section 3 shows what happens when it cannot. ### 1.4. The project this guide starts from [#14-the-project-this-guide-starts-from] The project was created with `npx prisma@latest orm init --yes --target postgres --authoring psl` and has this contract: ```prisma title="src/prisma/contract.prisma" // use prisma-8 model User { id Int @id @default(autoincrement()) email String @unique username String? name String? posts Post[] createdAt TimestamptzString @default(now()) updatedAt DateTime(as: string) @onCreate(now()) @onUpdate(now()) } model Post { id Int @id @default(autoincrement()) title String content String? author User @relation(fields: [authorId], references: [id]) authorId Int createdAt TimestamptzString @default(now()) updatedAt DateTime(as: string) @onCreate(now()) @onUpdate(now()) } ``` Its first migration was planned and applied on `main` with: #### bun ```bash bunx prisma migration plan --name init bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma migration plan --name init pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma migration plan --name init yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma migration plan --name init npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (6 operation(s)) across 1 contract space(s) App space ├─ Create schema "public" ├─ Create table "Post" ├─ Create table "User" ├─ Add unique constraint on "User" (email) ├─ Create index "Post_authorId_idx_e47547ed" on "Post" ├─ Add foreign key "Post_authorId_fkey" on "Post" └─ marker 91e7f9f035806fa2789a4d726ef7724cad434fd6b00014d47ebf12d6e6bb784e ✔ Advanced ref "db" → 91e7f9f035806fa2789a4d726ef7724cad434fd6b00014d47ebf12d6e6bb784e → Check every space against the database: prisma migration status ``` Every developer clones this repository, points `DATABASE_URL` in their `.env` at their own database, and runs `npx prisma db migrate` once to bring it to the same state. ## 2. Incorporate team changes [#2-incorporate-team-changes] ### 2.1. Pull, check, apply [#21-pull-check-apply] When a teammate merges a schema change, it arrives as three things: an edited `contract.prisma`, the re-emitted `contract.json` and `contract.d.ts`, and a new migration directory. Pull them, then ask Prisma which contract state your database matches: ```bash git pull ``` #### bun ```bash bunx prisma migration status ``` #### pnpm ```bash pnpm prisma migration status ``` #### yarn ```bash yarn prisma migration status ``` #### npm ```bash npx prisma migration status ``` If nothing changed, you see the whole history marked applied: ```text no-copy ○ 91e7f9f @contract @db (db) │↑ 20260910T1543_init ∅ → 91e7f9f 6 ops ✓ applied ○ ∅ ✔ Up to date ``` `@db` marks the contract state your database matches, `@contract` the emitted contract, and `(db)` the state the `db` ref names. When migrations are pending, the tree flags each one with `⧗ pending` and a summary line tells you how many. Apply them and update the `db` ref in one step: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` There is no generate step after applying: your typed client reads `contract.json`, which you just pulled. ### 2.2. Example scenario [#22-example-scenario] The rest of this guide follows three developers changing the same contract. Ania adds a `favoriteColor` field, Javier adds a `Tag` model, and you add a `bestPacmanScore` field: #### Before ```prisma title="src/prisma/contract.prisma" model User { id Int @id @default(autoincrement()) email String @unique username String? name String? posts Post[] createdAt TimestamptzString @default(now()) updatedAt DateTime(as: string) @onCreate(now()) @onUpdate(now()) } ``` #### After ```prisma title="src/prisma/contract.prisma" model User { id Int @id @default(autoincrement()) email String @unique username String? name String? favoriteColor String? // Added by Ania // [!code ++] bestPacmanScore Int? // Added by you // [!code ++] posts Post[] createdAt TimestamptzString @default(now()) updatedAt DateTime(as: string) @onCreate(now()) @onUpdate(now()) } // Added by Javier // [!code ++] model Tag { // [!code ++] tagName String @id // [!code ++] tagCategory String // [!code ++] } // [!code ++] ``` ## 3. Handle concurrent changes [#3-handle-concurrent-changes] Ania and Javier both branch from the same commit on `main`, where the `db` ref points at the `init` state. ### 3.1. Ania adds a field [#31-ania-adds-a-field] On her branch, Ania adds the field: ```prisma title="src/prisma/contract.prisma" model User { /* ... */ favoriteColor String? } ``` Then she emits, plans, and applies to her own database: #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_favorite_color ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_favorite_color ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_favorite_color ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_favorite_color ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1546_add_favorite_color └─ Add column "favoriteColor" to "User" from: 91e7f9f035806fa2789a4d726ef7724cad434fd6b00014d47ebf12d6e6bb784e to: b29af3990b528c7a67809a2ac609305c59aa9c0af1ed0e4591cc0a727b38b1d1 app space: migrations/app/20260910T1546_add_favorite_color ℹ DDL preview ALTER TABLE "public"."User" ADD COLUMN "favoriteColor" text; ``` The `from:` line is the `init` state, taken from the `db` ref. She applies and commits: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (1 operation(s)) across 1 contract space(s) App space ├─ Add column "favoriteColor" to "User" └─ marker b29af3990b528c7a67809a2ac609305c59aa9c0af1ed0e4591cc0a727b38b1d1 ✔ Advanced ref "db" → b29af3990b528c7a67809a2ac609305c59aa9c0af1ed0e4591cc0a727b38b1d1 ``` ```bash git add -A git commit -m "Add User.favoriteColor" ``` ### 3.2. Javier adds a model [#32-javier-adds-a-model] On his branch, from the same starting commit, Javier adds a model: ```prisma title="src/prisma/contract.prisma" model Tag { tagName String @id tagCategory String } ``` #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_tag_model ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_tag_model ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_tag_model ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_tag_model ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1547_add_tag_model └─ Create table "Tag" from: 91e7f9f035806fa2789a4d726ef7724cad434fd6b00014d47ebf12d6e6bb784e to: 18b24e59a8b291a37b50e0d82c7afb58b314a2b64920d530627c73bd6e2d9768 app space: migrations/app/20260910T1547_add_tag_model ℹ DDL preview CREATE TABLE "public"."Tag" ( "tagCategory" text NOT NULL, "tagName" text NOT NULL, PRIMARY KEY ("tagName") ); ``` His plan also starts `from:` the `init` state. He applies with `db migrate --advance-ref db` and commits. Both migrations now leave the same node and arrive at different ones. Neither developer knows about the other yet, and neither needs to. ### 3.3. Merge both branches [#33-merge-both-branches] Ania's branch merges into `main` first, as a fast-forward. Javier's merge conflicts: ```bash git merge javier/tag-model ``` ```text no-copy Auto-merging migrations/app/refs/db.json CONFLICT (content): Merge conflict in migrations/app/refs/db.json Auto-merging src/prisma/contract.d.ts CONFLICT (content): Merge conflict in src/prisma/contract.d.ts Auto-merging src/prisma/contract.json CONFLICT (content): Merge conflict in src/prisma/contract.json Auto-merging src/prisma/contract.prisma Automatic merge failed; fix conflicts and then commit the result. ``` Read the list carefully. `contract.prisma`, the file you author, merged cleanly: the two edits touch different parts of the schema. The three conflicts are all in files Prisma writes for you, and none of them needs hand editing: * `contract.json` and `contract.d.ts` are emitted from `contract.prisma`. Re-emit and they are regenerated from the merged source, conflict markers and all: #### bun ```bash bunx prisma contract emit ``` #### pnpm ```bash pnpm prisma contract emit ``` #### yarn ```bash yarn prisma contract emit ``` #### npm ```bash npx prisma contract emit ``` ```text no-copy ✔ Emitted contract.json and contract.d.ts storageHash: 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ``` * `migrations/app/refs/db.json` records the contract state a local database last matched. Each branch pointed it at its own state, and neither is the state your database matches now. Take either side; you will set it correctly when you apply in section 3.5. ```bash git checkout --ours migrations/app/refs/db.json ``` Do not commit yet. The graph is not finished. ### 3.4. What Prisma reports after the merge [#34-what-prisma-reports-after-the-merge] Draw the graph: #### bun ```bash bunx prisma migration graph ``` #### pnpm ```bash pnpm prisma migration graph ``` #### yarn ```bash yarn prisma migration graph ``` #### npm ```bash npx prisma migration graph ``` ```text no-copy ○ 1e5059c @contract ○ b29af39 (db) │↑ 20260910T1546_add_favorite_color 91e7f9f → b29af39 1 ops │ ○ 18b24e5 │ │↑ 20260910T1547_add_tag_model 91e7f9f → 18b24e5 1 ops │─╯ ○ 91e7f9f │↑ 20260910T1543_init ∅ → 91e7f9f 6 ops ○ ∅ 1 space(s), 4 contract(s), 3 migration(s) ``` Read it bottom-up. From `init` (`91e7f9f`) two branches leave: Ania's ends at `b29af39`, Javier's at `18b24e5`. The merged contract you just emitted, `1e5059c`, sits at the top with no edge arriving at it. No database can reach it yet. `migration status` draws the same graph and marks where your database is, which is still on `init` (`@db`): #### bun ```bash bunx prisma migration status ``` #### pnpm ```bash pnpm prisma migration status ``` #### yarn ```bash yarn prisma migration status ``` #### npm ```bash npx prisma migration status ``` ```text no-copy ○ 1e5059c @contract ○ b29af39 (db) │↑ 20260910T1546_add_favorite_color 91e7f9f → b29af39 1 ops │ ○ 18b24e5 │ │↑ 20260910T1547_add_tag_model 91e7f9f → 18b24e5 1 ops │─╯ ○ 91e7f9f @db │↑ 20260910T1543_init ∅ → 91e7f9f 6 ops ✓ applied ○ ∅ ⚠ No migration path from the database state (91e7f9f03580) to the application's contract (1e5059c1976c). Run `prisma migration plan --name ` to author one. ``` Do not follow that hint literally. Without `--from`, the planner takes the `db` ref as its origin, and after `git checkout --ours` that ref is Ania's tip, so `migration plan --name merge_schema` writes only the half of the merge her branch is missing. Javier's database would still have no path to the top. Had the ref still pointed at `init`, the planner would have started a third branch from the divergence point instead, with a warning that it forks the graph. Neither is the merge. Do not delete either branch's migration directory to get out of this: Ania's and Javier's databases have already applied those migrations. Name the origin yourself, once per tip. ### 3.5. Close the diamond [#35-close-the-diamond] Plan one merge migration from each tip. Each one carries the change its branch is missing, and both arrive at the merged contract: #### bun ```bash bunx prisma migration plan --from 20260910T1546_add_favorite_color --name merge_add_tag_model ``` #### pnpm ```bash pnpm prisma migration plan --from 20260910T1546_add_favorite_color --name merge_add_tag_model ``` #### yarn ```bash yarn prisma migration plan --from 20260910T1546_add_favorite_color --name merge_add_tag_model ``` #### npm ```bash npx prisma migration plan --from 20260910T1546_add_favorite_color --name merge_add_tag_model ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1550_merge_add_tag_model └─ Create table "Tag" from: b29af3990b528c7a67809a2ac609305c59aa9c0af1ed0e4591cc0a727b38b1d1 to: 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ``` #### bun ```bash bunx prisma migration plan --from 20260910T1547_add_tag_model --name merge_add_favorite_color ``` #### pnpm ```bash pnpm prisma migration plan --from 20260910T1547_add_tag_model --name merge_add_favorite_color ``` #### yarn ```bash yarn prisma migration plan --from 20260910T1547_add_tag_model --name merge_add_favorite_color ``` #### npm ```bash npx prisma migration plan --from 20260910T1547_add_tag_model --name merge_add_favorite_color ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1550_merge_add_favorite_color └─ Add column "favoriteColor" to "User" from: 18b24e59a8b291a37b50e0d82c7afb58b314a2b64920d530627c73bd6e2d9768 to: 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ``` `--from` accepts a migration directory name, as here, or a contract hash from the graph. The planner diffs the two contract snapshots and writes exactly the operations that are missing on that side. Review both DDL previews the way you would review any migration. The graph is now a diamond, and every database on either branch has a path to the top: #### bun ```bash bunx prisma migration graph ``` #### pnpm ```bash pnpm prisma migration graph ``` #### yarn ```bash yarn prisma migration graph ``` #### npm ```bash npx prisma migration graph ``` ```text no-copy ○ 1e5059c @contract │─╮ │↑│ 20260910T1550_merge_add_tag_model b29af39 → 1e5059c 1 ops │ │↑ 20260910T1550_merge_add_favorite_color 18b24e5 → 1e5059c 1 ops ○ │ b29af39 (db) │↑│ 20260910T1546_add_favorite_color 91e7f9f → b29af39 1 ops │ ○ 18b24e5 │ │↑ 20260910T1547_add_tag_model 91e7f9f → 18b24e5 1 ops │─╯ ○ 91e7f9f │↑ 20260910T1543_init ∅ → 91e7f9f 6 ops ○ ∅ 1 space(s), 5 contract(s), 5 migration(s) ``` Your own database is still on `init`, so two migrations are pending for it. Apply them and let `--advance-ref db` set the `db` ref to where the database actually ends up, which also settles the `db.json` conflict from section 3.3: #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 2 migration(s) (2 operation(s)) across 1 contract space(s) App space ├─ Add column "favoriteColor" to "User" ├─ Create table "Tag" └─ marker 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ✔ Advanced ref "db" → 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ``` The runner walked `init → add_favorite_color → merge_add_tag_model`. It could equally have walked the other side; both paths end at the same contract. Now commit the merge, the re-emitted contract, both merge migrations, and the `db` ref together: ```bash git add -A git commit -m "Merge javier/tag-model and plan merge migrations" ``` ### 3.6. Every database runs only the migrations it needs [#36-every-database-catches-up-on-its-own-path] Ania pulls `main`. Her database matches `b29af39`, so only the migration that adds Javier's table is pending for her: #### bun ```bash bunx prisma migration status ``` #### pnpm ```bash pnpm prisma migration status ``` #### yarn ```bash yarn prisma migration status ``` #### npm ```bash npx prisma migration status ``` ```text no-copy ○ 1e5059c @contract (db) │─╮ │↑│ 20260910T1550_merge_add_tag_model b29af39 → 1e5059c 1 ops ⧗ pending │ │↑ 20260910T1550_merge_add_favorite_color 18b24e5 → 1e5059c 1 ops ○ │ b29af39 @db │↑│ 20260910T1546_add_favorite_color 91e7f9f → b29af39 1 ops ✓ applied │ ○ 18b24e5 │ │↑ 20260910T1547_add_tag_model 91e7f9f → 18b24e5 1 ops │─╯ ○ 91e7f9f │↑ 20260910T1543_init ∅ → 91e7f9f 6 ops ✓ applied ○ ∅ ⚠ 1 pending: run `prisma db migrate --to 1e5059c1976c` ``` #### bun ```bash bunx prisma db migrate --advance-ref db ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db ``` #### yarn ```bash yarn prisma db migrate --advance-ref db ``` #### npm ```bash npx prisma db migrate --advance-ref db ``` ```text no-copy ✔ Applied 1 migration(s) (1 operation(s)) across 1 contract space(s) App space ├─ Create table "Tag" └─ marker 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b ``` Javier does the same, and for him the pending migration is `merge_add_favorite_color`, which adds Ania's column. Nobody re-created anything, and the database's own ledger shows the route each one took: #### bun ```bash bunx prisma migration log ``` #### pnpm ```bash pnpm prisma migration log ``` #### yarn ```bash yarn prisma migration log ``` #### npm ```bash npx prisma migration log ``` ```text no-copy Applied at Migration Change Ops 2026-09-10 17:45:41 +02:00 20260910T1543_init ∅ → 91e7f9f 6 ops 2026-09-10 17:46:17 +02:00 20260910T1546_add_favorite_color 91e7f9f → b29af39 1 ops 2026-09-10 17:52:47 +02:00 20260910T1550_merge_add_tag_model b29af39 → 1e5059c 1 ops ``` ## 4. Integrate your changes [#4-integrate-your-changes] ### 4.1. Pull first [#41-pull-first] With `main` merged and your database on the merged state, add your own field. Always pull and apply before you plan, so your plan chains from the state everyone shares: ```bash git pull ``` #### bun ```bash bunx prisma migration status ``` #### pnpm ```bash pnpm prisma migration status ``` #### yarn ```bash yarn prisma migration status ``` #### npm ```bash npx prisma migration status ``` ### 4.2. Edit, emit, plan [#42-edit-emit-plan] ```prisma title="src/prisma/contract.prisma" model User { /* ... */ favoriteColor String? bestPacmanScore Int? } ``` #### bun ```bash bunx prisma contract emit bunx prisma migration plan --name add_best_pacman_score ``` #### pnpm ```bash pnpm prisma contract emit pnpm prisma migration plan --name add_best_pacman_score ``` #### yarn ```bash yarn prisma contract emit yarn prisma migration plan --name add_best_pacman_score ``` #### npm ```bash npx prisma contract emit npx prisma migration plan --name add_best_pacman_score ``` ```text no-copy ✔ Planned 1 operation(s) migrations/app/20260910T1554_add_best_pacman_score └─ Add column "bestPacmanScore" to "User" from: 1e5059c1976c2439863eae8ac13211916ca411614c917394c413346f0d00f60b to: 4961e5b3ceb00cb24a60245343f288095c5a00fc2344d02db1b68509a8b91440 app space: migrations/app/20260910T1554_add_best_pacman_score ℹ DDL preview ALTER TABLE "public"."User" ADD COLUMN "bestPacmanScore" int4; ``` No `--from` was needed: the `db` ref points at the merged state because the last apply advanced it. Check the `from:` line anyway. If it does not name the state you expect, stop and read [Common gotchas](#common-gotchas). ### 4.3. Apply and check [#43-apply-and-check] #### bun ```bash bunx prisma db migrate --advance-ref db bunx prisma migration check ``` #### pnpm ```bash pnpm prisma db migrate --advance-ref db pnpm prisma migration check ``` #### yarn ```bash yarn prisma db migrate --advance-ref db yarn prisma migration check ``` #### npm ```bash npx prisma db migrate --advance-ref db npx prisma migration check ``` ```text no-copy ✔ Applied 1 migration(s) (1 operation(s)) across 1 contract space(s) App space ├─ Add column "bestPacmanScore" to "User" └─ marker 4961e5b3ceb00cb24a60245343f288095c5a00fc2344d02db1b68509a8b91440 ✔ Advanced ref "db" → 4961e5b3ceb00cb24a60245343f288095c5a00fc2344d02db1b68509a8b91440 ``` ```text no-copy ✔ All checks passed ``` `migration check` is offline and verifies every migration's hash and the graph's integrity. Run it after you edit a migration by hand, so an `ops.json` or `migration.json` that no longer matches its hash shows up before you commit. A pipeline does not need it, because `db migrate` refuses such a migration too. `migration check` reads only the files, so it cannot tell you whether a database matches them. `db verify` does. Run `npx prisma db verify --db "$DATABASE_URL"` after `db migrate`, and it fails if the database's marker or its tables differ from the contract you emitted. A pipeline that migrates a shared database runs `db migrate` alone; it refuses a database whose marker is outside your history with `MIGRATION.MARKER_MISMATCH` before it runs anything. [Migrate a shared database from a workflow](https://www.prisma.io/docs/guides/integrations/github-actions#migrate-a-shared-database) shows the job. ### 4.4. Commit [#44-commit] Commit the same set of files your teammates did: ```bash git add src/prisma/contract.prisma src/prisma/contract.json src/prisma/contract.d.ts migrations git commit -m "Add User.bestPacmanScore" ``` The final graph on `main` is a diamond with one more step on top, and your application code can use all three changes right away: ```ts title="script.ts" const user = await db.orm.public.User.create({ email: "pacman@prisma.io", favoriteColor: "yellow", bestPacmanScore: 3333360, }); const tag = await db.orm.public.Tag.create({ tagName: "arcade", tagCategory: "games" }); ``` ## Common gotchas [#common-gotchas] > [!WARNING] > `migration plan` fails with `MIGRATION.PLAN_ORIGIN_UNKNOWN` when the project has migrations but no `db` ref and you passed no `--from`. This happens in a fresh clone that has never run `db migrate --advance-ref db`, or after a merge dropped `refs/db.json`. The error lists the three exits: > > ```text no-copy > ✘ [MIGRATION.PLAN_ORIGIN_UNKNOWN] Cannot determine the plan origin: migrations exist but no origin is named > why: Migrations exist on disk, but there is no `db` ref and no --from was given, so the plan origin would silently fall back to an empty database and the resulting migration would recreate everything the existing migrations already create. > → Point the db ref at the origin contract: prisma migration ref set db > → Plan from an explicit origin: prisma migration plan --from > → Plan from an empty database deliberately: prisma migration plan --from @empty > ``` > > Pick the first or second. `--from @empty` over an existing history is only right for a deliberate rebuild. > [!WARNING] > Never run `db update` against a database that changes only through migrations, such as production. It reconciles the database to your contract directly and leaves no migration behind, so when the contract it applied is one no migration starts or ends at, the next `db migrate` there finds a marker the graph does not know. Use `db update` only on a database whose migration history does not need to be kept, and switch to `migration plan` before you open a pull request. A `db update` without `--db` moves the `db` ref to the contract it applied, and `migration plan` starts from that ref. So to keep that change in your migration history, plan it from the state before it: `npx prisma migration plan --from `, where `` is your newest migration directory. If a shared database such as staging fails with `MIGRATION.MARKER_MISMATCH`, the error's `db update` commands move it back; [Drift](https://www.prisma.io/docs/orm/migrations/rollbacks-and-recovery#drift-when-the-database-isnt-where-migrations-left-it) explains. > [!NOTE] > The merge conflict in `migrations/app/refs/db.json` is expected whenever two branches both applied with `--advance-ref db`. The file records where one developer's database was, so no merged value is "correct" for everyone. Resolve it with either side and let your next `db migrate --advance-ref db` write the truth. > [!NOTE] > Renaming a field plans as a destructive drop column plus add column, because the planner has no rename hint yet. Before a rename reaches a shared database, [edit the migration](https://www.prisma.io/docs/orm/migrations/editing-a-migration) to replace the pair with a `rawSql` `ALTER TABLE ... RENAME COLUMN`, then recompile it with `node migration.ts`. ## Prompt your coding agent [#prompt-your-coding-agent] Run [`npx prisma@latest init`](https://www.prisma.io/docs/cli/init) once to install the [Prisma ORM skills](https://www.prisma.io/docs/ai/tools/skills#available-skills-for-prisma-8) for your coding agent and keep them matching your installed packages. Prompts that map to this guide: * "Using the prisma-8 skill, check whether my database is behind the migrations on this branch and apply what is pending." * "Two branches both added migrations from the same state. Draw the migration graph and plan the merge migrations from each tip." * "Run `migration check` and explain any integrity failure before I open this pull request." ## Next steps [#next-steps] * [The migration graph](https://www.prisma.io/docs/orm/migrations/the-migration-graph): refs, markers, and how `db migrate` finds a path * [Applying a migration](https://www.prisma.io/docs/orm/migrations/applying-a-migration): the status, preview, apply rhythm for staging and production * [Rollbacks and recovery](https://www.prisma.io/docs/orm/migrations/rollbacks-and-recovery): planning a backwards edge when a merged change has to come out * [Editing a migration](https://www.prisma.io/docs/orm/migrations/editing-a-migration): backfills and raw SQL when a schema change needs a data step ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/database/data-migration): Replace a column without downtime using the expand and contract pattern, with the data backfill inside a Prisma ORM migration. - [`Multiple databases`](https://www.prisma.io/docs/guides/database/multiple-databases): Connect one Next.js app to two PostgreSQL databases with Prisma ORM: one contract, config, and client per database, selected with the --config flag. # Bun workspaces (/docs/guides/deployment/bun-workspaces) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Set up Prisma ORM in a Bun workspaces monorepo through a shared database package, seed it with Bun, and query it from a Next.js app in the same workspace. Location: Guides > Deployment > Bun workspaces ## Introduction [#introduction] This guide shows you how to use Prisma ORM in a [Bun workspaces](https://bun.sh/docs/install/workspaces) monorepo. You create a shared `database` package that owns the schema, the database client, and a seed script, then import that client from a Next.js app in the same workspace. Every workspace member shares one lockfile and one `bun install`, so the database package is wired into the app like any other dependency. Every command, file, and output below was run end to end against a live PostgreSQL database. > [!NOTE] > Using Prisma ORM 7? > > Prisma ORM 8 is a [release candidate](https://www.prisma.io/docs/orm/release-status). Prisma ORM 7 remains fully supported; the Prisma ORM 7 version of this guide is at [/guides/v7/deployment/bun-workspaces](https://www.prisma.io/docs/guides/v7/deployment/bun-workspaces). ## Prerequisites [#prerequisites] * [Bun](https://bun.sh/docs/installation) 1.1 or later (`bun --version`) * [Node.js](https://nodejs.org) 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer (24 recommended): Bun runs the scripts, and Next.js runs on Node.js * A PostgreSQL connection string, or nothing at all: `bunx create-db@latest` can create a [Prisma Postgres](https://www.prisma.io/docs/postgres) database for you ## Use with your agent [#use-with-your-agent] To delegate this guide to your coding agent, copy the prompt below and hand it over: ```text Create a Bun workspaces monorepo with a shared Prisma ORM database package and a Next.js app that queries it. 1. Create `my-monorepo` with a root `package.json` that sets `"workspaces": ["apps/*", "packages/*"]`, then create `apps/` and `packages/database/`. Give `packages/database` a `package.json` with `"name": "database"`, `"private": true`, `"type": "module"` and `"main": "index.ts"`. 2. In `packages/database`, run `bunx prisma@latest orm init --yes --target postgres --authoring psl`. Then run `bunx prisma@latest init` there so the Prisma agent skills are installed and stay current, and use them. Get a database connection string: use the one I give you, or create a Prisma Postgres database with `bunx create-db@latest` and show me the claim URL it prints. Write it as `DATABASE_URL` into `packages/database/.env`. 3. Add package scripts to `packages/database`: `db:init` (`prisma db init`), `db:update` (`prisma db update`), `db:seed` (`bun src/prisma/seed.ts`). Run `bun run db:init` there. 4. Create `packages/database/index.ts` that re-exports `db` from `./src/prisma/db`, and `packages/database/src/prisma/seed.ts` that upserts three users with `db.orm.public.User.upsert({ create, update: {}, conflictOn: { email } })` and ends with `await db.close()`, following https://www.prisma.io/docs/guides/deployment/bun-workspaces.md. Run `bun run db:seed`. 5. Add root scripts `dev`, `build`, `start`, `db:init`, `db:update` and `seed` that use `bun run --filter // [!code ++] ``` Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead. ```html title="src/pages/sign-up/index.astro" --- export const prerender = false; if (Astro.locals.user?.id) return Astro.redirect("/dashboard"); // [!code ++] --- Sign Up

Sign Up

Already have an account? Sign in here.

``` ### 7.2. Sign in page [#72-sign-in-page] This page allows existing users to authenticate. Start with the basic HTML structure in `src/pages/sign-in/index.astro`. ```html title="src/pages/sign-in/index.astro" --- export const prerender = false; --- Sign In

Sign In

``` Add a form with input fields for email and password. This form will collect the user's credentials. ```html title="src/pages/sign-in/index.astro" --- export const prerender = false; --- Sign In

Sign In

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

Don't have an account? Sign up here.

// [!code ++]
``` Now add a script to handle form submission. Import the `authClient` and add an event listener that prevents default submission, extracts the form data, and calls the Better Auth sign-in method. ```html title="src/pages/sign-in/index.astro" --- export const prerender = false; --- Sign In

Sign In

Don't have an account? Sign up here.

// [!code ++] ``` Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead. ```html title="src/pages/sign-in/index.astro" --- export const prerender = false; if (Astro.locals.user?.id) return Astro.redirect("/dashboard"); // [!code ++] --- Sign In

Sign In

Don't have an account? Sign up here.

``` ### 7.3. Dashboard page [#73-dashboard-page] This is the protected page for authenticated users. Start with the basic HTML structure in `src/pages/dashboard/index.astro`. ```html title="src/pages/dashboard/index.astro" --- export const prerender = false; --- Dashboard

Dashboard

``` Add a server-side check to protect this route. If the user is not authenticated, redirect them to the sign-in page. ```html title="src/pages/dashboard/index.astro" --- export const prerender = false; if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); // [!code ++] --- Dashboard

Dashboard

``` Now display the authenticated user's information. The `Astro.locals.user` object contains the user data that was set by the middleware. ```html title="src/pages/dashboard/index.astro" --- export const prerender = false; if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); --- Dashboard

Dashboard

{JSON.stringify(Astro.locals.user, null, 2)}
// [!code ++]
``` Finally, add a sign-out button. Import the `authClient` and add a button that calls the sign-out method, allowing the user to log out and be redirected to the sign-in page. ```html title="src/pages/dashboard/index.astro" --- export const prerender = false; if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); --- Dashboard

Dashboard

{JSON.stringify(Astro.locals.user, null, 2)}
// [!code ++]
// [!code ++] ``` ### 7.4. Home page [#74-home-page] Finally, update the home page to link to the sign-up, sign-in, and dashboard pages. Replace the contents of `src/pages/index.astro` with the following: ```html title="src/pages/index.astro" --- export const prerender = false; --- Better Auth + Astro + Prisma

Better Auth + Astro + Prisma

{ Astro.locals.user ? (

Welcome back, {Astro.locals.user.name}!

Go to Dashboard
) : ( ) }
``` ## 8. Test it out [#8-test-it-out] Your application is now fully configured. 1. Start the development server to test it: #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm run dev ``` 2. Navigate to `http://localhost:4321` in your browser. You should see the home page with "Sign Up" and "Sign In" links. 3. Click on **Sign Up**, create a new account, and you should be redirected to the dashboard. You can then sign out and sign back in. 4. To view the user data directly in your database, you can use Prisma Studio. #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm prisma studio ``` #### yarn ```bash yarn prisma studio ``` #### npm ```bash npx prisma studio ``` 5. This will open a new tab in your browser where you can see the `User`, `Session`, and `Account` tables and their contents. > [!TIP] > You now have a working authentication system built with Better Auth, Prisma, and Astro. ## Next steps [#next-steps] * Add support for social login or magic links * Implement password reset and email verification * Add user profile and account management pages * Deploy to Vercel or Netlify and secure your environment variables * Extend your Prisma schema with custom application models ## Further reading [#further-reading] * [Better Auth documentation](https://www.better-auth.com/docs) * [Prisma documentation](https://www.prisma.io/docs/orm/v7) * [Astro documentation](https://astro.build/docs) ## Related pages - [`Better Auth (with Next.js)`](https://www.prisma.io/docs/guides/authentication/better-auth/nextjs): Learn how to use Prisma ORM in a Next.js app with Better Auth # Better Auth (with Next.js) (/docs/guides/authentication/better-auth/nextjs) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Learn how to use Prisma ORM in a Next.js app with Better Auth Location: Guides > Authentication > Better Auth > Better Auth (with Next.js) > [!NOTE] > This guide uses Prisma ORM 7 > > The commands and code on this page target Prisma ORM 7, which remains fully supported. To start a new Prisma ORM 8 project, see [Create a new app with PostgreSQL](https://www.prisma.io/docs/prisma-orm/quickstart/postgresql); to add Prisma ORM 8 to an existing app, see [Add Prisma ORM to an existing PostgreSQL database](https://www.prisma.io/docs/prisma-orm/add-to-existing-project/postgresql). A Prisma ORM 8 version of this guide is not available yet: Better Auth's `prismaAdapter` requires Prisma Client, which Prisma ORM 8 replaces with the `@prisma/orm-postgres` runtime. ## Introduction [#introduction] [Better Auth](https://better-auth.com/) is an open-source authentication library for web applications. It's written in TypeScript, can be extended with plugins, and supports multiple database adapters, including Prisma. In this guide, you'll wire Better Auth into a brand-new [Next.js](https://nextjs.org/) app and persist users in a [Prisma Postgres](https://prisma.io/postgres) database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/betterauth-nextjs). ## Prerequisites [#prerequisites] * [Node.js 22.12+ on 22.x or 24+](https://nodejs.org) * Basic familiarity with Next.js App Router and Prisma ## 1. Set up your project [#1-set-up-your-project] Create a new Next.js application: #### bun ```bash bunx create-next-app@latest betterauth-nextjs-prisma ``` #### pnpm ```bash pnpm dlx create-next-app@latest betterauth-nextjs-prisma ``` #### yarn ```bash yarn dlx create-next-app@latest betterauth-nextjs-prisma ``` #### npm ```bash npx create-next-app@latest betterauth-nextjs-prisma ``` It will prompt you to customize your setup. Choose the defaults: > [!NOTE] > * *Would you like to use TypeScript?* `Yes` > * *Would you like to use ESLint?* `Yes` > * *Would you like to use Tailwind CSS?* `Yes` > * *Would you like your code inside a `src/` directory?* `Yes` > * *Would you like to use App Router?* `Yes` > * *Would you like to use Turbopack?* `Yes` > * _Would you like to customize the import alias (`@/_`by default)?\*`No` Navigate to the project directory: ```bash cd betterauth-nextjs-prisma ``` These selections create a Next.js project with TypeScript for type safety, ESLint for code quality, and Tailwind CSS for styling. Using the `src/` directory and the App Router are common conventions for new Next.js applications. ## 2. Set up Prisma [#2-set-up-prisma] Next, you'll add Prisma to your project to manage your database. ### 2.1. Install Prisma and dependencies [#21-install-prisma-and-dependencies] Install the necessary Prisma packages. The dependencies differ slightly depending on whether you use Prisma Postgres with Accelerate or another database. #### bun ```bash bun add prisma@prev tsx @types/pg --dev ``` #### pnpm ```bash pnpm add prisma@prev tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma@prev tsx @types/pg --dev ``` #### npm ```bash npm install prisma@prev tsx @types/pg --save-dev ``` #### bun ```bash bun add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### npm ```bash npm install @prisma/client@7 @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/database-drivers). Once installed, initialize Prisma in your project: #### bun ```bash bunx --bun prisma init --output ../src/generated/prisma ``` #### pnpm ```bash pnpm prisma init --output ../src/generated/prisma ``` #### yarn ```bash yarn prisma init --output ../src/generated/prisma ``` #### npm ```bash npx prisma init --output ../src/generated/prisma ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, you will create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This will create: * A `prisma` directory with a `schema.prisma` file * A `.env` file containing a local `DATABASE_URL` at the project root * An `output` directory for the generated Prisma Client as `better-auth/generated/prisma` Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### bun ```bash bunx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### npm ```bash npx create-db ``` ### 2.2. Configure Prisma [#22-configure-prisma] Create a `prisma.config.ts` file in the root of your project with the following content: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > The `dotenv` package should already be installed as it's a Next.js dependency. If not, install it using: > > > > > #### bun > ```bash > bun add dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### npm > ```bash > npm install dotenv > ``` > > ### 2.3. Generate the Prisma client [#23-generate-the-prisma-client] Run the following command to create the database tables and generate the Prisma Client: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ### 2.4. Set up a global Prisma client [#24-set-up-a-global-prisma-client] In the `src` directory, create a `lib` folder and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. ```bash mkdir -p src/lib touch src/lib/prisma.ts ``` Set up the Prisma client like this: ```tsx title="src/lib/prisma.ts" import { PrismaClient } from "@/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; ``` > [!WARNING] > We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently. > > If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections. ## 3. Set up Better Auth [#3-set-up-better-auth] Next, add Better Auth to handle sign-up, sign-in, and sessions. ### 3.1. Install and configure Better Auth [#31-install-and-configure-better-auth] First, install the Better Auth core package: #### bun ```bash bun add better-auth ``` #### pnpm ```bash pnpm add better-auth ``` #### yarn ```bash yarn add better-auth ``` #### npm ```bash npm install better-auth ``` Next, generate a secure secret that Better Auth will use to sign authentication tokens. This ensures your tokens cannot be messed with. #### bun ```bash bunx auth@latest secret ``` #### pnpm ```bash pnpm dlx auth@latest secret ``` #### yarn ```bash yarn dlx auth@latest secret ``` #### npm ```bash npx auth@latest secret ``` Copy the generated secret and add it, along with your application's URL, to your `.env` file: ```bash title=".env" # Better Auth BETTER_AUTH_SECRET=your-generated-secret # [!code ++] BETTER_AUTH_URL=http://localhost:3000 # [!code ++] # Prisma DATABASE_URL="your-database-url" ``` Now, create a configuration file for Better Auth. In the `src/lib` directory, create an `auth.ts` file: ```bash touch src/lib/auth.ts ``` In this file, you'll configure Better Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication. ```ts title="src/lib/auth.ts" import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import prisma from "@/lib/prisma"; export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql", }), }); ``` Better Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [email and password documentation](https://www.better-auth.com/docs/authentication/email-password). ```ts title="src/lib/auth.ts" import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import prisma from "@/lib/prisma"; export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql", }), emailAndPassword: { // [!code ++] enabled: true, // [!code ++] }, // [!code ++] }); ``` > [!NOTE] > If your application runs on a port other than `3000`, you must add it to the `trustedOrigins` in your `auth.ts` configuration to avoid CORS errors during authentication requests. > > ```ts title="src/lib/auth.ts" > import { betterAuth } from "better-auth"; > import { prismaAdapter } from "better-auth/adapters/prisma"; > import prisma from "@/lib/prisma"; > > export const auth = betterAuth({ > database: prismaAdapter(prisma, { > provider: "postgresql", > }), > emailAndPassword: { > enabled: true, > }, > trustedOrigins: ["http://localhost:3001"], // [!code ++] > }); > ``` ### 3.2. Add Better Auth models to your schema [#32-add-better-auth-models-to-your-schema] Better Auth provides a CLI command to automatically add the necessary authentication models (`User`, `Session`, `Account`, and `Verification`) to your `schema.prisma` file. Run the following command: #### bun ```bash bunx auth generate ``` #### pnpm ```bash pnpm dlx auth generate ``` #### yarn ```bash yarn dlx auth generate ``` #### npm ```bash npx auth generate ``` > [!NOTE] > It will ask for confirmation to overwrite your existing Prisma schema. Select `y`. This will add the following models: ```prisma model User { id String @id name String email String emailVerified Boolean image String? createdAt DateTime updatedAt DateTime sessions Session[] accounts Account[] @@unique([email]) @@map("user") } model Session { id String @id expiresAt DateTime token String createdAt DateTime updatedAt DateTime ipAddress String? userAgent String? userId String user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([token]) @@map("session") } model Account { id String @id accountId String providerId String userId String user User @relation(fields: [userId], references: [id], onDelete: Cascade) accessToken String? refreshToken String? idToken String? accessTokenExpiresAt DateTime? refreshTokenExpiresAt DateTime? scope String? password String? createdAt DateTime updatedAt DateTime @@map("account") } model Verification { id String @id identifier String value String expiresAt DateTime createdAt DateTime? updatedAt DateTime? @@map("verification") } ``` ### 3.3. Migrate the database [#33-migrate-the-database] With the new models in your schema, you need to update your database. Run a migration to create the corresponding tables: #### bun ```bash bunx prisma migrate dev --name add-auth-models ``` #### pnpm ```bash pnpm prisma migrate dev --name add-auth-models ``` #### yarn ```bash yarn prisma migrate dev --name add-auth-models ``` #### npm ```bash npx prisma migrate dev --name add-auth-models ``` #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ## 4. Set up the API routes [#4-set-up-the-api-routes] Better Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Next.js to handle all requests sent to `/api/auth/[...all]`. In the `src/app/api` directory, create an `auth/[...all]` folder structure and a `route.ts` file inside it: ```bash mkdir -p "src/app/api/auth/[...all]" touch "src/app/api/auth/[...all]/route.ts" ``` Add the following code to the newly created `route.ts` file. This code uses a helper from Better Auth to create Next.js-compatible `GET` and `POST` request handlers. ```ts import { auth } from "@/lib/auth"; import { toNextJsHandler } from "better-auth/next-js"; export const { POST, GET } = toNextJsHandler(auth); ``` Next, you'll need a client-side utility to interact with these endpoints from your React components. In the `src/lib` directory, create an `auth-client.ts` file: ```bash touch src/lib/auth-client.ts ``` Add the following code, which creates the React hooks and functions you'll use in your UI: ```ts import { createAuthClient } from "better-auth/react"; export const { signIn, signUp, signOut, useSession } = createAuthClient(); ``` ## 5. Set up your pages [#5-set-up-your-pages] Next, build the user interface for authentication. In the `src/app` directory, create the following folder structure: * `sign-up/page.tsx` * `sign-in/page.tsx` * `dashboard/page.tsx` ```bash mkdir -p src/app/{sign-up,sign-in,dashboard} touch src/app/{sign-up,sign-in,dashboard}/page.tsx ``` ### 5.1. Sign up page [#51-sign-up-page] First, create the basic `SignUpPage` component in `src/app/sign-up/page.tsx`. This sets up the main container and a title for your page. ```tsx title="src/app/sign-up/page.tsx" "use client"; export default function SignUpPage() { return (

Sign Up

); } ``` Next, import the necessary hooks from React and Next.js to manage state and navigation. Initialize the router and a state variable to hold any potential error messages. ```tsx title="src/app/sign-up/page.tsx" "use client"; import { useState } from "react"; // [!code ++] import { useRouter } from "next/navigation"; // [!code ++] export default function SignUpPage() { const router = useRouter(); // [!code ++] const [error, setError] = useState(null); // [!code ++] return (

Sign Up

); } ``` Now, import the `signUp` function from your Better Auth client and add the `handleSubmit` function. This function is triggered on form submission and calls the `signUp.email` method provided by Better Auth, passing the user's name, email, and password. ```tsx title="src/app/sign-up/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; //add-next-lin import { signUp } from "@/lib/auth-client"; export default function SignUpPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { // [!code ++] e.preventDefault(); // [!code ++] setError(null); // [!code ++] // [!code ++] const formData = new FormData(e.currentTarget); // [!code ++] // [!code ++] const res = await signUp.email({ // [!code ++] name: formData.get("name") as string, // [!code ++] email: formData.get("email") as string, // [!code ++] password: formData.get("password") as string, // [!code ++] }); // [!code ++] // [!code ++] if (res.error) { // [!code ++] setError(res.error.message || "Something went wrong."); // [!code ++] } else { // [!code ++] router.push("/dashboard"); // [!code ++] } // [!code ++] } // [!code ++] return (

Sign Up

); } ``` To inform the user of any issues, add an element that conditionally renders when the `error` state is not null. ```tsx title="src/app/sign-up/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signUp } from "@/lib/auth-client"; export default function SignUpPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); const formData = new FormData(e.currentTarget); const res = await signUp.email({ name: formData.get("name") as string, email: formData.get("email") as string, password: formData.get("password") as string, }); if (res.error) { setError(res.error.message || "Something went wrong."); } else { router.push("/dashboard"); } } return (

Sign Up

{error &&

{error}

} // [!code ++]
); } ``` Finally, add the HTML form with input fields for the user's name, email, and password, and a submit button. ```tsx title="src/app/sign-up/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signUp } from "@/lib/auth-client"; export default function SignUpPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); const formData = new FormData(e.currentTarget); const res = await signUp.email({ name: formData.get("name") as string, email: formData.get("email") as string, password: formData.get("password") as string, }); if (res.error) { setError(res.error.message || "Something went wrong."); } else { router.push("/dashboard"); } } return (

Sign Up

{error &&

{error}

}
{" "} // [!code ++] {" "} // [!code ++] {" "} // [!code ++] {" "} // [!code ++] {" "} // [!code ++]
{" "} // [!code ++]
); } ``` ### 5.2. Sign in page [#52-sign-in-page] For the sign-in page, start with the basic structure in `src/app/sign-in/page.tsx`. ```tsx title="src/app/sign-in/page.tsx" "use client"; export default function SignInPage() { return (

Sign In

); } ``` Now, add the state and router hooks, similar to the sign-up page. ```tsx title="src/app/sign-in/page.tsx" "use client"; import { useState } from "react"; // [!code ++] import { useRouter } from "next/navigation"; // [!code ++] export default function SignInPage() { const router = useRouter(); // [!code ++] const [error, setError] = useState(null); // [!code ++] return (

Sign In

); } ``` Add the `handleSubmit` function, this time importing and using the `signIn.email` method from Better Auth. ```tsx title="src/app/sign-in/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signIn } from "@/lib/auth-client"; // [!code ++] export default function SignInPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { // [!code ++] e.preventDefault(); // [!code ++] setError(null); // [!code ++] // [!code ++] const formData = new FormData(e.currentTarget); // [!code ++] // [!code ++] const res = await signIn.email({ // [!code ++] email: formData.get("email") as string, // [!code ++] password: formData.get("password") as string, // [!code ++] }); // [!code ++] // [!code ++] if (res.error) { // [!code ++] setError(res.error.message || "Something went wrong."); // [!code ++] } else { // [!code ++] router.push("/dashboard"); // [!code ++] } // [!code ++] } // [!code ++] return (

Sign In

); } ``` Add the conditional error message display. ```tsx title="src/app/sign-in/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signIn } from "@/lib/auth-client"; export default function SignInPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); const formData = new FormData(e.currentTarget); const res = await signIn.email({ email: formData.get("email") as string, password: formData.get("password") as string, }); if (res.error) { setError(res.error.message || "Something went wrong."); } else { router.push("/dashboard"); } } return (

Sign In

{error &&

{error}

} // [!code ++]
); } ``` Finally, add the form fields for email and password and a sign-in button. ```tsx title="src/app/sign-in/page.tsx" "use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signIn } from "@/lib/auth-client"; export default function SignInPage() { const router = useRouter(); const [error, setError] = useState(null); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); const formData = new FormData(e.currentTarget); const res = await signIn.email({ email: formData.get("email") as string, password: formData.get("password") as string, }); if (res.error) { setError(res.error.message || "Something went wrong."); } else { router.push("/dashboard"); } } return (

Sign In

{error &&

{error}

}
{" "} // [!code ++] {" "} // [!code ++] {" "} // [!code ++] {" "} // [!code ++]
{" "} // [!code ++]
); } ``` ### 5.3. Dashboard page [#53-dashboard-page] This is the protected page for authenticated users. Start with the basic component in `src/app/dashboard/page.tsx`. ```tsx title="src/app/dashboard/page.tsx" "use client"; export default function DashboardPage() { return (

Dashboard

); } ``` Import the `useSession` hook from your Better Auth client. This hook is the key to managing authentication state on the client side. It provides the session data and a pending status. ```tsx title="src/app/dashboard/page.tsx" "use client"; import { useRouter } from "next/navigation"; // [!code ++] import { useSession } from "@/lib/auth-client"; // [!code ++] export default function DashboardPage() { const router = useRouter(); // [!code ++] const { data: session, isPending } = useSession(); // [!code ++] return (

Dashboard

); } ``` To protect this route, use a `useEffect` hook. This effect checks if the session has loaded (`!isPending`) and if there is no authenticated user (`!session?.user`). If both are true, it redirects the user to the sign-in page. ```tsx title="src/app/dashboard/page.tsx" "use client"; import { useRouter } from "next/navigation"; import { useSession } from "@/lib/auth-client"; import { useEffect } from "react"; // [!code ++] export default function DashboardPage() { const router = useRouter(); const { data: session, isPending } = useSession(); useEffect(() => { // [!code ++] if (!isPending && !session?.user) { // [!code ++] router.push("/sign-in"); // [!code ++] } // [!code ++] }, [isPending, session, router]); // [!code ++] return (

Dashboard

); } ``` Add loading and redirecting states so the page does not flash an empty dashboard while the session is being verified. ```tsx title="src/app/dashboard/page.tsx" "use client"; import { useRouter } from "next/navigation"; import { useSession } from "@/lib/auth-client"; import { useEffect } from "react"; export default function DashboardPage() { const router = useRouter(); const { data: session, isPending } = useSession(); useEffect(() => { if (!isPending && !session?.user) { router.push("/sign-in"); } }, [isPending, session, router]); if (isPending) // [!code ++] return

Loading...

; // [!code ++] if (!session?.user) // [!code ++] return

Redirecting...

; // [!code ++] return (

Dashboard

); } ``` Finally, if the user is authenticated, display their name and email from the `session` object. Also, import the `signOut` function and add a button that calls it, allowing the user to log out. ```tsx title="src/app/dashboard/page.tsx" "use client"; import { useRouter } from "next/navigation"; import { useSession, signOut } from "@/lib/auth-client"; import { useEffect } from "react"; export default function DashboardPage() { const router = useRouter(); const { data: session, isPending } = useSession(); useEffect(() => { if (!isPending && !session?.user) { router.push("/sign-in"); } }, [isPending, session, router]); if (isPending) return

Loading...

; if (!session?.user) return

Redirecting...

; const { user } = session; // [!code ++] return (

Dashboard

Welcome, {user.name || "User"}!

Email: {user.email}

{/* [!code ++] */}
); } ``` ### 5.4. Home page [#54-home-page] Finally, update the home page to link to the sign-in and sign-up pages. Replace the contents of `src/app/page.tsx` with the following: ```tsx title="src/app/page.tsx" "use client"; import { useRouter } from "next/navigation"; export default function Home() { const router = useRouter(); return (
); } ``` ## 6. Test it out [#6-test-it-out] Your application is now fully configured. 1. Start the development server to test it: #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm run dev ``` 2. Navigate to `http://localhost:3000` in your browser. You should see the home page with "Sign Up" and "Sign In" buttons. 3. Click on **Sign Up**, create a new account, and you should be redirected to the dashboard. You can then sign out and sign back in. 4. To view the user data directly in your database, you can use Prisma Studio. #### bun ```bash bunx prisma studio ``` #### pnpm ```bash pnpm prisma studio ``` #### yarn ```bash yarn prisma studio ``` #### npm ```bash npx prisma studio ``` 5. This will open a new tab in your browser where you can see the `User`, `Session`, and `Account` tables and their contents. > [!TIP] > You now have a working authentication system built with Better Auth, Prisma, and Next.js. ## Next steps [#next-steps] * Add support for social login or magic links * Implement password reset and email verification * Add user profile and account management pages * Deploy to Vercel and secure your environment variables * Extend your Prisma schema with custom application models ## Further reading [#further-reading] * [Better Auth documentation](https://www.better-auth.com/docs) * [Prisma documentation](https://www.prisma.io/docs/orm/v7) * [Next.js App Router](https://nextjs.org/docs/app) ## Related pages - [`Better Auth (with Astro)`](https://www.prisma.io/docs/guides/authentication/better-auth/astro): Learn how to use Prisma ORM in an Astro app with Better Auth # Expand-and-contract migrations (Prisma ORM v7) (/docs/guides/v7/database/data-migration) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Learn how to perform data migrations using the expand and contract pattern with Prisma ORM Location: Guides > v7 > Database > Expand-and-contract migrations ## Introduction [#introduction] When you change your database schema in production, you need to keep the data consistent and avoid downtime. This guide shows you how to use the expand and contract pattern to safely migrate data between columns. The example replaces a boolean field with an enum field while preserving existing data. ## Prerequisites [#prerequisites] Before starting this guide, make sure you have: * Node.js installed (version 20 or higher) * A Prisma ORM project with an existing schema * A supported database (PostgreSQL, MySQL, SQLite, SQL Server, etc.) * Access to both development and production databases * Basic understanding of Git branching * Basic familiarity with TypeScript ## 1. Set up your environment [#1-set-up-your-environment] ### 1.1. Review initial schema [#11-review-initial-schema] Start with a basic schema containing a Post model: ```prisma generator client { provider = "prisma-client" output = "./generated/prisma" } datasource db { provider = "postgresql" } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) } ``` ### 1.2. Configure Prisma [#12-configure-prisma] Create a `prisma.config.ts` file in the root of your project with the following content: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > You'll need to install the required packages. If you haven't already, install them using your package manager: > > > > > #### bun > ```bash > bun add prisma@prev tsx @types/pg --dev > ``` > > > #### pnpm > ```bash > pnpm add prisma@prev tsx @types/pg --save-dev > ``` > > > #### yarn > ```bash > yarn add prisma@prev tsx @types/pg --dev > ``` > > > #### npm > ```bash > npm install prisma@prev tsx @types/pg --save-dev > ``` > > > > > > > #### bun > ```bash > bun add @prisma/client@7 @prisma/adapter-pg pg dotenv > ``` > > > #### pnpm > ```bash > pnpm add @prisma/client@7 @prisma/adapter-pg pg dotenv > ``` > > > #### yarn > ```bash > yarn add @prisma/client@7 @prisma/adapter-pg pg dotenv > ``` > > > #### npm > ```bash > npm install @prisma/client@7 @prisma/adapter-pg pg dotenv > ``` > > > > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/database-drivers). ### 1.3. Create a development branch [#13-create-a-development-branch] Create a new branch for your changes: ```bash git checkout -b create-status-field ``` ## 2. Expand the schema [#2-expand-the-schema] ### 2.1. Add new column [#21-add-new-column] Update your schema to add the new Status enum and field: ```prisma model Post { id Int @id @default(autoincrement()) title String content String? published Boolean? @default(false) status Status @default(Unknown) } enum Status { Unknown Draft InProgress InReview Published } ``` ### 2.2. Create migration [#22-create-migration] Generate the migration: #### bun ```bash bunx prisma migrate dev --name add-status-column ``` #### pnpm ```bash pnpm prisma migrate dev --name add-status-column ``` #### yarn ```bash yarn prisma migrate dev --name add-status-column ``` #### npm ```bash npx prisma migrate dev --name add-status-column ``` Then generate Prisma Client: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ## 3. Migrate the data [#3-migrate-the-data] ### 3.1. Create migration script [#31-create-migration-script] Create a new TypeScript file for the data migration: ```typescript import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import "dotenv/config"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); const prisma = new PrismaClient({ adapter, }); async function main() { await prisma.$transaction(async (tx) => { const posts = await tx.post.findMany(); for (const post of posts) { await tx.post.update({ where: { id: post.id }, data: { status: post.published ? "Published" : "Unknown", }, }); } }); } main() .catch(async (e) => { console.error(e); process.exit(1); }) .finally(async () => await prisma.$disconnect()); ``` ### 3.2. Set up migration script [#32-set-up-migration-script] Add the migration script to your package.json: ```json { "scripts": { "data-migration:add-status-column": "tsx ./prisma/migrations//data-migration.ts" } } ``` ### 3.3. Execute migration [#33-execute-migration] 1. Update your DATABASE_URL to point to the production database 2. Run the migration script: #### bun ```bash bun run data-migration:add-status-column ``` #### pnpm ```bash pnpm run data-migration:add-status-column ``` #### yarn ```bash yarn data-migration:add-status-column ``` #### npm ```bash npm run data-migration:add-status-column ``` ## 4. Contract the schema [#4-contract-the-schema] ### 4.1. Create cleanup branch [#41-create-cleanup-branch] Create a new branch for removing the old column: ```bash git checkout -b drop-published-column ``` ### 4.2. Remove old column [#42-remove-old-column] Update your schema to remove the published field: ```prisma model Post { id Int @id @default(autoincrement()) title String content String? status Status @default(Draft) } enum Status { Draft InProgress InReview Published } ``` ### 4.3. Generate cleanup migration [#43-generate-cleanup-migration] Create and run the final migration: #### bun ```bash bunx prisma migrate dev --name drop-published-column ``` #### pnpm ```bash pnpm prisma migrate dev --name drop-published-column ``` #### yarn ```bash yarn prisma migrate dev --name drop-published-column ``` #### npm ```bash npx prisma migrate dev --name drop-published-column ``` Then generate Prisma Client: #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ## 5. Deploy to production [#5-deploy-to-production] ### 5.1. Set up deployment [#51-set-up-deployment] Add the following command to your CI/CD pipeline: #### bun ```bash bunx prisma migrate deploy ``` #### pnpm ```bash pnpm prisma migrate deploy ``` #### yarn ```bash yarn prisma migrate deploy ``` #### npm ```bash npx prisma migrate deploy ``` ### 5.2. Monitor deployment [#52-monitor-deployment] Watch for any errors in your logs and monitor your application's behavior after deployment. ## Troubleshooting [#troubleshooting] ### Common issues and solutions [#common-issues-and-solutions] 1. **Migration fails due to missing default** * Ensure you've added a proper default value * Check that all existing records can be migrated 2. **Data loss prevention** * Always backup your database before running migrations * Test migrations on a copy of production data first 3. **Transaction rollback** * If the data migration fails, the transaction will automatically rollback * Fix any errors and retry the migration ## Next steps [#next-steps] Now that you've completed your first expand and contract migration, you can: * Learn more about [Prisma Migrate](https://www.prisma.io/docs/orm/v7/prisma-migrate) * Explore [schema prototyping](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/prototyping-your-schema) * Understand [customizing migrations](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/customizing-migrations) For more information: * [Expand and Contract Pattern Documentation](https://www.prisma.io/dataguide/types/relational/expand-and-contract-pattern) * [Prisma Migrate Workflows](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/development-and-production) ## Related pages - [`Multiple databases`](https://www.prisma.io/docs/guides/v7/database/multiple-databases): Learn how to use multiple Prisma Clients in a single app to connect to multiple databases, handle migrations, and deploy your application to Vercel - [`Schema management in teams`](https://www.prisma.io/docs/guides/v7/database/schema-changes): Learn how to use Prisma Migrate effectively when collaborating on a project as a team # Multiple databases (Prisma ORM v7) (/docs/guides/v7/database/multiple-databases) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Learn how to use multiple Prisma Clients in a single app to connect to multiple databases, handle migrations, and deploy your application to Vercel Location: Guides > v7 > Database > Multiple databases ## Introduction [#introduction] This guide shows you how to use multiple databases using Prisma ORM in a single [Next.js app](https://nextjs.org/). You will learn how to connect to two different Prisma Postgres databases, manage migrations, and deploy your application to Vercel. This approach is useful for multi-tenant applications or when you need to separate concerns when managing connections to multiple databases. ## Prerequisites [#prerequisites] Before you begin, make sure that you have the following: * Node.js 20.19+ on 20.x, 22.12+ on 22.x, or 24+ installed. * A [Prisma Data Platform account](https://pris.ly/pdp?utm_campaign=multi-client\&utm_source=docs). * A Vercel account (if you plan to deploy your application). ## 1. Set up a Next.js project [#1-set-up-a-nextjs-project] Create a new Next.js app using `create-next-app` from your desired directory: #### bun ```bash bunx create-next-app@latest my-multi-client-app ``` #### pnpm ```bash pnpm dlx create-next-app@latest my-multi-client-app ``` #### yarn ```bash yarn dlx create-next-app@latest my-multi-client-app ``` #### npm ```bash npx create-next-app@latest my-multi-client-app ``` You will be prompted to answer a few questions about your project. Select all of the defaults. > [!NOTE] > For completeness, those are: > > * TypeScript > * ESLint > * Tailwind CSS > * No `src` directory > * App Router > * Turbopack > * Default custom import alias: `@/*` Then, navigate to the project directory: ```bash cd my-multi-client-app ``` ## 2. Set up your databases and Prisma Clients [#2-set-up-your-databases-and-prisma-clients] In this section, you will create two separate Prisma Postgres instances, one for user data and one for post data. You will also configure the Prisma schema and environment variables for each. First, install Prisma and the required dependencies: #### bun ```bash bun add prisma@prev tsx @types/pg --dev ``` #### pnpm ```bash pnpm add prisma@prev tsx @types/pg --save-dev ``` #### yarn ```bash yarn add prisma@prev tsx @types/pg --dev ``` #### npm ```bash npm install prisma@prev tsx @types/pg --save-dev ``` #### bun ```bash bun add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### pnpm ```bash pnpm add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### yarn ```bash yarn add @prisma/client@7 @prisma/adapter-pg dotenv pg ``` #### npm ```bash npm install @prisma/client@7 @prisma/adapter-pg dotenv pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/database-drivers). You have installed the required dependencies for the project. ### 2.1. Create a Prisma Postgres instance to contain user data [#21-create-a-prisma-postgres-instance-to-contain-user-data] Initialize Prisma with a [Prisma Postgres](https://www.prisma.io/docs/postgres) instance by running: #### bun ```bash bunx --bun prisma@prev init --db ``` #### pnpm ```bash pnpm dlx prisma@prev init --db ``` #### yarn ```bash yarn dlx prisma@prev init --db ``` #### npm ```bash npx prisma@prev init --db ``` > [!NOTE] > If you are not using a Prisma Postgres database, do not use the `--db` flag. Instead, create two PostgreSQL database instances and add their connection URLs to the `.env` file as `PPG_USER_DATABASE_URL` and `PPG_POST_DATABASE_URL`. Follow the prompts to name your project and choose a database region. The `prisma@prev init --db` command: * Connects your CLI to your [Prisma Data Platform](https://console.prisma.io/?utm_source=docs\&utm_medium=content\&utm_content=guides) account. If you are not logged in or do not have an account, your browser will open to guide you through creating a new account or signing into your existing one. * Creates a `prisma` directory containing a `schema.prisma` file for your database models. * Creates a `.env` file with your `DATABASE_URL` (e.g., `DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require"`). Rename the `prisma` folder to `prisma-user-database`: ```bash mv prisma prisma-user-database ``` Edit your `.env` file to rename `DATABASE_URL` to `PPG_USER_DATABASE_URL`: ```bash title=".env" DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code --] PPG_USER_DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code ++] ``` Open `prisma-user-database/schema.prisma` file and update it to define a `User` model. Also, set the environment variable and specify a [custom `output` directory](https://www.prisma.io/docs/orm/v7/reference/prisma-schema-reference#fields-for-prisma-client-provider) for the generated Prisma Client: ```prisma title="prisma-user-database/schema.prisma" generator client { provider = "prisma-client" output = "../prisma-user-database/user-database-client-types" // [!code ++] } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` Create a `prisma.config.ts` file for the user database: ```typescript title="prisma-user-database/prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; // [!code ++] // [!code ++] export default defineConfig({ // [!code ++] schema: "prisma-user-database/schema.prisma", // [!code ++] migrations: { // [!code ++] path: "prisma-user-database/migrations", // [!code ++] }, // [!code ++] datasource: { // [!code ++] url: env("PPG_USER_DATABASE_URL"), // [!code ++] }, // [!code ++] }); // [!code ++] ``` > [!NOTE] > You'll need to install the `dotenv` package if you haven't already: > > > > > #### bun > ```bash > bun add dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### npm > ```bash > npm install dotenv > ``` > > Your user database schema is now ready. ### 2.2. Create a Prisma Postgres instance for post data [#22-create-a-prisma-postgres-instance-for-post-data] Repeat the initialization for the post database: #### bun ```bash bunx --bun prisma init bunx create-db ``` #### pnpm ```bash pnpm prisma init pnpm dlx create-db ``` #### yarn ```bash yarn prisma init yarn dlx create-db ``` #### npm ```bash npx prisma init npx create-db ``` Replace the generated `DATABASE_URL` in your `.env` file with the value from `npx create-db`, then rename the new `prisma` folder to `prisma-post-database`: ```bash mv prisma prisma-post-database ``` Rename the `DATABASE_URL` variable in `.env` to `PPG_POST_DATABASE_URL`: ```bash title=".env" DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code --] PPG_POST_DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require" # [!code ++] ``` Edit the `prisma-post-database/schema.prisma` file to define a `Post` model. Also, update the datasource URL and set a [custom `output` directory](https://www.prisma.io/docs/orm/v7/reference/prisma-schema-reference#fields-for-prisma-client-provider): ```prisma title="prisma-post-database/schema.prisma" generator client { provider = "prisma-client" output = "../prisma-post-database/post-database-client-types" // [!code ++] } datasource db { provider = "postgresql" } model Post { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] title String // [!code ++] content String? // [!code ++] } // [!code ++] ``` Create a `prisma.config.ts` file for the post database: ```typescript title="prisma-post-database/prisma.config.ts" import "dotenv/config"; // [!code ++] import { defineConfig, env } from "prisma/config"; // [!code ++] // [!code ++] export default defineConfig({ // [!code ++] schema: "prisma-post-database/schema.prisma", // [!code ++] migrations: { // [!code ++] path: "prisma-post-database/migrations", // [!code ++] }, // [!code ++] datasource: { // [!code ++] url: env("PPG_POST_DATABASE_URL"), // [!code ++] }, // [!code ++] }); // [!code ++] ``` Your post database schema is now set. ### 2.3. Add helper scripts and migrate the schemas [#23-add-helper-scripts-and-migrate-the-schemas] So you don't have to pass `--schema` for each database on every command, add helper scripts to your `package.json` file that run Prisma commands for both databases: ```json title="package.json" "scripts": { "dev": "next dev --turbopack", "build": "next build", "start": "next start", "lint": "next lint", "postinstall": "npx prisma generate --config ./prisma-user-database/prisma.config.ts && npx prisma generate --config ./prisma-post-database/prisma.config.ts", // [!code ++] "generate": "npx prisma generate --config ./prisma-user-database/prisma.config.ts && npx prisma generate --config ./prisma-post-database/prisma.config.ts", // [!code ++] "migrate": "npx prisma migrate dev --config ./prisma-user-database/prisma.config.ts && npx prisma migrate dev --config ./prisma-post-database/prisma.config.ts", // [!code ++] "deploy": "npx prisma migrate deploy --config ./prisma-user-database/prisma.config.ts && npx prisma migrate deploy --config ./prisma-post-database/prisma.config.ts", // [!code ++] "studio": "npx prisma studio --config ./prisma-user-database/prisma.config.ts --port 5555 & npx prisma studio --config ./prisma-post-database/prisma.config.ts --port 5556" // [!code ++] } ``` Here is an explanation of the custom scripts: * `postinstall`: Runs immediately after installing dependencies to generate Prisma Clients for both the user and post databases using their respective schema files. * `generate`: Manually triggers the generation of Prisma Clients for both schemas, ensuring your client code reflects the latest models. * `migrate`: Applies pending migrations in development mode for both databases using [Prisma Migrate](https://www.prisma.io/docs/orm/v7/prisma-migrate), updating their schemas based on changes in your Prisma files. * `deploy`: Executes migrations in a production environment, synchronizing your live databases with your Prisma schemas. * `studio`: Opens Prisma Studio for both databases simultaneously on different ports (`5555` for the user database and `5556` for the post database) for visual data management. Run the migrations: #### bun ```bash bun run migrate ``` #### pnpm ```bash pnpm run migrate ``` #### yarn ```bash yarn migrate ``` #### npm ```bash npm run migrate ``` When prompted, name the migration for each database accordingly. ## 3. Prepare the application to use multiple Prisma Clients [#3-prepare-the-application-to-use-multiple-prisma-clients] Next, create a `lib` folder to store helper files for instantiating and exporting your Prisma Clients: ```bash mkdir -p lib && touch lib/user-prisma-client.ts lib/post-prisma-client.ts ``` ### 3.1. Instantiate and export the Prisma Client for the user database [#31-instantiate-and-export-the-prisma-client-for-the-user-database] In `lib/user-prisma-client.ts`, add the following code: ```ts title="lib/user-prisma-client.ts" import { PrismaClient } from "../prisma-user-database/user-database-client-types/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.PPG_USER_DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const getPrisma = () => new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] const globalForUserDBPrismaClient = global as unknown as { // [!code ++] userDBPrismaClient: ReturnType; // [!code ++] }; // [!code ++] // [!code ++] export const userDBPrismaClient = globalForUserDBPrismaClient.userDBPrismaClient || getPrisma(); // [!code ++] // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") // [!code ++] globalForUserDBPrismaClient.userDBPrismaClient = userDBPrismaClient; // [!code ++] ``` ### 3.2. Instantiate and export the Prisma Client for the post database [#32-instantiate-and-export-the-prisma-client-for-the-post-database] In `lib/post-prisma-client.ts`, add this code: ```ts title="lib/post-prisma-client.ts" import { PrismaClient } from "../prisma-post-database/post-database-client-types/client"; // [!code ++] import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] // [!code ++] const adapter = new PrismaPg({ // [!code ++] connectionString: process.env.PPG_POST_DATABASE_URL, // [!code ++] }); // [!code ++] // [!code ++] const getPrisma = () => new PrismaClient({ // [!code ++] adapter, // [!code ++] }); // [!code ++] // [!code ++] const globalForPostDBPrismaClient = global as unknown as { // [!code ++] postDBPrismaClient: ReturnType; // [!code ++] }; // [!code ++] // [!code ++] export const postDBPrismaClient = globalForPostDBPrismaClient.postDBPrismaClient || getPrisma(); // [!code ++] // [!code ++] // [!code ++] if (process.env.NODE_ENV !== "production") // [!code ++] globalForPostDBPrismaClient.postDBPrismaClient = postDBPrismaClient; // [!code ++] ``` ## 4. Integrate multiple Prisma Clients in your Next.js app [#4-integrate-multiple-prisma-clients-in-your-nextjs-app] Modify your application code to fetch data from both databases. Update the `app/page.tsx` file as follows: ```ts title="app/page.tsx" import { postDBPrismaClient } from "@/lib/post-prisma-client"; // [!code ++] import { userDBPrismaClient } from "@/lib/user-prisma-client"; // [!code ++] // [!code ++] export default async function Home() { // [!code ++] const user = await userDBPrismaClient.user.findFirst(); // [!code ++] const post = await postDBPrismaClient.post.findFirst(); // [!code ++] // [!code ++] return ( // [!code ++]
// [!code ++]
// [!code ++]
// [!code ++]

Multi-DB Showcase

// [!code ++]

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

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

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

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

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

// [!code ++]
 // [!code ++]
            {post ? JSON.stringify(post, null, 2) : "No post data available."} // [!code ++]
          
// [!code ++]
// [!code ++]
// [!code ++]
// [!code ++] ); // [!code ++] } // [!code ++] ``` ### 4.1. Populate your databases with data [#41-populate-your-databases-with-data] In a separate terminal window, open two instances of [Prisma Studio](https://www.prisma.io/docs/studio) to add data to your databases by running the script: #### bun ```bash bun run studio ``` #### pnpm ```bash pnpm run studio ``` #### yarn ```bash yarn studio ``` #### npm ```bash npm run studio ``` This will open up two browser windows, one in `http://localhost:5555` and one in `http://localhost:5556`. Navigate to those windows and add sample data to both databases. ### 4.2. Run the development server [#42-run-the-development-server] Before starting the development server, note that if you are using Next.js `v15.2.0`, do not use Turbopack as there is a known [issue](https://github.com/vercel/next.js/issues/76497). Remove Turbopack from your dev script by updating your `package.json`: ```json title="package.json" "scripts": { "dev": "next dev --turbopack", // [!code --] "dev": "next dev", // [!code ++] "build": "next build", "start": "next start", "lint": "next lint", "postinstall": "npx prisma generate --config ./prisma-user-database/prisma.config.ts && npx prisma generate --config ./prisma-post-database/prisma.config.ts", "generate": "npx prisma generate --config ./prisma-user-database/prisma.config.ts && npx prisma generate --config ./prisma-post-database/prisma.config.ts", "migrate": "npx prisma migrate dev --config ./prisma-user-database/prisma.config.ts && npx prisma migrate dev --config ./prisma-post-database/prisma.config.ts", "deploy": "npx prisma migrate deploy --config ./prisma-user-database/prisma.config.ts && npx prisma migrate deploy --config ./prisma-post-database/prisma.config.ts", "studio": "npx prisma studio --config ./prisma-user-database/prisma.config.ts --port 5555 & npx prisma studio --config ./prisma-post-database/prisma.config.ts --port 5556" } ``` In a separate terminal window, start the development server by running: #### bun ```bash bun run dev ``` #### pnpm ```bash pnpm run dev ``` #### yarn ```bash yarn dev ``` #### npm ```bash npm run dev ``` Navigate to `http://localhost:3000` to see your Next.js app display data from both databases: ![App displaying data by querying two separate database instances](https://www.prisma.io/img/guides/multi-client-app-demo.png) Congratulations, you have a Next.js app running with two Prisma Client instances querying different databases. ## 5. Deploy your Next.js app using multiple databases to Vercel [#5-deploy-your-nextjs-app-using-multiple-databases-to-vercel] Deploy your app by following these steps: 1. Ensure your project is version-controlled and pushed to a GitHub repository. If you do not have a repository yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository). Once the repository is ready, run the following commands: ```bash git add . git commit -m "Initial commit with Prisma Postgres integration" git branch -M main git remote add origin https://github.com//.git git push -u origin main ``` > [!NOTE] > Replace `` and `` with your GitHub username and the name of your repository. 2. Log in to [Vercel](https://vercel.com/) and navigate to your [Dashboard](https://vercel.com/docs/deployments). 3. Create a new project. Follow Vercel's [Import an existing project](https://vercel.com/docs/getting-started-with-vercel/import) guide, but stop at [step 3](https://vercel.com/docs/getting-started-with-vercel/import#optionally-configure-any-settings) where you will configure environment variables *before* clicking **Deploy**. 4. Configure the `DATABASE_URL` environment variable: 1. Expand the **Environment variables** section. 2. Add the `PPG_USER_DATABASE_URL` environment variable: * **Key**: `PPG_USER_DATABASE_URL` * **Value**: Paste your user database connection URL, e.g. by copying it from the `.env` file in your project. 3. Add the `PPG_POST_DATABASE_URL` environment variable: * **Key**: `PPG_POST_DATABASE_URL` * **Value**: Paste your post database connection URL, e.g. by copying it from the `.env` file in your project. > [!WARNING] > Do not deploy without setting the environment variables. Your deployment will fail if the application cannot connect to the databases. 5. Click the **Deploy** button. Vercel will build your project and deploy it to a live URL. Open the live URL provided by Vercel and verify that your application is working. Your application now runs on Vercel and uses two Prisma Clients to query two different databases. ## Next steps [#next-steps] In this guide, you learned how to use multiple databases using Prisma ORM in a single Next.js app by: * Setting up separate Prisma schemas for user and post databases. * Configuring custom output directories and environment variables. * Creating helper scripts to generate and migrate each schema. * Instantiating and integrating multiple Prisma Clients into your application. * Deploying your multi-database application to Vercel. This approach allows you to maintain a clear separation of data models and simplifies multi-tenant or multi-database scenarios. For further improvements in managing your project, consider using a monorepo setup. Check out our related guides: * [How to use Prisma ORM in a pnpm workspaces monorepo](https://www.prisma.io/docs/guides/v7/deployment/pnpm-workspaces) * [How to use Prisma ORM with Turborepo](https://www.prisma.io/docs/guides/v7/deployment/turborepo) ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/v7/database/data-migration): Learn how to perform data migrations using the expand and contract pattern with Prisma ORM - [`Schema management in teams`](https://www.prisma.io/docs/guides/v7/database/schema-changes): Learn how to use Prisma Migrate effectively when collaborating on a project as a team # Schema management in teams (Prisma ORM v7) (/docs/guides/v7/database/schema-changes) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Learn how to use Prisma Migrate effectively when collaborating on a project as a team Location: Guides > v7 > Database > Schema management in teams ## Introduction [#introduction] When working in a team, managing database schema changes can be challenging. This guide shows you how to effectively collaborate on schema changes using Prisma Migrate, ensuring that all team members can safely contribute to and incorporate schema changes. ## Prerequisites [#prerequisites] Before starting this guide, make sure you have: * Node.js installed (version 20 or higher) * A Prisma project set up with migrations * A relational database (PostgreSQL, MySQL, SQLite, SQL Server, etc.) * Basic understanding of Git * Basic familiarity with Prisma Migrate > [!WARNING] > This guide **does not apply for MongoDB**.
> Instead of `migrate dev`, [`db push`](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/prototyping-your-schema) is used for [MongoDB](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/mongodb). ## 1. Understand migration basics [#1-understand-migration-basics] ### 1.1. Migration order [#11-migration-order] Migrations are **applied in the same order as they were created**. The creation date is part of the migration subfolder name - for example, `20210316081837-updated-fields` was created on `2021-03-16-08:18:37`. ### 1.2. Source control requirements [#12-source-control-requirements] You should commit the following files to source control: * The contents of the `prisma/migrations` folder, including the `migration_lock.toml` file * The Prisma Schema (`schema.prisma`) Source-controlling the `schema.prisma` file is not enough - you must include your migration history because: * Customized migrations contain information that cannot be represented in the Prisma schema * The `prisma migrate deploy` command only runs migration files ### 1.3. Configure Prisma [#13-configure-prisma] Create a `prisma.config.ts` file in the root of your project with the following content: ```typescript title="prisma.config.ts" import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: env("DATABASE_URL"), }, }); ``` > [!NOTE] > You'll need to install the `dotenv` package to load environment variables. If you haven't already, install it using your package manager: > > > > > #### bun > ```bash > bun add dotenv > ``` > > > #### pnpm > ```bash > pnpm add dotenv > ``` > > > #### yarn > ```bash > yarn add dotenv > ``` > > > #### npm > ```bash > npm install dotenv > ``` > > ## 2. Incorporate team changes [#2-incorporate-team-changes] ### 2.1. Pull latest changes [#21-pull-latest-changes] To incorporate changes from collaborators: 1. Pull the changed Prisma schema and `./prisma/migrations` folder 2. Run the migrate command: #### bun ```bash bunx prisma migrate dev ``` #### pnpm ```bash pnpm prisma migrate dev ``` #### yarn ```bash yarn prisma migrate dev ``` #### npm ```bash npx prisma migrate dev ``` ### 2.2. Example scenario [#22-example-scenario] Consider a sample scenario with three developers sharing schema changes: #### Before ```prisma title="schema.prisma" model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } ``` #### After ```prisma title="schema.prisma" model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } model User { id Int @id @default(autoincrement()) email String @unique name String? favoriteColor String? // Added by Ania // [!code ++] bestPacmanScore Int? // Added by you // [!code ++] posts Post[] } // Added by Javier // [!code ++] model Tag { // [!code ++] tagName String @id // [!code ++] tagCategory Category // [!code ++] } // [!code ++] ``` ## 3. Handle concurrent changes [#3-handle-concurrent-changes] ### 3.1. Developer A's changes [#31-developer-as-changes] Ania adds a new field: ```prisma model User { /* ... */ favoriteColor String? } ``` And generates a migration: #### bun ```bash bunx prisma migrate dev --name new-field ``` #### pnpm ```bash pnpm prisma migrate dev --name new-field ``` #### yarn ```bash yarn prisma migrate dev --name new-field ``` #### npm ```bash npx prisma migrate dev --name new-field ``` #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ### 3.2. Developer B's changes [#32-developer-bs-changes] Javier adds a new model: ```prisma model Tag { tagName String @id tagCategory Category } ``` And generates a migration: #### bun ```bash bunx prisma migrate dev --name new-model ``` #### pnpm ```bash pnpm prisma migrate dev --name new-model ``` #### yarn ```bash yarn prisma migrate dev --name new-model ``` #### npm ```bash npx prisma migrate dev --name new-model ``` #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` ### 3.3. Merge changes [#33-merge-changes] The migration history now has two new migrations: ![A diagram showing changes by two separate developers converging in a single migration history.](https://www.prisma.io/img/guides/migrate-team-dev.png) ## 4. Integrate your changes [#4-integrate-your-changes] ### 4.1. Pull team changes [#41-pull-team-changes] 1. Pull the most recent changes: * Two new migrations * Updated schema file 2. Review the merged schema: ```prisma model User { /* ... */ favoriteColor String? bestPacmanScore Int? } model Tag { tagName String @id tagCategory Category posts Post[] } ``` ### 4.2. Generate your migration [#42-generate-your-migration] Run the migrate command: #### bun ```bash bunx prisma migrate dev ``` #### pnpm ```bash pnpm prisma migrate dev ``` #### yarn ```bash yarn prisma migrate dev ``` #### npm ```bash npx prisma migrate dev ``` #### bun ```bash bunx prisma generate ``` #### pnpm ```bash pnpm prisma generate ``` #### yarn ```bash yarn prisma generate ``` #### npm ```bash npx prisma generate ``` This will: 1. Apply your team's migrations 2. Create a new migration for your changes 3. Apply your new migration ### 4.3. Commit changes [#43-commit-changes] Commit: * The merged `schema.prisma` * Your new migration file ## Next steps [#next-steps] Now that you understand team schema management, you can: * Learn about [customizing migrations](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/customizing-migrations) * Explore [deployment workflows](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/development-and-production) For more information: * [Prisma Migrate documentation](https://www.prisma.io/docs/orm/v7/prisma-migrate) * [Team development workflows](https://www.prisma.io/docs/orm/v7/prisma-migrate/workflows/development-and-production) ## Related pages - [`Expand-and-contract migrations`](https://www.prisma.io/docs/guides/v7/database/data-migration): Learn how to perform data migrations using the expand and contract pattern with Prisma ORM - [`Multiple databases`](https://www.prisma.io/docs/guides/v7/database/multiple-databases): Learn how to use multiple Prisma Clients in a single app to connect to multiple databases, handle migrations, and deploy your application to Vercel # Bun workspaces (Prisma ORM v7) (/docs/guides/v7/deployment/bun-workspaces) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Learn step-by-step how to integrate Prisma ORM in a Bun workspaces monorepo through a shared database package Location: Guides > v7 > Deployment > Bun workspaces ## Introduction [#introduction] This guide shows you how to use Prisma ORM in a [Bun Workspaces](https://bun.sh/docs/install/workspaces) monorepo. You'll set up a shared database package with Prisma ORM, then integrate it into a Next.js app in the same workspace. ## Prerequisites [#prerequisites] * [Bun](https://bun.sh/docs/installation) installed * A [Prisma Postgres](https://www.prisma.io/docs/postgres) database (or another [supported database](https://www.prisma.io/docs/orm/v7/reference/supported-databases)) ## 1. Set up project [#1-set-up-project] Before integrating Prisma ORM, you need to set up your project structure. Start by creating a new directory for your project (for example, `my-monorepo`) and initialize a Node.js project: #### bun ```bash mkdir my-monorepo cd my-monorepo bun init ``` #### pnpm ```bash mkdir my-monorepo cd my-monorepo pnpm init ``` #### yarn ```bash mkdir my-monorepo cd my-monorepo yarn init ``` #### npm ```bash mkdir my-monorepo cd my-monorepo npm init ``` Next, add the `workspaces` array to your root `package.json` to define your workspace structure: ```json title="package.json" { "name": "my-monorepo", // [!code ++] "workspaces": ["apps/*", "packages/*"] // [!code ++] } ``` Finally, create directories for your applications and shared packages: ```bash mkdir apps mkdir -p packages/database ``` ## 2. Set up database package [#2-set-up-database-package] This section covers creating a standalone database package that uses Prisma ORM. The package will house all database models and the generated Prisma ORM client, making it reusable across your monorepo. ### 2.1. Install dependencies [#21-install-dependencies] Navigate to the `packages/database` directory and initialize a new package: #### bun ```bash cd packages/database bun init ``` #### pnpm ```bash cd packages/database pnpm init ``` #### yarn ```bash cd packages/database yarn init ``` #### npm ```bash cd packages/database npm init ``` Install the required Prisma ORM packages and other dependencies: #### bun ```bash bun add prisma@prev typescript tsx @types/node @types/pg --dev bun add @prisma/client@7 @prisma/adapter-pg pg ``` #### pnpm ```bash pnpm add prisma@prev typescript tsx @types/node @types/pg --save-dev pnpm add @prisma/client@7 @prisma/adapter-pg pg ``` #### yarn ```bash yarn add prisma@prev typescript tsx @types/node @types/pg --dev yarn add @prisma/client@7 @prisma/adapter-pg pg ``` #### npm ```bash npm install prisma@prev typescript tsx @types/node @types/pg --save-dev npm install @prisma/client@7 @prisma/adapter-pg pg ``` > [!NOTE] > If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/database-drivers). ### 2.2. Set up Prisma ORM and schema [#22-set-up-prisma-orm-and-schema] Initialize Prisma ORM with an instance of [Prisma Postgres](https://www.prisma.io/docs/postgres) in the `database` package by running the following command: #### bun ```bash bunx --bun prisma init ``` #### pnpm ```bash pnpm prisma init ``` #### yarn ```bash yarn prisma init ``` #### npm ```bash npx prisma init ``` > [!NOTE] > `prisma init` creates the Prisma scaffolding and a local `DATABASE_URL`. In the next step, create a Prisma Postgres database and replace that value with a direct `postgres://...` connection string. This command: * Creates a `prisma` directory containing a `schema.prisma` file for your database models. * Creates a `prisma.config.ts` file for configuring Prisma. * Creates a `.env` file with a local `DATABASE_URL`. Create a Prisma Postgres database and replace the generated `DATABASE_URL` in your `.env` file with the `postgres://...` connection string from the CLI output: #### bun ```bash bunx create-db ``` #### pnpm ```bash pnpm dlx create-db ``` #### yarn ```bash yarn dlx create-db ``` #### npm ```bash npx create-db ``` Edit the `schema.prisma` file to add a `User` model. The default generator already sets `output = "../generated/prisma"`: ```prisma title="prisma/schema.prisma" generator client { provider = "prisma-client" output = "../generated/prisma" } datasource db { provider = "postgresql" } model User { // [!code ++] id Int @id @default(autoincrement()) // [!code ++] email String @unique // [!code ++] name String? // [!code ++] } // [!code ++] ``` If the generated `prisma.config.ts` comments mention installing `dotenv`, install it so environment variables load: #### bun ```bash bun add dotenv ``` #### pnpm ```bash pnpm add dotenv ``` #### yarn ```bash yarn add dotenv ``` #### npm ```bash npm install dotenv ``` Add a `scripts` section to your database `package.json` (Bun init may not add one by default): ```json title="database/package.json" { "scripts": { // [!code ++] "db:generate": "prisma generate", // [!code ++] "db:migrate": "prisma migrate dev", // [!code ++] "db:deploy": "prisma migrate deploy", // [!code ++] "db:seed": "prisma db seed", // [!code ++] "db:studio": "prisma studio" // [!code ++] } // [!code ++] } ``` Use [Prisma Migrate](https://www.prisma.io/docs/orm/v7/prisma-migrate) to migrate your database changes: #### bun ```bash bun run db:migrate ``` #### pnpm ```bash pnpm run db:migrate ``` #### yarn ```bash yarn db:migrate ``` #### npm ```bash npm run db:migrate ``` When prompted by the CLI, enter a descriptive name for your migration. After the migration completes, run generate so the Prisma ORM client is created: #### bun ```bash bun run db:generate ``` #### pnpm ```bash pnpm run db:generate ``` #### yarn ```bash yarn db:generate ``` #### npm ```bash npm run db:generate ``` Create a `client.ts` file to initialize the Prisma ORM client with a driver adapter: ```ts title="database/client.ts" import { PrismaClient } from "./generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, }); // Use globalThis for broader environment compatibility const globalForPrisma = globalThis as typeof globalThis & { prisma?: PrismaClient; }; export const prisma: PrismaClient = globalForPrisma.prisma ?? new PrismaClient({ adapter, }); if (process.env.NODE_ENV !== "production") { globalForPrisma.prisma = prisma; } ``` Then, create an `index.ts` file to re-export the instance of the Prisma ORM client and all generated types: ```ts title="database/index.ts" export { prisma } from "./client"; export * from "./generated/prisma/client"; ``` ### 2.3. Seed the database [#23-seed-the-database] Add a seed script to populate the database with sample users. Create `prisma/seed.ts` in the database package: ```ts title="database/prisma/seed.ts" import "dotenv/config"; import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const prisma = new PrismaClient({ adapter }); async function main() { await prisma.user.createMany({ data: [ { email: "alice@example.com", name: "Alice" }, { email: "bob@example.com", name: "Bob" }, { email: "charlie@example.com", name: "Charlie" }, ], skipDuplicates: true, }); console.log("Seed complete."); } main() .catch((e) => { console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); }); ``` Add the `seed` option to the existing `migrations` config in your database package's `prisma.config.ts` (add the `seed` line inside `migrations`): ```ts title="database/prisma.config.ts" migrations: { path: "prisma/migrations", seed: "bun prisma/seed.ts", // [!code ++] }, ``` At this point, your shared database package is fully configured and ready for use across your monorepo. ### 2.4. Add root scripts [#24-add-root-scripts] Add the following scripts to the root `package.json` of your monorepo. They let you run database and app commands from the root: ```json title="package.json" "scripts": { // [!code ++] "build": "bun run --filter database db:deploy && bun run --filter database db:generate && bun run --filter web build", // [!code ++] "start": "bun run --filter web start", // [!code ++] "dev": "bun run --filter database db:generate && bun run --filter web dev", // [!code ++] "seed": "bun run --filter database db:seed", // [!code ++] "studio": "bun run --filter database db:studio" // [!code ++] } // [!code ++] ``` From the monorepo root, run `bun run seed` to add sample users. Run `bun run studio` to open [Prisma Studio](https://www.prisma.io/docs/studio) at [`http://localhost:5555`](http://localhost:5555) to view and edit your data. ## 3. Set up Next.js app [#3-set-up-nextjs-app] Now that the database package is set up, create a frontend application (using Next.js) that uses the shared Prisma ORM client to interact with your database. ### 3.1. Create Next.js app [#31-create-nextjs-app] Navigate to the `apps` directory: ```bash cd ../../apps ``` Create a new Next.js app named `web`: ```bash bun create next-app@latest web --yes ``` > [!NOTE] > important > > The `--yes` flag uses default configurations to bootstrap the Next.js app (which in this guide uses the app router without a `src/` directory). When prompted for a package manager, choose **Bun** so the app uses Bun within the workspace. > > The flag may also initialize a Git repository in the `web` folder. If that happens, please remove the `.git` directory by running `rm -r .git`. Then, navigate into the web directory: ```bash cd web/ ``` Copy the `.env` file from the database package to ensure the same environment variables are available: ```bash cp ../../packages/database/.env . ``` Open the `package.json` file of your Next.js app and add the shared `database` package as a dependency: ```json title="web/package.json" "dependencies": { "database": "workspace:*" // [!code ++] } ``` Run the following command to install the `database` package: #### bun ```bash bun install ``` #### pnpm ```bash pnpm install ``` #### yarn ```bash yarn install ``` #### npm ```bash npm install ``` ### 3.2. Add database to app [#32-add-database-to-app] Modify your Next.js application code to use the Prisma ORM client from the database package. Update `app/page.tsx` as follows: ```tsx title="app/page.tsx" import { prisma } from "database"; export default async function Home() { const user = await prisma.user.findFirst({ select: { name: true, }, }); return (
{user?.name &&

Hello from {user.name}

} {!user?.name &&

No user has been added to the database yet.

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

Hello from {user.name}

} {!user?.name &&

No user has been added to the database yet.

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

Astro + Prisma

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

    {user.name}

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

Superblog

  1. Alice
  2. Bob
); } ``` This gives you a basic page with a title and a list of users. However, that list is static with hardcoded values. Update the page to fetch the users from your database and make it dynamic. ```tsx title="app/page.tsx" import prisma from "@/lib/prisma"; export default async function Home() { const users = await prisma.user.findMany(); return (

Superblog

    {users.map((user) => (
  1. {user.name}
  2. ))}
); } ``` You are now importing your client, querying the `User` model for all users, and then displaying them in a list. Now your home page is dynamic and will display the users from your database. ### 3.1 Update your data (optional) [#31-update-your-data-optional] If you want to see what happens when data is updated, you could: * update your `User` table via a SQL browser of your choice * change your `seed.ts` file to add more users * change the call to `prisma.user.findMany` to re-order the users, filter the users, or similar. Reload the page to see the changes. ## 4. Add a new Posts list page [#4-add-a-new-posts-list-page] You have your home page working, but you should add a new page that displays all of your posts. First create a new `posts` directory in the `app` directory and create a new `page.tsx` file inside of it. ```bash mkdir -p app/posts && touch app/posts/page.tsx ``` Second, add the following code to the `app/posts/page.tsx` file: ```tsx title="app/posts/page.tsx" import prisma from "@/lib/prisma"; export default async function Posts() { return (

Posts

  • My first post
); } ``` Now `localhost:3000/posts` will load, but the content is hardcoded again. Update it to be dynamic, similarly to the home page: ```tsx title="app/posts/page.tsx" import prisma from "@/lib/prisma"; export default async function Posts() { const posts = await prisma.post.findMany({ include: { author: true, }, }); return (

Posts

    {posts.map((post) => (
  • {post.title} by {post.author.name}
  • ))}
); } ``` This works similarly to the home page, but instead of displaying users, it displays posts. You can also see that you've used `include` in your Prisma Client query to fetch the author of each post so you can display the author's name. This "list view" is one of the most common patterns in web applications. You're going to add two more pages to your application which you'll also commonly need: a "detail view" and a "create view". ## 5. Add a new Posts detail page [#5-add-a-new-posts-detail-page] To complement the Posts list page, you'll add a Posts detail page. In the `posts` directory, create a new `[id]` directory and a new `page.tsx` file inside of that. ```bash mkdir -p "app/posts/[id]" && touch "app/posts/[id]/page.tsx" ``` This page will display a single post's title, content, and author. Just like your other pages, add the following code to the `app/posts/[id]/page.tsx` file: ```tsx title="app/posts/[id]/page.tsx" import prisma from "@/lib/prisma"; export default async function Post({ params }: { params: Promise<{ id: string }> }) { return (

My first post

by Anonymous

No content available.
); } ``` As before, this page is static with hardcoded content. Update it to be dynamic based on the `params` passed to the page: ```tsx title="app/posts/[id]/page.tsx" import prisma from "@/lib/prisma"; import { notFound } from "next/navigation"; export default async function Post({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const post = await prisma.post.findUnique({ where: { id: parseInt(id) }, include: { author: true, }, }); if (!post) { notFound(); } return (

{post.title}

by {post.author.name}

{post.content || "No content available."}
); } ``` There's a lot of changes here, so here is what each part does: * You're using Prisma Client to fetch the post by its `id`, which you get from the `params` object. * In case the post doesn't exist (maybe it was deleted or maybe you typed a wrong ID), you call `notFound()` to display a 404 page. * You then display the post's title, content, and author. If the post doesn't have content, you display a placeholder message. It's not the prettiest page, but it's a good start. Try it out by navigating to `localhost:3000/posts/1` and `localhost:3000/posts/2`. You can also test the 404 page by navigating to `localhost:3000/posts/999`. ## 6. Add a new Posts create page [#6-add-a-new-posts-create-page] To round out your application, you'll add a "create" page for posts. This will let you write your own posts and save them to the database. As with the other pages, you'll start with a static page and then update it to be dynamic. ```bash mkdir -p app/posts/new && touch app/posts/new/page.tsx ``` Now, add the following code to the `app/posts/new/page.tsx` file: ```tsx title="app/posts/new/page.tsx" import Form from "next/form"; export default function NewPost() { async function createPost(formData: FormData) { "use server"; const title = formData.get("title") as string; const content = formData.get("content") as string; } return (

Create New Post