From c832ff3ccf0c7887e03aceb4e96adff384f91ac9 Mon Sep 17 00:00:00 2001 From: Mike Hartington Date: Mon, 13 Apr 2026 15:19:29 +0300 Subject: [PATCH 1/2] feat(docs): only version the orm content --- apps/docs/content/docs.v6/(index)/index.mdx | 70 -- apps/docs/content/docs.v6/(index)/meta.json | 6 - .../add-to-existing-project/cockroachdb.mdx | 241 ----- .../add-to-existing-project/meta.json | 13 - .../add-to-existing-project/mongodb.mdx | 322 ------ .../add-to-existing-project/mysql.mdx | 245 ----- .../add-to-existing-project/planetscale.mdx | 223 ---- .../add-to-existing-project/postgresql.mdx | 237 ----- .../prisma-postgres.mdx | 240 ----- .../add-to-existing-project/sql-server.mdx | 255 ----- .../add-to-existing-project/sqlite.mdx | 283 ----- .../docs.v6/(index)/prisma-orm/meta.json | 5 - .../prisma-orm/quickstart/cockroachdb.mdx | 255 ----- .../(index)/prisma-orm/quickstart/meta.json | 13 - .../(index)/prisma-orm/quickstart/mongodb.mdx | 311 ------ .../(index)/prisma-orm/quickstart/mysql.mdx | 268 ----- .../prisma-orm/quickstart/planetscale.mdx | 292 ----- .../prisma-orm/quickstart/postgresql.mdx | 270 ----- .../prisma-orm/quickstart/prisma-postgres.mdx | 252 ----- .../prisma-orm/quickstart/sql-server.mdx | 275 ----- .../(index)/prisma-orm/quickstart/sqlite.mdx | 296 ------ .../(index)/prisma-postgres/from-the-cli.mdx | 524 --------- .../import-from-existing-database-mysql.mdx | 209 ---- ...port-from-existing-database-postgresql.mdx | 193 ---- .../docs.v6/(index)/prisma-postgres/index.mdx | 13 - .../docs.v6/(index)/prisma-postgres/meta.json | 11 - .../quickstart/drizzle-orm.mdx | 194 ---- .../prisma-postgres/quickstart/kysely.mdx | 270 ----- .../prisma-postgres/quickstart/meta.json | 4 - .../prisma-postgres/quickstart/prisma-orm.mdx | 245 ----- .../prisma-postgres/quickstart/typeorm.mdx | 176 ---- .../docs.v6/accelerate/api-reference.mdx | 232 ---- .../content/docs.v6/accelerate/caching.mdx | 11 - .../content/docs.v6/accelerate/compare.mdx | 95 -- .../docs.v6/accelerate/connection-pooling.mdx | 10 - .../content/docs.v6/accelerate/evaluating.mdx | 224 ---- .../content/docs.v6/accelerate/examples.mdx | 20 - apps/docs/content/docs.v6/accelerate/faq.mdx | 221 ---- .../content/docs.v6/accelerate/feedback.mdx | 9 - .../docs.v6/accelerate/getting-started.mdx | 252 ----- .../docs/content/docs.v6/accelerate/index.mdx | 34 - .../docs.v6/accelerate/known-limitations.mdx | 42 - .../docs.v6/accelerate/local-development.mdx | 62 -- .../docs/content/docs.v6/accelerate/meta.json | 20 - .../content/docs.v6/accelerate/static-ip.mdx | 42 - .../docs.v6/accelerate/troubleshoot.mdx | 184 ---- apps/docs/content/docs.v6/ai/index.mdx | 61 -- apps/docs/content/docs.v6/ai/meta.json | 5 - .../docs/content/docs.v6/ai/prompts/astro.mdx | 298 ------ .../content/docs.v6/ai/prompts/nextjs.mdx | 637 ----------- .../content/docs.v6/ai/prompts/prisma-7.mdx | 459 -------- .../content/docs.v6/ai/prompts/turborepo.mdx | 524 --------- .../docs.v6/ai/tutorials/linktree-clone.mdx | 751 ------------- .../content/docs.v6/guides/ai-sdk-nextjs.mdx | 649 ------------ apps/docs/content/docs.v6/guides/astro.mdx | 403 ------- .../content/docs.v6/guides/authjs-nextjs.mdx | 631 ----------- .../docs.v6/guides/betterauth-astro.mdx | 878 --------------- .../docs.v6/guides/betterauth-nextjs.mdx | 996 ------------------ apps/docs/content/docs.v6/guides/bun.mdx | 329 ------ .../content/docs.v6/guides/clerk-astro.mdx | 518 --------- .../content/docs.v6/guides/clerk-nextjs.mdx | 834 --------------- .../content/docs.v6/guides/cloudflare-d1.mdx | 318 ------ .../docs.v6/guides/cloudflare-workers.mdx | 414 -------- apps/docs/content/docs.v6/guides/data-dog.mdx | 504 --------- .../content/docs.v6/guides/data-migration.mdx | 281 ----- .../docs.v6/guides/deno-integration.mdx | 274 ----- apps/docs/content/docs.v6/guides/docker.mdx | 563 ---------- apps/docs/content/docs.v6/guides/elysia.mdx | 444 -------- .../docs.v6/guides/embed-studio-nextjs.mdx | 493 --------- .../content/docs.v6/guides/github-actions.mdx | 648 ------------ apps/docs/content/docs.v6/guides/hono.mdx | 358 ------- .../guides/implementing-schema-changes.mdx | 248 ----- apps/docs/content/docs.v6/guides/index.mdx | 17 - .../docs.v6/guides/management-api-basic.mdx | 186 ---- .../content/docs.v6/guides/management-api.mdx | 164 --- apps/docs/content/docs.v6/guides/meta.json | 55 - .../docs.v6/guides/migrate-from-drizzle.mdx | 551 ---------- .../docs.v6/guides/migrate-from-mongoose.mdx | 396 ------- .../docs.v6/guides/migrate-from-sequelize.mdx | 256 ----- .../docs.v6/guides/migrate-from-typeorm.mdx | 228 ---- .../docs.v6/guides/multiple-databases.mdx | 463 -------- .../docs.v6/guides/neon-accelerate.mdx | 179 ---- apps/docs/content/docs.v6/guides/nestjs.mdx | 515 --------- apps/docs/content/docs.v6/guides/nextjs.mdx | 703 ------------ apps/docs/content/docs.v6/guides/nuxt.mdx | 281 ----- .../guides/permit-io-access-control.mdx | 705 ------------- .../content/docs.v6/guides/react-router-7.mdx | 713 ------------- apps/docs/content/docs.v6/guides/shopify.mdx | 765 -------------- .../content/docs.v6/guides/solid-start.mdx | 443 -------- .../docs.v6/guides/supabase-accelerate.mdx | 179 ---- .../docs/content/docs.v6/guides/sveltekit.mdx | 383 ------- .../content/docs.v6/guides/tanstack-start.mdx | 268 ----- .../docs/content/docs.v6/guides/turborepo.mdx | 535 ---------- .../guides/use-prisma-in-pnpm-workspaces.mdx | 360 ------- .../docs.v6/guides/vercel-app-deployment.mdx | 624 ----------- apps/docs/content/docs.v6/meta.json | 11 - apps/docs/content/docs.v6/orm/meta.json | 16 - apps/docs/content/docs.v6/orm/more/meta.json | 5 - .../content/docs.v6/orm/overview/meta.json | 5 - .../docs.v6/orm/prisma-client/meta.json | 5 - .../docs.v6/orm/prisma-migrate/meta.json | 5 - .../docs.v6/orm/prisma-schema/meta.json | 5 - .../content/docs.v6/orm/reference/meta.json | 5 - apps/docs/content/docs.v6/platform/about.mdx | 146 --- .../docs.v6/platform/concepts/meta.json | 5 - apps/docs/content/docs.v6/platform/index.mdx | 16 - .../docs.v6/platform/maturity-levels.mdx | 42 - apps/docs/content/docs.v6/platform/meta.json | 6 - .../docs.v6/platform/platform-cli/about.mdx | 12 - .../platform/platform-cli/commands.mdx | 268 ----- .../docs.v6/platform/platform-cli/meta.json | 5 - .../docs/content/docs.v6/platform/support.mdx | 39 - .../api-reference/error-reference.mdx | 124 --- .../postgres/database/api-reference/index.mdx | 8 - .../docs.v6/postgres/database/backups.mdx | 81 -- .../docs.v6/postgres/database/caching.mdx | 297 ------ .../postgres/database/connection-pooling.mdx | 134 --- .../postgres/database/direct-connections.mdx | 163 --- .../postgres/database/local-development.mdx | 281 ----- .../docs.v6/postgres/database/meta.json | 13 - .../postgres/database/postgres-extensions.mdx | 223 ---- .../prisma-studio/embedding-studio.mdx | 307 ------ .../postgres/database/prisma-studio/index.mdx | 22 - .../postgres/database/prisma-studio/meta.json | 5 - .../prisma-studio/studio-in-vs-code.mdx | 26 - .../postgres/database/serverless-driver.mdx | 332 ------ apps/docs/content/docs.v6/postgres/faq.mdx | 388 ------- .../docs.v6/postgres/getting-started.mdx | 56 - apps/docs/content/docs.v6/postgres/index.mdx | 19 - .../docs.v6/postgres/integrations/flyio.mdx | 144 --- .../docs.v6/postgres/integrations/idx.mdx | 14 - .../docs.v6/postgres/integrations/index.mdx | 15 - .../postgres/integrations/mcp-server.mdx | 458 -------- .../docs.v6/postgres/integrations/meta.json | 4 - .../docs.v6/postgres/integrations/netlify.mdx | 256 ----- .../docs.v6/postgres/integrations/vercel.mdx | 94 -- .../postgres/integrations/viewing-data.mdx | 142 --- .../docs.v6/postgres/integrations/vscode.mdx | 143 --- .../import-from-existing-database.mdx | 12 - .../docs.v6/postgres/introduction/index.mdx | 15 - .../introduction/management-api-sdk.mdx | 439 -------- .../postgres/introduction/management-api.mdx | 513 --------- .../docs.v6/postgres/introduction/meta.json | 10 - .../postgres/introduction/npx-create-db.mdx | 178 ---- .../postgres/introduction/overview.mdx | 76 -- apps/docs/content/docs.v6/postgres/meta.json | 14 - .../docs.v6/postgres/troubleshooting.mdx | 64 -- .../docs/orm/core-concepts/api-patterns.mdx | 2 +- .../docs/orm/core-concepts/data-modeling.mdx | 2 +- .../supported-databases/database-drivers.mdx | 2 +- .../supported-databases/index.mdx | 2 +- .../supported-databases/mongodb.mdx | 2 +- .../supported-databases/mysql.mdx | 2 +- .../supported-databases/postgresql.mdx | 2 +- .../supported-databases/sql-server.mdx | 2 +- .../supported-databases/sqlite.mdx | 2 +- apps/docs/content/docs/orm/index.mdx | 2 +- apps/docs/content/docs/orm/meta.json | 3 +- .../content/docs/orm/more/best-practices.mdx | 2 +- .../more/comparisons/prisma-and-drizzle.mdx | 2 +- .../more/comparisons/prisma-and-mongoose.mdx | 2 +- .../more/comparisons/prisma-and-sequelize.mdx | 2 +- .../more/comparisons/prisma-and-typeorm.mdx | 2 +- .../orm/more/dev-environment/editor-setup.mdx | 2 +- .../dev-environment/environment-variables.mdx | 2 +- apps/docs/content/docs/orm/more/releases.mdx | 2 +- .../more/troubleshooting/bundler-issues.mdx | 2 +- .../troubleshooting/check-constraints.mdx | 2 +- .../graphql-autocompletion.mdx | 2 +- .../many-to-many-relations.mdx | 2 +- .../docs/orm/more/troubleshooting/nextjs.mdx | 2 +- .../docs/orm/more/troubleshooting/nuxt.mdx | 2 +- .../troubleshooting/raw-sql-comparisons.mdx | 2 +- .../typescript-performance.mdx | 2 +- .../client-extensions/client.mdx | 2 +- .../client-extensions/extension-examples.mdx | 2 +- .../prisma-client/client-extensions/index.mdx | 2 +- .../prisma-client/client-extensions/model.mdx | 2 +- .../prisma-client/client-extensions/query.mdx | 2 +- .../client-extensions/result.mdx | 2 +- .../shared-extensions/index.mdx | 2 +- .../shared-extensions/permit-rbac.mdx | 2 +- .../client-extensions/type-utilities.mdx | 2 +- .../debugging.mdx | 2 +- .../handling-exceptions-and-errors.mdx | 2 +- ...aveats-when-deploying-to-aws-platforms.mdx | 2 +- ...y-database-changes-with-prisma-migrate.mdx | 2 +- ...oy-migrations-from-a-local-environment.mdx | 2 +- .../deployment/deploy-prisma.mdx | 2 +- .../deployment/edge/deploy-to-cloudflare.mdx | 2 +- .../deployment/edge/deploy-to-deno-deploy.mdx | 2 +- .../deployment/edge/deploy-to-vercel.mdx | 2 +- .../deployment/edge/overview.mdx | 2 +- .../serverless/deploy-to-aws-lambda.mdx | 2 +- .../serverless/deploy-to-azure-functions.mdx | 2 +- .../serverless/deploy-to-netlify.mdx | 2 +- .../serverless/deploy-to-vercel.mdx | 2 +- .../traditional/deploy-to-flyio.mdx | 2 +- .../traditional/deploy-to-heroku.mdx | 2 +- .../traditional/deploy-to-koyeb.mdx | 2 +- .../traditional/deploy-to-railway.mdx | 2 +- .../traditional/deploy-to-render.mdx | 2 +- .../traditional/deploy-to-sevalla.mdx | 2 +- .../observability-and-logging/logging.mdx | 2 +- .../opentelemetry-tracing.mdx | 2 +- .../sql-comments.mdx | 2 +- .../query-optimization-performance.mdx | 2 +- .../aggregation-grouping-summarizing.mdx | 2 +- .../docs/orm/prisma-client/queries/crud.mdx | 2 +- .../queries/relation-queries.mdx | 2 +- .../prisma-client/queries/transactions.mdx | 2 +- .../custom-model-and-field-names.mdx | 2 +- .../database-polyfills.mdx | 2 +- .../connection-management.mdx | 2 +- .../databases-connections/connection-pool.mdx | 2 +- .../databases-connections/index.mdx | 2 +- .../databases-connections/pgbouncer.mdx | 2 +- .../error-formatting.mdx | 2 +- .../setup-and-configuration/introduction.mdx | 2 +- .../setup-and-configuration/read-replicas.mdx | 2 +- .../composite-types.mdx | 2 +- .../special-fields-and-types/index.mdx | 2 +- .../null-and-undefined.mdx | 2 +- ...ing-with-composite-ids-and-constraints.mdx | 2 +- .../working-with-geometry-fields.mdx | 2 +- .../working-with-json-fields.mdx | 2 +- .../working-with-scalar-lists-arrays.mdx | 2 +- .../testing/integration-testing.mdx | 2 +- .../prisma-client/testing/unit-testing.mdx | 2 +- .../orm/prisma-client/type-safety/index.mdx | 2 +- ...inst-partial-structures-of-model-types.mdx | 2 +- .../type-safety/prisma-type-system.mdx | 2 +- .../orm/prisma-client/using-raw-sql/index.mdx | 2 +- .../using-raw-sql/raw-queries.mdx | 2 +- .../prisma-client/using-raw-sql/safeql.mdx | 2 +- .../prisma-client/using-raw-sql/typedsql.mdx | 2 +- .../orm/prisma-migrate/getting-started.mdx | 2 +- .../content/docs/orm/prisma-migrate/index.mdx | 2 +- .../limitations-and-known-issues.mdx | 2 +- .../mental-model.mdx | 2 +- .../migration-histories.mdx | 2 +- .../shadow-database.mdx | 2 +- .../prisma-migrate/workflows/baselining.mdx | 2 +- .../workflows/customizing-migrations.mdx | 2 +- .../workflows/development-and-production.mdx | 2 +- .../workflows/generating-down-migrations.mdx | 2 +- .../workflows/native-database-functions.mdx | 2 +- .../workflows/native-database-types.mdx | 2 +- .../workflows/patching-and-hotfixing.mdx | 2 +- .../workflows/prototyping-your-schema.mdx | 2 +- .../orm/prisma-migrate/workflows/seeding.mdx | 2 +- .../workflows/squashing-migrations.mdx | 2 +- .../workflows/troubleshooting.mdx | 2 +- .../unsupported-database-features.mdx | 2 +- .../data-model/database-mapping.mdx | 2 +- .../data-model/externally-managed-tables.mdx | 2 +- .../orm/prisma-schema/data-model/indexes.mdx | 2 +- .../orm/prisma-schema/data-model/models.mdx | 2 +- .../prisma-schema/data-model/multi-schema.mdx | 2 +- .../data-model/relations/index.mdx | 2 +- .../relations/many-to-many-relations.mdx | 2 +- .../relations/one-to-many-relations.mdx | 2 +- .../relations/one-to-one-relations.mdx | 2 +- .../relations/referential-actions.mdx | 2 +- .../data-model/relations/relation-mode.mdx | 2 +- .../data-model/relations/self-relations.mdx | 2 +- .../relations/troubleshooting-relations.mdx | 2 +- .../data-model/table-inheritance.mdx | 2 +- .../unsupported-database-features.mdx | 2 +- .../orm/prisma-schema/data-model/views.mdx | 2 +- .../docs/orm/prisma-schema/introspection.mdx | 2 +- .../prisma-schema/overview/data-sources.mdx | 2 +- .../orm/prisma-schema/overview/generators.mdx | 2 +- .../docs/orm/prisma-schema/overview/index.mdx | 2 +- .../orm/prisma-schema/overview/location.mdx | 2 +- .../prisma-schema/postgresql-extensions.mdx | 2 +- .../docs/orm/reference/connection-urls.mdx | 2 +- .../docs/orm/reference/database-features.mdx | 2 +- .../environment-variables-reference.mdx | 2 +- .../docs/orm/reference/error-reference.mdx | 2 +- .../docs/orm/reference/errors/index.mdx | 2 +- .../preview-features/cli-preview-features.mdx | 2 +- .../client-preview-features.mdx | 2 +- .../orm/reference/prisma-cli-reference.mdx | 2 +- .../orm/reference/prisma-client-reference.mdx | 2 +- .../orm/reference/prisma-config-reference.mdx | 2 +- .../orm/reference/prisma-schema-reference.mdx | 2 +- .../orm/reference/supported-databases.mdx | 2 +- .../orm/reference/system-requirements.mdx | 2 +- .../add-to-existing-project.mdx | 2 +- .../orm/v6}/getting-started/index.mdx | 2 +- .../orm/v6}/getting-started/meta.json | 0 .../orm/v6}/getting-started/quickstart.mdx | 2 +- .../{docs.v6/orm => docs/orm/v6}/index.mdx | 2 +- apps/docs/content/docs/orm/v6/meta.json | 23 + .../orm/v6}/more/ai-tools/chatgpt.mdx | 2 +- .../orm/v6}/more/ai-tools/cursor.mdx | 2 +- .../orm/v6}/more/ai-tools/github-copilot.mdx | 2 +- .../orm/v6}/more/ai-tools/meta.json | 0 .../orm/v6}/more/ai-tools/tabnine.mdx | 2 +- .../orm/v6}/more/ai-tools/windsurf.mdx | 2 +- .../orm/v6}/more/comparisons/meta.json | 0 .../more/comparisons/prisma-and-drizzle.mdx | 2 +- .../more/comparisons/prisma-and-mongoose.mdx | 2 +- .../more/comparisons/prisma-and-sequelize.mdx | 2 +- .../more/comparisons/prisma-and-typeorm.mdx | 2 +- .../v6}/more/dev-environment/editor-setup.mdx | 2 +- .../dev-environment/environment-variables.mdx | 2 +- .../orm/v6}/more/dev-environment/meta.json | 0 .../orm/v6}/more/internals/engines.mdx | 2 +- .../orm/v6}/more/internals/meta.json | 0 apps/docs/content/docs/orm/v6/more/meta.json | 13 + .../orm => docs/orm/v6}/more/releases.mdx | 2 +- .../more/troubleshooting/bundler-issues.mdx | 2 +- .../troubleshooting/check-constraints.mdx | 2 +- .../graphql-autocompletion.mdx | 2 +- .../many-to-many-relations.mdx | 2 +- .../orm/v6}/more/troubleshooting/meta.json | 0 .../orm/v6}/more/troubleshooting/nextjs.mdx | 2 +- .../orm/v6}/more/troubleshooting/nuxt.mdx | 2 +- .../troubleshooting/raw-sql-comparisons.mdx | 2 +- .../typescript-performance.mdx | 2 +- .../orm/v6}/more/upgrades/from-v1.mdx | 2 +- .../orm/v6}/more/upgrades/meta.json | 0 .../orm/v6}/more/upgrades/older-versions.mdx | 2 +- .../v6}/more/upgrades/preview-features.mdx | 2 +- .../orm/v6}/more/upgrades/to-v7.mdx | 2 +- .../orm/v6}/overview/beyond-prisma-orm.mdx | 2 +- .../v6}/overview/databases/cloudflare-d1.mdx | 2 +- .../v6}/overview/databases/cockroachdb.mdx | 2 +- .../overview/databases/database-drivers.mdx | 2 +- .../orm/v6}/overview/databases/meta.json | 8 +- .../orm/v6}/overview/databases/mongodb.mdx | 2 +- .../orm/v6}/overview/databases/mysql.mdx | 2 +- .../orm/v6}/overview/databases/neon.mdx | 2 +- .../v6}/overview/databases/planetscale.mdx | 2 +- .../orm/v6}/overview/databases/postgresql.mdx | 2 +- .../overview/databases/sql-server/index.mdx | 2 +- .../overview/databases/sql-server/meta.json | 0 .../sql-server/sql-server-docker.mdx | 2 +- .../databases/sql-server/sql-server-local.mdx | 2 +- .../orm/v6}/overview/databases/sqlite.mdx | 2 +- .../orm/v6}/overview/databases/supabase.mdx | 2 +- .../orm/v6}/overview/databases/turso.mdx | 2 +- .../overview/introduction/data-modeling.mdx | 2 +- .../orm/v6}/overview/introduction/meta.json | 0 .../introduction/should-you-use-prisma.mdx | 2 +- .../overview/introduction/what-is-prisma.mdx | 2 +- .../v6}/overview/introduction/why-prisma.mdx | 2 +- .../content/docs/orm/v6/overview/meta.json | 5 + .../prisma-in-your-stack/fullstack.mdx | 2 +- .../overview/prisma-in-your-stack/graphql.mdx | 2 +- .../prisma-in-your-stack/is-prisma-an-orm.mdx | 2 +- .../overview/prisma-in-your-stack/meta.json | 0 .../overview/prisma-in-your-stack/rest.mdx | 2 +- .../client-extensions/client.mdx | 2 +- .../client-extensions/extension-examples.mdx | 2 +- .../prisma-client/client-extensions/index.mdx | 2 +- .../prisma-client/client-extensions/meta.json | 0 .../prisma-client/client-extensions/model.mdx | 2 +- .../prisma-client/client-extensions/query.mdx | 2 +- .../client-extensions/result.mdx | 2 +- .../shared-extensions/index.mdx | 2 +- .../shared-extensions/meta.json | 0 .../shared-extensions/permit-rbac.mdx | 2 +- .../client-extensions/type-utilities.mdx | 2 +- .../debugging.mdx | 2 +- .../handling-exceptions-and-errors.mdx | 2 +- .../debugging-and-troubleshooting/meta.json | 0 .../troubleshooting-binary-size-issues.mdx | 2 +- ...aveats-when-deploying-to-aws-platforms.mdx | 2 +- ...y-database-changes-with-prisma-migrate.mdx | 2 +- ...oy-migrations-from-a-local-environment.mdx | 2 +- .../deployment/deploy-prisma.mdx | 2 +- .../deployment/deploy-to-a-different-os.mdx | 2 +- .../deployment/edge/deploy-to-cloudflare.mdx | 2 +- .../deployment/edge/deploy-to-deno-deploy.mdx | 2 +- .../deployment/edge/deploy-to-vercel.mdx | 2 +- .../edge/images/450-03-import-project.snagx | Bin .../edge/images/450-04-connect-db.snagx | Bin .../edge/images/450-05-data-proxy.snagx | Bin ...02-deploy-to-deno-project-parameters.snagx | Bin .../prisma-client/deployment/edge/index.mdx | 2 +- .../prisma-client/deployment/edge/meta.json | 0 .../deployment/edge/overview.mdx | 2 +- .../v6}/prisma-client/deployment/meta.json | 0 .../deployment/module-bundlers.mdx | 2 +- .../serverless/deploy-to-aws-lambda.mdx | 2 +- .../serverless/deploy-to-azure-functions.mdx | 2 +- .../serverless/deploy-to-netlify.mdx | 2 +- .../serverless/deploy-to-vercel.mdx | 2 +- ...00-10-deploy-to-vercel-deploy-button.snagx | Bin ...00-20-deploy-to-vercel-select-github.snagx | Bin ...-30-deploy-to-vercel-create-git-repo.snagx | Bin ...0-deploy-to-vercel-configure-project.snagx | Bin .../300-50-deploy-to-vercel-success.snagx | Bin ...-vercel-preview-environment-variable.snagx | Bin ...ploy-to-vercel-environment-variables.snagx | Bin ...y-to-netlify-example-repo-click-fork.snagx | Bin ...etlify-example-repo-create-fork-page.snagx | Bin ...lify-copy-supabase-connection-string.snagx | Bin ...-netlify-netlify-init-configure-site.snagx | Bin ...0-06-deploy-to-netlify-site-settings.snagx | Bin ...tlify-environment-variables-settings.snagx | Bin ...ploy-to-netlify-application-deployed.snagx | Bin ...ify-application-deployed-call-result.snagx | Bin .../deployment/serverless/index.mdx | 2 +- .../deployment/serverless/meta.json | 0 .../traditional/deploy-to-flyio.mdx | 2 +- .../traditional/deploy-to-heroku.mdx | 2 +- .../traditional/deploy-to-koyeb.mdx | 2 +- .../traditional/deploy-to-railway.mdx | 2 +- .../traditional/deploy-to-render.mdx | 2 +- .../traditional/deploy-to-sevalla.mdx | 2 +- .../deployment/traditional/index.mdx | 2 +- .../deployment/traditional/meta.json | 0 .../docs/orm/v6/prisma-client/meta.json | 16 + .../observability-and-logging/logging.mdx | 2 +- .../observability-and-logging/meta.json | 0 .../observability-and-logging/metrics.mdx | 2 +- .../opentelemetry-tracing.mdx | 2 +- .../sql-comments.mdx | 2 +- .../aggregation-grouping-summarizing.mdx | 2 +- .../queries/case-sensitivity.mdx | 2 +- .../prisma-client/queries/computed-fields.mdx | 2 +- .../orm/v6}/prisma-client/queries/crud.mdx | 2 +- .../prisma-client/queries/custom-models.mdx | 2 +- .../queries/custom-validation.mdx | 2 +- .../queries/excluding-fields.mdx | 2 +- .../queries/filtering-and-sorting.mdx | 2 +- .../queries/full-text-search.mdx | 2 +- .../orm/v6}/prisma-client/queries/meta.json | 0 .../v6}/prisma-client/queries/pagination.mdx | 2 +- .../query-optimization-performance.mdx | 2 +- .../queries/relation-queries.mdx | 2 +- .../prisma-client/queries/select-fields.mdx | 2 +- .../prisma-client/queries/transactions.mdx | 2 +- .../custom-model-and-field-names.mdx | 2 +- .../database-polyfills.mdx | 2 +- .../connection-management.mdx | 2 +- .../databases-connections/connection-pool.mdx | 2 +- .../databases-connections/index.mdx | 2 +- .../databases-connections/meta.json | 0 .../databases-connections/pgbouncer.mdx | 2 +- .../error-formatting.mdx | 2 +- .../generating-prisma-client.mdx | 2 +- .../instantiate-prisma-client.mdx | 2 +- .../setup-and-configuration/introduction.mdx | 2 +- .../setup-and-configuration/meta.json | 0 .../no-rust-engine.mdx | 2 +- .../setup-and-configuration/read-replicas.mdx | 2 +- .../composite-types.mdx | 2 +- .../special-fields-and-types/index.mdx | 2 +- .../special-fields-and-types/meta.json | 0 .../null-and-undefined.mdx | 2 +- ...ing-with-composite-ids-and-constraints.mdx | 2 +- .../working-with-json-fields.mdx | 2 +- .../working-with-scalar-lists-arrays.mdx | 2 +- .../orm/v6}/prisma-client/testing/index.mdx | 2 +- .../testing/integration-testing.mdx | 2 +- .../orm/v6}/prisma-client/testing/meta.json | 0 .../prisma-client/testing/unit-testing.mdx | 2 +- .../v6}/prisma-client/type-safety/index.mdx | 2 +- .../v6}/prisma-client/type-safety/meta.json | 0 ...inst-partial-structures-of-model-types.mdx | 2 +- .../type-safety/prisma-type-system.mdx | 2 +- .../type-safety/prisma-validator.mdx | 2 +- .../v6}/prisma-client/using-raw-sql/index.mdx | 2 +- .../v6}/prisma-client/using-raw-sql/meta.json | 0 .../using-raw-sql/raw-queries.mdx | 2 +- .../prisma-client/using-raw-sql/safeql.mdx | 2 +- .../prisma-client/using-raw-sql/typedsql.mdx | 2 +- .../v6}/prisma-migrate/getting-started.mdx | 2 +- .../docs/orm/v6/prisma-migrate/meta.json | 10 + .../legacy-migrate.mdx | 2 +- .../limitations-and-known-issues.mdx | 2 +- .../mental-model.mdx | 2 +- .../understanding-prisma-migrate/meta.json | 0 .../migration-histories.mdx | 2 +- .../understanding-prisma-migrate/overview.mdx | 2 +- .../shadow-database.mdx | 2 +- .../prisma-migrate/workflows/baselining.mdx | 2 +- .../workflows/customizing-migrations.mdx | 2 +- .../workflows/data-migration.mdx | 2 +- .../workflows/development-and-production.mdx | 2 +- .../workflows/generating-down-migrations.mdx | 2 +- .../v6}/prisma-migrate/workflows/meta.json | 0 .../workflows/native-database-functions.mdx | 2 +- .../workflows/native-database-types.mdx | 2 +- .../workflows/patching-and-hotfixing.mdx | 2 +- .../workflows/prototyping-your-schema.mdx | 2 +- .../v6}/prisma-migrate/workflows/seeding.mdx | 2 +- .../workflows/squashing-migrations.mdx | 2 +- .../workflows/team-development.mdx | 2 +- .../workflows/troubleshooting.mdx | 2 +- .../unsupported-database-features.mdx | 2 +- .../data-model/database-mapping.mdx | 2 +- .../data-model/externally-managed-tables.mdx | 2 +- .../v6}/prisma-schema/data-model/indexes.mdx | 2 +- .../v6}/prisma-schema/data-model/meta.json | 0 .../v6}/prisma-schema/data-model/models.mdx | 2 +- .../prisma-schema/data-model/multi-schema.mdx | 2 +- .../data-model/relations/index.mdx | 2 +- .../relations/many-to-many-relations.mdx | 2 +- .../data-model/relations/meta.json | 0 .../relations/one-to-many-relations.mdx | 2 +- .../relations/one-to-one-relations.mdx | 2 +- .../relations/quick-fix-index.snagx | Bin .../relations/referential-actions/index.mdx | 2 +- .../relations/referential-actions/meta.json | 0 .../special-rules-for-referential-actions.mdx | 2 +- .../data-model/relations/relation-mode.mdx | 2 +- .../data-model/relations/self-relations.mdx | 2 +- .../relations/troubleshooting-relations.mdx | 2 +- .../data-model/table-inheritance.mdx | 2 +- .../unsupported-database-features.mdx | 2 +- .../v6}/prisma-schema/data-model/views.mdx | 2 +- .../orm/v6}/prisma-schema/introspection.mdx | 2 +- .../docs/orm/v6/prisma-schema/meta.json | 10 + .../prisma-schema/overview/data-sources.mdx | 2 +- .../v6}/prisma-schema/overview/generators.mdx | 2 +- .../orm/v6}/prisma-schema/overview/index.mdx | 2 +- .../v6}/prisma-schema/overview/location.mdx | 2 +- .../orm/v6}/prisma-schema/overview/meta.json | 0 .../prisma-schema/postgresql-extensions.mdx | 2 +- .../orm/v6}/reference/connection-urls.mdx | 2 +- .../orm/v6}/reference/database-features.mdx | 2 +- .../environment-variables-reference.mdx | 2 +- .../orm/v6}/reference/error-reference.mdx | 2 +- .../orm/v6}/reference/errors/index.mdx | 2 +- .../orm/v6}/reference/errors/meta.json | 0 .../content/docs/orm/v6/reference/meta.json | 18 + .../preview-features/cli-preview-features.mdx | 2 +- .../client-preview-features.mdx | 2 +- .../v6}/reference/preview-features/index.mdx | 2 +- .../v6}/reference/preview-features/meta.json | 0 .../v6}/reference/prisma-cli-reference.mdx | 2 +- .../v6}/reference/prisma-client-reference.mdx | 2 +- .../v6}/reference/prisma-config-reference.mdx | 2 +- .../v6}/reference/prisma-schema-reference.mdx | 2 +- .../orm/v6}/reference/supported-databases.mdx | 2 +- .../orm/v6}/reference/system-requirements.mdx | 2 +- .../orm => docs/orm/v6}/tools/meta.json | 2 +- .../orm => docs/orm/v6}/tools/prisma-cli.mdx | 2 +- .../orm/v6}/tools/prisma-studio.mdx | 2 +- apps/docs/next.config.mjs | 25 + apps/docs/scripts/lint-links.ts | 53 +- apps/docs/source.config.ts | 40 +- apps/docs/src/app/(docs)/(default)/layout.tsx | 14 +- apps/docs/src/app/(docs)/sitemap.ts | 25 +- .../src/app/(docs)/v6/[[...slug]]/page.tsx | 120 --- apps/docs/src/app/(docs)/v6/layout.tsx | 80 -- apps/docs/src/app/api/search/route.ts | 11 +- apps/docs/src/app/llms-full.txt/route.ts | 6 +- .../src/app/llms.mdx/[[...slug]]/route.ts | 16 +- apps/docs/src/app/llms.txt/route.ts | 23 +- apps/docs/src/app/not-found.tsx | 6 - apps/docs/src/app/og/[...slug]/route.tsx | 15 +- .../src/components/layout/notebook/client.tsx | 32 +- .../components/layout/notebook/sidebar.tsx | 97 +- .../components/layout/sidebar/tabs/index.tsx | 1 - apps/docs/src/components/structured-data.tsx | 4 +- apps/docs/src/components/version-switcher.tsx | 46 +- apps/docs/src/lib/get-llm-text.ts | 4 +- apps/docs/src/lib/layout.shared.tsx | 1 + apps/docs/src/lib/page-badges.ts | 8 +- apps/docs/src/lib/remark-console-utm.ts | 2 +- apps/docs/src/lib/rss.ts | 8 +- apps/docs/src/lib/source.ts | 26 +- apps/docs/src/lib/version.ts | 168 ++- apps/docs/src/lib/versioned-sidebar-tree.ts | 110 ++ 571 files changed, 963 insertions(+), 35578 deletions(-) delete mode 100644 apps/docs/content/docs.v6/(index)/index.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/cockroachdb.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mongodb.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mysql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/planetscale.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/postgresql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/prisma-postgres.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sql-server.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sqlite.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/cockroachdb.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mongodb.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mysql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/planetscale.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/postgresql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/prisma-postgres.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sql-server.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sqlite.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/from-the-cli.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-mysql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-postgresql.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/index.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/drizzle-orm.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/kysely.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/meta.json delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/prisma-orm.mdx delete mode 100644 apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/typeorm.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/api-reference.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/caching.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/compare.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/connection-pooling.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/evaluating.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/examples.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/faq.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/feedback.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/getting-started.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/index.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/known-limitations.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/local-development.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/meta.json delete mode 100644 apps/docs/content/docs.v6/accelerate/static-ip.mdx delete mode 100644 apps/docs/content/docs.v6/accelerate/troubleshoot.mdx delete mode 100644 apps/docs/content/docs.v6/ai/index.mdx delete mode 100644 apps/docs/content/docs.v6/ai/meta.json delete mode 100644 apps/docs/content/docs.v6/ai/prompts/astro.mdx delete mode 100644 apps/docs/content/docs.v6/ai/prompts/nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/ai/prompts/prisma-7.mdx delete mode 100644 apps/docs/content/docs.v6/ai/prompts/turborepo.mdx delete mode 100644 apps/docs/content/docs.v6/ai/tutorials/linktree-clone.mdx delete mode 100644 apps/docs/content/docs.v6/guides/ai-sdk-nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/astro.mdx delete mode 100644 apps/docs/content/docs.v6/guides/authjs-nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/betterauth-astro.mdx delete mode 100644 apps/docs/content/docs.v6/guides/betterauth-nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/bun.mdx delete mode 100644 apps/docs/content/docs.v6/guides/clerk-astro.mdx delete mode 100644 apps/docs/content/docs.v6/guides/clerk-nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/cloudflare-d1.mdx delete mode 100644 apps/docs/content/docs.v6/guides/cloudflare-workers.mdx delete mode 100644 apps/docs/content/docs.v6/guides/data-dog.mdx delete mode 100644 apps/docs/content/docs.v6/guides/data-migration.mdx delete mode 100644 apps/docs/content/docs.v6/guides/deno-integration.mdx delete mode 100644 apps/docs/content/docs.v6/guides/docker.mdx delete mode 100644 apps/docs/content/docs.v6/guides/elysia.mdx delete mode 100644 apps/docs/content/docs.v6/guides/embed-studio-nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/github-actions.mdx delete mode 100644 apps/docs/content/docs.v6/guides/hono.mdx delete mode 100644 apps/docs/content/docs.v6/guides/implementing-schema-changes.mdx delete mode 100644 apps/docs/content/docs.v6/guides/index.mdx delete mode 100644 apps/docs/content/docs.v6/guides/management-api-basic.mdx delete mode 100644 apps/docs/content/docs.v6/guides/management-api.mdx delete mode 100644 apps/docs/content/docs.v6/guides/meta.json delete mode 100644 apps/docs/content/docs.v6/guides/migrate-from-drizzle.mdx delete mode 100644 apps/docs/content/docs.v6/guides/migrate-from-mongoose.mdx delete mode 100644 apps/docs/content/docs.v6/guides/migrate-from-sequelize.mdx delete mode 100644 apps/docs/content/docs.v6/guides/migrate-from-typeorm.mdx delete mode 100644 apps/docs/content/docs.v6/guides/multiple-databases.mdx delete mode 100644 apps/docs/content/docs.v6/guides/neon-accelerate.mdx delete mode 100644 apps/docs/content/docs.v6/guides/nestjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/nextjs.mdx delete mode 100644 apps/docs/content/docs.v6/guides/nuxt.mdx delete mode 100644 apps/docs/content/docs.v6/guides/permit-io-access-control.mdx delete mode 100644 apps/docs/content/docs.v6/guides/react-router-7.mdx delete mode 100644 apps/docs/content/docs.v6/guides/shopify.mdx delete mode 100644 apps/docs/content/docs.v6/guides/solid-start.mdx delete mode 100644 apps/docs/content/docs.v6/guides/supabase-accelerate.mdx delete mode 100644 apps/docs/content/docs.v6/guides/sveltekit.mdx delete mode 100644 apps/docs/content/docs.v6/guides/tanstack-start.mdx delete mode 100644 apps/docs/content/docs.v6/guides/turborepo.mdx delete mode 100644 apps/docs/content/docs.v6/guides/use-prisma-in-pnpm-workspaces.mdx delete mode 100644 apps/docs/content/docs.v6/guides/vercel-app-deployment.mdx delete mode 100644 apps/docs/content/docs.v6/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/more/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/overview/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/prisma-client/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/prisma-migrate/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/prisma-schema/meta.json delete mode 100644 apps/docs/content/docs.v6/orm/reference/meta.json delete mode 100644 apps/docs/content/docs.v6/platform/about.mdx delete mode 100644 apps/docs/content/docs.v6/platform/concepts/meta.json delete mode 100644 apps/docs/content/docs.v6/platform/index.mdx delete mode 100644 apps/docs/content/docs.v6/platform/maturity-levels.mdx delete mode 100644 apps/docs/content/docs.v6/platform/meta.json delete mode 100644 apps/docs/content/docs.v6/platform/platform-cli/about.mdx delete mode 100644 apps/docs/content/docs.v6/platform/platform-cli/commands.mdx delete mode 100644 apps/docs/content/docs.v6/platform/platform-cli/meta.json delete mode 100644 apps/docs/content/docs.v6/platform/support.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/api-reference/error-reference.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/api-reference/index.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/backups.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/caching.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/connection-pooling.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/direct-connections.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/local-development.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/meta.json delete mode 100644 apps/docs/content/docs.v6/postgres/database/postgres-extensions.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/prisma-studio/embedding-studio.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/prisma-studio/index.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/prisma-studio/meta.json delete mode 100644 apps/docs/content/docs.v6/postgres/database/prisma-studio/studio-in-vs-code.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/database/serverless-driver.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/faq.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/getting-started.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/index.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/flyio.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/idx.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/index.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/mcp-server.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/meta.json delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/netlify.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/vercel.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/viewing-data.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/integrations/vscode.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/import-from-existing-database.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/index.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/management-api-sdk.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/management-api.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/meta.json delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/npx-create-db.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/introduction/overview.mdx delete mode 100644 apps/docs/content/docs.v6/postgres/meta.json delete mode 100644 apps/docs/content/docs.v6/postgres/troubleshooting.mdx rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/getting-started/add-to-existing-project.mdx (95%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/getting-started/index.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/getting-started/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/getting-started/quickstart.mdx (96%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/index.mdx (97%) create mode 100644 apps/docs/content/docs/orm/v6/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/chatgpt.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/cursor.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/github-copilot.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/tabnine.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/ai-tools/windsurf.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/comparisons/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/comparisons/prisma-and-drizzle.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/comparisons/prisma-and-mongoose.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/comparisons/prisma-and-sequelize.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/comparisons/prisma-and-typeorm.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/dev-environment/editor-setup.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/dev-environment/environment-variables.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/dev-environment/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/internals/engines.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/internals/meta.json (100%) create mode 100644 apps/docs/content/docs/orm/v6/more/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/releases.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/bundler-issues.mdx (94%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/check-constraints.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/graphql-autocompletion.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/many-to-many-relations.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/nextjs.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/nuxt.mdx (92%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/raw-sql-comparisons.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/troubleshooting/typescript-performance.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/upgrades/from-v1.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/upgrades/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/upgrades/older-versions.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/upgrades/preview-features.mdx (94%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/more/upgrades/to-v7.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/beyond-prisma-orm.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/cloudflare-d1.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/cockroachdb.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/database-drivers.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/meta.json (69%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/mongodb.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/mysql.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/neon.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/planetscale.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/postgresql.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/sql-server/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/sql-server/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/sql-server/sql-server-docker.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/sql-server/sql-server-local.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/sqlite.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/supabase.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/databases/turso.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/introduction/data-modeling.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/introduction/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/introduction/should-you-use-prisma.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/introduction/what-is-prisma.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/introduction/why-prisma.mdx (99%) create mode 100644 apps/docs/content/docs/orm/v6/overview/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/prisma-in-your-stack/fullstack.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/prisma-in-your-stack/graphql.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/prisma-in-your-stack/is-prisma-an-orm.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/prisma-in-your-stack/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/overview/prisma-in-your-stack/rest.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/client.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/extension-examples.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/model.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/query.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/result.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/shared-extensions/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/shared-extensions/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/shared-extensions/permit-rbac.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/client-extensions/type-utilities.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/debugging-and-troubleshooting/debugging.mdx (96%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/debugging-and-troubleshooting/handling-exceptions-and-errors.mdx (95%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/debugging-and-troubleshooting/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/debugging-and-troubleshooting/troubleshooting-binary-size-issues.mdx (96%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/caveats-when-deploying-to-aws-platforms.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/deploy-database-changes-with-prisma-migrate.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/deploy-migrations-from-a-local-environment.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/deploy-prisma.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/deploy-to-a-different-os.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/deploy-to-cloudflare.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/deploy-to-deno-deploy.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/deploy-to-vercel.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/images/450-03-import-project.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/images/450-04-connect-db.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/images/450-05-data-proxy.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/images/550-02-deploy-to-deno-project-parameters.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/index.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/edge/overview.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/module-bundlers.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/deploy-to-aws-lambda.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/deploy-to-azure-functions.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/deploy-to-netlify.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/deploy-to-vercel.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-10-deploy-to-vercel-deploy-button.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-20-deploy-to-vercel-select-github.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-30-deploy-to-vercel-create-git-repo.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-40-deploy-to-vercel-configure-project.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-50-deploy-to-vercel-success.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-60-deploy-to-vercel-preview-environment-variable.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/300-70-deploy-to-vercel-environment-variables.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-02-deploy-to-netlify-example-repo-click-fork.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-03-deploy-to-netlify-example-repo-create-fork-page.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-04-deploy-to-netlify-copy-supabase-connection-string.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-05-deploy-to-netlify-netlify-init-configure-site.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-06-deploy-to-netlify-site-settings.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-07-deploy-to-netlify-environment-variables-settings.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-08-deploy-to-netlify-application-deployed.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/images/500-09-deploy-to-netlify-application-deployed-call-result.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/index.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/serverless/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-flyio.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-heroku.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-koyeb.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-railway.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-render.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/deploy-to-sevalla.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/index.mdx (92%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/deployment/traditional/meta.json (100%) create mode 100644 apps/docs/content/docs/orm/v6/prisma-client/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/observability-and-logging/logging.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/observability-and-logging/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/observability-and-logging/metrics.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/observability-and-logging/opentelemetry-tracing.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/observability-and-logging/sql-comments.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/aggregation-grouping-summarizing.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/case-sensitivity.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/computed-fields.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/crud.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/custom-models.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/custom-validation.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/excluding-fields.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/filtering-and-sorting.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/full-text-search.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/pagination.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/query-optimization-performance.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/relation-queries.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/select-fields.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/queries/transactions.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/custom-model-and-field-names.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/database-polyfills.mdx (95%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/databases-connections/connection-management.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/databases-connections/connection-pool.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/databases-connections/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/databases-connections/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/databases-connections/pgbouncer.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/error-formatting.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/generating-prisma-client.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/instantiate-prisma-client.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/introduction.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/no-rust-engine.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/setup-and-configuration/read-replicas.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/composite-types.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/index.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/null-and-undefined.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/working-with-composite-ids-and-constraints.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/working-with-json-fields.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/special-fields-and-types/working-with-scalar-lists-arrays.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/testing/index.mdx (89%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/testing/integration-testing.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/testing/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/testing/unit-testing.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/type-safety/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/type-safety/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/type-safety/operating-against-partial-structures-of-model-types.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/type-safety/prisma-type-system.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/type-safety/prisma-validator.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/using-raw-sql/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/using-raw-sql/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/using-raw-sql/raw-queries.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/using-raw-sql/safeql.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-client/using-raw-sql/typedsql.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/getting-started.mdx (99%) create mode 100644 apps/docs/content/docs/orm/v6/prisma-migrate/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/legacy-migrate.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/limitations-and-known-issues.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/mental-model.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/migration-histories.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/overview.mdx (96%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/understanding-prisma-migrate/shadow-database.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/baselining.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/customizing-migrations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/data-migration.mdx (86%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/development-and-production.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/generating-down-migrations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/native-database-functions.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/native-database-types.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/patching-and-hotfixing.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/prototyping-your-schema.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/seeding.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/squashing-migrations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/team-development.mdx (86%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/troubleshooting.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-migrate/workflows/unsupported-database-features.mdx (96%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/database-mapping.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/externally-managed-tables.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/indexes.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/models.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/multi-schema.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/many-to-many-relations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/one-to-many-relations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/one-to-one-relations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/quick-fix-index.snagx (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/referential-actions/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/referential-actions/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/referential-actions/special-rules-for-referential-actions.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/relation-mode.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/self-relations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/relations/troubleshooting-relations.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/table-inheritance.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/unsupported-database-features.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/data-model/views.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/introspection.mdx (99%) create mode 100644 apps/docs/content/docs/orm/v6/prisma-schema/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/overview/data-sources.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/overview/generators.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/overview/index.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/overview/location.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/overview/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/prisma-schema/postgresql-extensions.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/connection-urls.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/database-features.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/environment-variables-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/error-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/errors/index.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/errors/meta.json (100%) create mode 100644 apps/docs/content/docs/orm/v6/reference/meta.json rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/preview-features/cli-preview-features.mdx (97%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/preview-features/client-preview-features.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/preview-features/index.mdx (95%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/preview-features/meta.json (100%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/prisma-cli-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/prisma-client-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/prisma-config-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/prisma-schema-reference.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/supported-databases.mdx (98%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/reference/system-requirements.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/tools/meta.json (52%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/tools/prisma-cli.mdx (99%) rename apps/docs/content/{docs.v6/orm => docs/orm/v6}/tools/prisma-studio.mdx (99%) delete mode 100644 apps/docs/src/app/(docs)/v6/[[...slug]]/page.tsx delete mode 100644 apps/docs/src/app/(docs)/v6/layout.tsx create mode 100644 apps/docs/src/lib/versioned-sidebar-tree.ts diff --git a/apps/docs/content/docs.v6/(index)/index.mdx b/apps/docs/content/docs.v6/(index)/index.mdx deleted file mode 100644 index 42479025ad..0000000000 --- a/apps/docs/content/docs.v6/(index)/index.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Get Started -description: Welcome to Prisma! Choose your path below to get started. -url: /v6 -metaTitle: Get started with Prisma -metaDescription: 'Build data-driven applications with ease using Prisma ORM, add connection pooling with Prisma Postgres.' ---- - -## Prisma ORM - -[**Prisma ORM**](/v6/orm/overview/introduction/what-is-prisma) is an open-source ORM that provides fast, type-safe access to Postgres, MySQL, SQLite, and more databases. - -```npm -npx prisma init --db -``` - -## Prisma Postgres - -[**Prisma Postgres**](/v6/postgres) is a fully managed PostgreSQL database that scales to zero, integrates with Prisma ORM and Prisma Studio. - -```npm -npx create-db -``` - ---- - -## Quickstart - -The fastest way to set up **Prisma ORM** with a ready-to-use **Prisma Postgres** database. - -[**Start Quickstart →**](/v6/prisma-orm/quickstart/prisma-postgres) - ---- - -## Have Your Own Database? - -Set up Prisma ORM with your existing database: - -| Database | Guide | -| ----------- | --------------------------------------------------------------------------- | -| PostgreSQL | [Get started →](/v6/prisma-orm/quickstart/postgresql) | -| MySQL | [Get started →](/v6/prisma-orm/quickstart/mysql) | -| SQL Server | [Get started →](/v6/prisma-orm/quickstart/sql-server) | -| SQLite | [Get started →](/v6/prisma-orm/quickstart/sqlite) | -| MongoDB | [Get started →](/v6/prisma-orm/quickstart/mongodb) | -| PlanetScale | [Get started →](/v6/prisma-orm/quickstart/planetscale) | -| CockroachDB | [Get started →](/v6/prisma-orm/quickstart/cockroachdb) | - ---- - -## Add Prisma to Your Framework - -Working with a popular framework? You can easily add Prisma to your setup: - -| Framework | Guide | -| -------------- | ----------------------------------------------- | -| Next.js | [Get started →](/v6/guides/nextjs) | -| Nuxt.js | [Get started →](/v6/guides/nuxt) | -| Astro | [Get started →](/v6/guides/astro) | -| SvelteKit | [Get started →](/v6/guides/sveltekit) | -| React Router 7 | [Get started →](/v6/guides/react-router-7) | -| TanStack Start | [Get started →](/v6/guides/tanstack-start) | - ---- - -## Add to Existing Project - -Already have a project? Add Prisma ORM to your existing application: - -[**Add to Existing Project →**](/v6/prisma-orm/add-to-existing-project/prisma-postgres) diff --git a/apps/docs/content/docs.v6/(index)/meta.json b/apps/docs/content/docs.v6/(index)/meta.json deleted file mode 100644 index 938f6a66cf..0000000000 --- a/apps/docs/content/docs.v6/(index)/meta.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "title": "Getting Started", - "root": true, - "defaultOpen": true, - "pages": ["index", "prisma-orm", "prisma-postgres"] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/cockroachdb.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/cockroachdb.mdx deleted file mode 100644 index 5fa7027aeb..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/cockroachdb.mdx +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: CockroachDB -description: 'Add Prisma ORM to an existing TypeScript project with CockroachDB and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/cockroachdb -metaTitle: How to add Prisma ORM to an existing project using CockroachDB (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with CockroachDB and learn database introspection, baselining, and querying.' ---- - -[CockroachDB](https://www.cockroachlabs.com/) is a distributed SQL database designed for cloud applications, offering horizontal scalability, strong consistency, and high availability. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to CockroachDB, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible) -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider cockroachdb --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "cockroachdb" -} -``` - -## 3. Connect your database - -Update the `.env` file with your CockroachDB connection URL: - -```bash title=".env" -DATABASE_URL="postgresql://user:password@host:26257/mydb?sslmode=require" -``` - -The [format of the connection URL](/v6/orm/reference/connection-urls) for CockroachDB looks as follows: - -``` -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslmode=require -``` - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data - -Explore the options suggested by [CockroachDB](https://www.cockroachlabs.com/blog/cockroachdb-gui-options/) to view and manage your data. - -[Prisma Studio](/v6/orm/tools/prisma-studio) does not currently support CockroachDB. Support may be added in a future release. See [Databases supported by Prisma Studio](/v6/orm/tools/prisma-studio#databases-supported-by-prisma-studio) for more information. - -## Next steps - -## More info - -- [CockroachDB database connector](/v6/orm/overview/databases/cockroachdb) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/meta.json b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/meta.json deleted file mode 100644 index d0d0a4e667..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Add to Existing Project", - "pages": [ - "prisma-postgres", - "sqlite", - "postgresql", - "mysql", - "sql-server", - "planetscale", - "cockroachdb", - "mongodb" - ] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mongodb.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mongodb.mdx deleted file mode 100644 index e6f9b156b6..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mongodb.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -title: MongoDB -description: Add Prisma ORM to an existing TypeScript project with MongoDB and learn database introspection and querying. -url: /v6/prisma-orm/add-to-existing-project/mongodb -metaTitle: How to add Prisma ORM to an existing project using MongoDB (15 min) -metaDescription: Add Prisma ORM to an existing TypeScript project with MongoDB and learn database introspection and querying. ---- - -[MongoDB](https://www.mongodb.com/) is a popular document-based NoSQL database known for its flexibility, scalability, and developer-friendly features. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to MongoDB, introspect your existing database schema, and start querying with type-safe Prisma Client. - -:::warning[MongoDB support for Prisma ORM v7] - -**MongoDB support for Prisma ORM v7 is coming in the near future.** In the meantime, please use **Prisma ORM v6.19** (the latest v6 release) when working with MongoDB. - -This guide uses Prisma ORM v6.19 to ensure full compatibility with MongoDB. - -::: - -:::tip - -If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/v6/guides/migrate-from-mongoose). - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/v6/orm/more/upgrades/to-v7#minimum-supported-nodejs--typescript-versions) for officially supported versions) -- An existing TypeScript project with a `package.json` file -- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). - -:::warning - -The MongoDB database connector uses transactions to support nested writes. Transactions **requires** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. - -::: - -Make sure you have your database [connection URL](/v6/orm/reference/connection-urls) (that includes your authentication credentials) at hand! - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma@6.19 @types/node --save-dev -``` - -```npm -npm install @prisma/client@6.19 dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`dotenv`** - Loads environment variables from your `.env` file - -:::info[Why Prisma v6.19?] - -This is the latest stable version of Prisma ORM v6 that fully supports MongoDB. MongoDB support for Prisma ORM v7 is coming soon. - -You can also install `prisma@6` and `@prisma/client@6` to automatically get the latest v6 release. - -::: - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mongodb --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - engine: "classic", - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: - -```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", - }, - engine: "classic", - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -## 3. Connect your database - -Update the `.env` file with your MongoDB connection URL: - -```bash title=".env" -DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb" -``` - -For MongoDB Atlas, the connection URL format is: - -``` -mongodb+srv://USERNAME:PASSWORD@CLUSTER.mongodb.net/DATABASE -``` - -Self-hosted MongoDB connection URL format: - -``` -mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE -``` - -Connection URL components: - -- **`USERNAME`**: Your database user name -- **`PASSWORD`**: Your database user password -- **`HOST`**: The host where [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos) is running -- **`PORT`**: The port where your database server is running (typically `27017`) -- **`DATABASE`**: The name of your database - -:::tip - -For MongoDB Atlas, you can manually append the database name to the connection URL, as Atlas doesn't include it by default. - -::: - -### Troubleshooting connection issues - -#### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -#### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/web/issues/5562). - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command: - -- Reads the `DATABASE_URL` from your `.env` file -- Connects to your MongoDB database -- Samples documents in your collections to infer the schema -- Generates Prisma models in your `schema.prisma` file - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -:::info - -**MongoDB introspection limitations:** Prisma introspects MongoDB by sampling documents. You may need to manually: - -- Add relation fields using the `@relation` attribute -- Adjust field types if the sampling didn't capture all variations -- Add indexes and constraints not detected during introspection - -::: - -## 5. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 6. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaClient } from "../generated/prisma/client"; - -const prisma = new PrismaClient(); - -export { prisma }; -``` - -## 7. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a collection - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 8. Evolve your schema - -MongoDB doesn't support migrations like relational databases. Instead, use `db push` to sync schema changes: - -### 8.1. Update your Prisma schema file - -Modify your Prisma schema file with the changes you want. For example, add a new model: - -```prisma title="prisma/schema.prisma" -model Post { // [!code ++] - id String @id @default(auto()) @map("_id") @db.ObjectId // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - authorId String @db.ObjectId // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] -} // [!code ++] - -model User { // [!code ++] - id String @id @default(auto()) @map("_id") @db.ObjectId // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -:::info - -In MongoDB, the `id` field is mapped to `_id` and uses `@db.ObjectId` type. Relations use `String` type with `@db.ObjectId` annotation. - -::: - -### 8.2. Push the changes to your database - -```npm -npx prisma db push -``` - -This command: - -- Applies schema changes to your MongoDB database -- Automatically regenerates Prisma Client - -:::info[Why `db push` instead of migrations?] - -MongoDB uses a flexible schema model. Prisma Migrate (which creates migration files) is not supported for MongoDB. Always use `prisma db push` to sync your schema changes. - -::: - -## 9. Explore your data - -You can use [MongoDB Atlas](https://www.mongodb.com/cloud/atlas), the MongoDB shell, or MongoDB Compass to view and manage your data. - -[Prisma Studio](/v6/orm/tools/prisma-studio) does not currently support MongoDB. Support may be added in a future release. See [Databases supported by Prisma Studio](/v6/orm/tools/prisma-studio#databases-supported-by-prisma-studio) for more information. - -## Next steps - -## More info - -- [MongoDB database connector](/v6/orm/overview/databases/mongodb) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mysql.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mysql.mdx deleted file mode 100644 index cf66a88ed2..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/mysql.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: MySQL -description: 'Add Prisma ORM to an existing TypeScript project with MySQL and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/mysql -metaTitle: How to add Prisma ORM to an existing project using MySQL (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with MySQL and learn database introspection, baselining, and querying.' ---- - -[MySQL](https://www.mysql.com/) is a widely-used open-source relational database management system known for its speed, reliability, and ease of use. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to MySQL, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-mariadb dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-mariadb`** - The MySQL/MariaDB driver adapter that connects Prisma Client to your database -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mysql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" -} -``` - -## 3. Connect your database - -Update the `.env` file with your MySQL connection string details: - -```bash title=".env" -DATABASE_URL="mysql://username:password@localhost:3306/mydb" -DATABASE_USER="username" # [!code ++] -DATABASE_PASSWORD="password" # [!code ++] -DATABASE_NAME="mydb" # [!code ++] -DATABASE_HOST="localhost" # [!code ++] -DATABASE_PORT=3306 # [!code ++] -``` - -Replace the placeholders with your actual database credentials: - -- `username`: Your MySQL username -- `password`: Your MySQL password -- `localhost:3306`: Your MySQL host and port -- `mydb`: Your database name - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaMariaDb } from "@prisma/adapter-mariadb"; -import { PrismaClient } from "../generated/prisma/client"; - -const adapter = new PrismaMariaDb({ - host: process.env.DATABASE_HOST, - user: process.env.DATABASE_USER, - password: process.env.DATABASE_PASSWORD, - database: process.env.DATABASE_NAME, - connectionLimit: 5, -}); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [MySQL database connector](/v6/orm/overview/databases/mysql) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/planetscale.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/planetscale.mdx deleted file mode 100644 index 2f1d64b491..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/planetscale.mdx +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: PlanetScale -description: Add Prisma ORM to an existing TypeScript project with PlanetScale MySQL and learn database introspection and querying. -url: /v6/prisma-orm/add-to-existing-project/planetscale -metaTitle: How to add Prisma ORM to an existing project using PlanetScale MySQL (15 min) -metaDescription: Add Prisma ORM to an existing TypeScript project with PlanetScale MySQL and learn database introspection and querying. ---- - -[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale MySQL**, which is built on Vitess and offers database branching, non-blocking schema changes, and automatic backups. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PlanetScale MySQL, introspect your existing database schema, and start querying with type-safe Prisma Client. - -:::note - -PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [Add to existing PostgreSQL project guide](/v6/prisma-orm/add-to-existing-project/postgresql) instead. - -::: - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-planetscale undici dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-planetscale`** - The PlanetScale driver adapter that connects Prisma Client to your database -- **`undici`** - A fast HTTP/1.1 client required by the PlanetScale adapter -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mysql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" - relationMode = "prisma" -} -``` - -:::info - -PlanetScale requires `relationMode = "prisma"` because it doesn't support foreign key constraints. - -::: - -## 3. Connect your database - -Update the `.env` file with your PlanetScale connection URL: - -```bash title=".env" -DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict" -``` - -You can find your connection string in the PlanetScale dashboard. - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 6. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPlanetScale } from "@prisma/adapter-planetscale"; -import { PrismaClient } from "../generated/prisma/client"; -import { fetch as undiciFetch } from "undici"; - -const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 7. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 8. Evolve your schema - -PlanetScale uses a branching workflow instead of traditional migrations. To make changes to your database schema: - -### 8.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 8.2. Push the changes to your development branch: - -```npm -npx prisma db push -``` - -This command will: - -- Apply the schema changes to your PlanetScale database -- Regenerate Prisma Client - -:::info - -For production deployments, use PlanetScale's [branching workflow](https://planetscale.com/docs/concepts/branching) to create deploy requests. - -::: - -## 9. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [PlanetScale database connector](/v6/orm/overview/databases/planetscale) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [PlanetScale branching workflow](https://planetscale.com/docs/concepts/branching) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/postgresql.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/postgresql.mdx deleted file mode 100644 index 15253192f5..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/postgresql.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: PostgreSQL -description: 'Add Prisma ORM to an existing TypeScript project with PostgreSQL and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/postgresql -metaTitle: How to add Prisma ORM to an existing project using PostgreSQL (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with PostgreSQL and learn database introspection, baselining, and querying.' ---- - -[PostgreSQL](https://www.postgresql.org/) is a popular open-source relational database known for its reliability, feature robustness, and performance. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PostgreSQL, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider postgresql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} -``` - -## 3. Connect your database - -Update the `.env` file with your PostgreSQL connection URL: - -```bash title=".env" -DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public" -``` - -The [format of the connection URL](/v6/orm/reference/connection-urls) for PostgreSQL looks as follows: - -``` -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [PostgreSQL database connector](/v6/orm/overview/databases/postgresql) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/prisma-postgres.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/prisma-postgres.mdx deleted file mode 100644 index 45ac3fbb55..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/prisma-postgres.mdx +++ /dev/null @@ -1,240 +0,0 @@ ---- -title: Prisma Postgres -description: 'Add Prisma ORM to an existing TypeScript project with Prisma Postgres and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/prisma-postgres -metaTitle: How to add Prisma ORM to an existing project using Prisma Postgres (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with Prisma Postgres and learn database introspection, baselining, and querying.' ---- - -[Prisma Postgres](/v6/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to Prisma Postgres, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider postgresql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} -``` - -## 3. Connect your database - -Update the `.env` file with your Prisma Postgres connection URL: - -```bash title=".env" -DATABASE_URL="postgresql://user:password@host:5432/database?schema=public" -``` - -Replace the placeholder values with your actual Prisma Postgres connection details. - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip - -If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/v6/postgres/database/serverless-driver#use-with-prisma-orm). - -::: - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [Prisma Postgres documentation](/v6/postgres) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) -- [Cache your queries](/v6/postgres/database/caching#setting-up-caching-in-prisma-postgres) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sql-server.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sql-server.mdx deleted file mode 100644 index 57d98dd0c2..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sql-server.mdx +++ /dev/null @@ -1,255 +0,0 @@ ---- -title: SQL Server -description: 'Add Prisma ORM to an existing TypeScript project with SQL Server and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/sql-server -metaTitle: How to add Prisma ORM to an existing project using SQL Server (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with SQL Server and learn database introspection, baselining, and querying.' ---- - -[SQL Server](https://www.microsoft.com/en-us/sql-server) is Microsoft's enterprise relational database management system known for its performance, security, and integration with Microsoft tools. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to SQL Server, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node @types/mssql --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-mssql dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-mssql`** - The SQL Server driver adapter that connects Prisma Client to your database -- **`dotenv`** - Loads environment variables from your `.env` file -- **`@types/mssql`** - TypeScript type definitions for mssql - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider sqlserver --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlserver" -} -``` - -## 3. Connect your database - -Update the `.env` file with your SQL Server connection string details: - -```bash title=".env" -DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=username;password=password;encrypt=true" -DB_USER="username" # [!code ++] -DB_PASSWORD="password" # [!code ++] -DB_NAME="mydb" # [!code ++] -HOST="localhost" # [!code ++] -``` - -Replace the placeholders with your actual database credentials: - -- `localhost:1433`: Your SQL Server host and port -- `mydb`: Your database name -- `username`: Your SQL Server username -- `password`: Your SQL Server password - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaMssql } from "@prisma/adapter-mssql"; -import { PrismaClient } from "../generated/prisma/client"; - -const sqlConfig = { - user: process.env.DB_USER, - password: process.env.DB_PASSWORD, - database: process.env.DB_NAME, - server: process.env.HOST, - pool: { - max: 10, - min: 0, - idleTimeoutMillis: 30000, - }, - options: { - encrypt: true, // for azure - trustServerCertificate: false, // change to true for local dev / self-signed certs - }, -}; - -const adapter = new PrismaMssql(sqlConfig); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [SQL Server database connector](/v6/orm/overview/databases/sql-server) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sqlite.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sqlite.mdx deleted file mode 100644 index d28f175c12..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/add-to-existing-project/sqlite.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: SQLite -description: 'Add Prisma ORM to an existing TypeScript project with SQLite and learn database introspection, baselining, and querying.' -url: /v6/prisma-orm/add-to-existing-project/sqlite -metaTitle: How to add Prisma ORM to an existing project using SQLite (15 min) -metaDescription: 'Add Prisma ORM to an existing TypeScript project with SQLite and learn database introspection, baselining, and querying.' ---- - -[SQLite](https://sqlite.org) is a lightweight, file-based database that's perfect for development, prototyping, and small applications. It requires no setup and stores data in a local file. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to SQLite, introspect your existing database schema, and start querying with type-safe Prisma Client. - -## Prerequisites - -## 1. Set up Prisma ORM - -Navigate to your existing project directory and install the required dependencies: - -```npm -npm install prisma @types/node @types/better-sqlite3 --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-better-sqlite3 dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-better-sqlite3`** - The SQLite driver adapter that connects Prisma Client to your database -- **`@types/better-sqlite3`** - TypeScript type definitions for better-sqlite3 -- **`dotenv`** - Loads environment variables from your `.env` file - -## 2. Initialize Prisma ORM - -Set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider sqlite --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlite" -} -``` - -A `.env` file should be created with the following value: - -```text title=".env" -DATABASE_URL="file:./dev.db" -``` - -## 3. Connect your database - -Update the `.env` file to point to your existing SQLite database file: - -```bash title=".env" -DATABASE_URL="file:./path/to/your/database.db" -``` - -## 4. Introspect your database - -Run the following command to introspect your existing database: - -```npm -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -After introspection, your Prisma schema will contain models that represent your existing database tables. - -## 5. Baseline your database - -To use Prisma Migrate with your existing database, you need to [baseline your database](/v6/orm/prisma-migrate/getting-started). - -First, create a `migrations` directory: - -```bash -mkdir -p prisma/migrations/0_init -``` - -Next, generate the migration file with `prisma migrate diff`: - -```npm -npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -Review the generated migration file to ensure it matches your database schema. - -Then, mark the migration as applied: - -```npm -npx prisma migrate resolve --applied 0_init -``` - -You now have a baseline for your current database schema. - -## 6. Generate Prisma ORM types - -Generate Prisma Client based on your introspected schema: - -```npm -npx prisma generate -``` - -This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. - -## 7. Instantiate Prisma Client - -Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaBetterSqlite3({ url: connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip[Using SQLite with Bun] -Bun doesn't support the native SQLite driver that `better-sqlite3` relies on (see the [`node:sqlite` reference](https://bun.com/reference/node/sqlite)). When targeting Bun, use the `@prisma/adapter-libsql` adapter instead: - -```ts -import "dotenv/config"; -import { PrismaLibSql } from "@prisma/adapter-libsql"; -import { PrismaClient } from "../generated/prisma/client"; - -const adapter = new PrismaLibSql({ - url: process.env.DATABASE_URL ?? "", -}); - -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -::: - -## 8. Query your database - -Now you can use Prisma Client to query your database. Create a `script.ts` file: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Example: Fetch all records from a table - // Replace 'user' with your actual model name - const allUsers = await prisma.user.findMany(); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -## 9. Evolve your schema - -To make changes to your database schema: - -### 9.1. Update your Prisma schema file - -Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: - -```prisma title="prisma/schema.prisma" -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 ++] - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] -``` - -### 9.2. Create and apply a migration: - -```npm -npx prisma migrate dev --name your_migration_name -``` - -This command will: - -- Create a new SQL migration file -- Apply the migration to your database -- Regenerate Prisma Client - -## 10. Explore your data with Prisma Studio - -:::note[SQLite requirements for Prisma Studio] - -- File paths must have a `file:` protocol right now in the database url for SQLite -- **Node.js 22.5+**: Works out of the box with the built-in `node:sqlite` module - - May require `NODE_OPTIONS=--experimental-sqlite` environment variable -- **Node.js 20**: Requires installing `better-sqlite3` as a dependency - - If using pnpm 10+ with `pnpx`, you'll need the [`--allow-build=better-sqlite3`](https://pnpm.io/cli/dlx#--allow-build) flag -- **Deno >= 2.2**: Supported via [built-in SQLite module](https://docs.deno.com/api/node/sqlite/) -- **Bun**: Support for Prisma Studio with SQLite is coming soon and is not available yet - -::: - -:::tip[Using `npx` with `better-sqlite3`] - -If you don't have `node:sqlite` available in your runtime or prefer not to install `better-sqlite3` as a hard dependency (it adds ~10MB), you can use `npx` to temporarily install the required packages: - -```npm -npx -p better-sqlite3 -p prisma prisma studio --url file:./path/to/your/database.db -``` - -This command: - -- Temporarily installs `better-sqlite3` without adding it to your project dependencies -- Runs Prisma Studio with the specified SQLite database file -- Avoids the 10MB overhead of `better-sqlite3` in your project - -::: - -## Next steps - -## More info - -- [SQLite database connector](/v6/orm/overview/databases/sqlite) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database introspection](/v6/orm/prisma-schema/introspection) -- [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/meta.json b/apps/docs/content/docs.v6/(index)/prisma-orm/meta.json deleted file mode 100644 index 1ee958a0a6..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "title": "Prisma ORM", - "defaultOpen": true, - "pages": ["quickstart", "add-to-existing-project"] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/cockroachdb.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/cockroachdb.mdx deleted file mode 100644 index d0550be9ab..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/cockroachdb.mdx +++ /dev/null @@ -1,255 +0,0 @@ ---- -title: CockroachDB -description: Create a new TypeScript project from scratch by connecting Prisma ORM to CockroachDB and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/cockroachdb -metaTitle: 'Quickstart: Prisma ORM with CockroachDB (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to CockroachDB and generating a Prisma Client for database access. ---- - -[CockroachDB](https://www.cockroachlabs.com) is a distributed SQL database built for cloud applications. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to CockroachDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -You also need: - -- A [CockroachDB](https://www.cockroachlabs.com/) database -- Database connection string from CockroachDB - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible) -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider cockroachdb --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "cockroachdb" -} -``` - -Update your `.env` file with your CockroachDB connection string: - -```text title=".env" -DATABASE_URL="postgresql://username:password@host:26257/mydb?sslmode=require" -``` - -Replace with your actual CockroachDB connection string from your cluster dashboard. - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "cockroachdb" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data - -Explore the options suggested by [CockroachDB](https://www.cockroachlabs.com/blog/cockroachdb-gui-options/) to view and manage your data. - -[Prisma Studio](/v6/orm/tools/prisma-studio) does not currently support CockroachDB. Support may be added in a future release. See [Databases supported by Prisma Studio](/v6/orm/tools/prisma-studio#databases-supported-by-prisma-studio) for more information. - -## Next steps - -## More info - -- [CockroachDB database connector](/v6/orm/overview/databases/cockroachdb) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/meta.json b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/meta.json deleted file mode 100644 index c7c3975061..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Quickstart", - "pages": [ - "prisma-postgres", - "sqlite", - "postgresql", - "mysql", - "sql-server", - "planetscale", - "cockroachdb", - "mongodb" - ] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mongodb.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mongodb.mdx deleted file mode 100644 index 6ce4c00fda..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mongodb.mdx +++ /dev/null @@ -1,311 +0,0 @@ ---- -title: MongoDB -description: Create a new TypeScript project from scratch by connecting Prisma ORM to MongoDB and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/mongodb -metaTitle: 'Quickstart: Prisma ORM with MongoDB (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to MongoDB and generating a Prisma Client for database access. ---- - -[MongoDB](https://www.mongodb.com) is a popular NoSQL document database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MongoDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -:::warning[MongoDB support for Prisma ORM v7] - -**MongoDB support for Prisma ORM v7 is coming in the near future.** In the meantime, please use **Prisma ORM v6.19** (the latest v6 release) when working with MongoDB. - -This guide uses Prisma ORM v6.19 to ensure full compatibility with MongoDB. - -::: - -## Prerequisites - -- Node.js installed in your system [with the supported version](/v6/orm/more/upgrades/to-v7#minimum-supported-nodejs--typescript-versions) -- A [MongoDB](https://www.mongodb.com/) database accessible via connection string - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma@6.19 @types/node --save-dev -``` - -```npm -npm install @prisma/client@6.19 dotenv -``` - -:::info[Why Prisma v6.19?] - -This is the latest stable version of Prisma ORM v6 that fully supports MongoDB. MongoDB support for Prisma ORM v7 is coming soon. - -You can also install `prisma@6` and `@prisma/client@6` to automatically get the latest v6 release. - -::: - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db push`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`dotenv`** - Loads environment variables from your `.env` file - -:::note - -MongoDB doesn't require driver adapters since Prisma ORM connects directly to MongoDB. - -::: - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mongodb --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file for your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -:::note - -Prisma Client will be generated in the `generated/prisma/` directory when you run `npx prisma generate` later in this guide. - -::: - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - engine: "classic", - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: - -```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", - }, - engine: "classic", - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -Update your `.env` file with your MongoDB connection string: - -```text title=".env" -DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb" -``` - -:::tip - -Replace `username`, `password`, `cluster`, and `mydb` with your actual MongoDB credentials and database name. You can get your connection string from [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) or your MongoDB deployment. - -::: - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -model User { // [!code ++] - id String @id @default(auto()) @map("_id") @db.ObjectId // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id String @id @default(auto()) @map("_id") @db.ObjectId // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId String @db.ObjectId // [!code ++] -} // [!code ++] -``` - -## 6. Push your schema to MongoDB - -MongoDB doesn't support migrations like relational databases. Instead, use `db push` to sync your schema: - -```npm -npx prisma db push -``` - -This command: - -- Creates the collections in MongoDB based on your schema -- Automatically generates Prisma Client - -:::info - -Unlike relational databases, MongoDB uses a flexible schema. The `db push` command ensures your Prisma schema is reflected in your database without creating migration files. - -::: - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaClient } from "../generated/prisma/client"; - -const prisma = new PrismaClient(); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data - -You can use [MongoDB Atlas](https://www.mongodb.com/cloud/atlas), the MongoDB shell, or MongoDB Compass to view and manage your data. - -[Prisma Studio](/v6/orm/tools/prisma-studio) does not currently support MongoDB. Support may be added in a future release. See [Databases supported by Prisma Studio](/v6/orm/tools/prisma-studio#databases-supported-by-prisma-studio) for more information. - -## Next steps - -## Troubleshooting - -### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/web/issues/5562). - -## More info - -- [MongoDB database connector](/v6/orm/overview/databases/mongodb) -- [MongoDB data modeling patterns](/v6/orm/overview/databases/mongodb#type-mapping-between-mongodb-and-the-prisma-schema) -- [MongoDB deployment considerations](/v6/orm/overview/databases/mongodb#differences-to-connectors-for-relational-databases) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mysql.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mysql.mdx deleted file mode 100644 index fd99c562a8..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/mysql.mdx +++ /dev/null @@ -1,268 +0,0 @@ ---- -title: MySQL -description: Create a new TypeScript project from scratch by connecting Prisma ORM to MySQL and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/mysql -metaTitle: 'Quickstart: Prisma ORM with MySQL (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to MySQL and generating a Prisma Client for database access. ---- - -[MySQL](https://www.mysql.com) is a popular open-source relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -:::note - -This guide also applies to **MariaDB**, which is MySQL-compatible. - -::: - -## Prerequisites - -You also need: - -- A [MySQL](https://www.mysql.com/) database server running and accessible -- Database connection details (host, port, username, password, database name) - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-mariadb dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-mariadb`** - The MySQL/MariaDB driver adapter that connects Prisma Client to your database -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mysql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" -} -``` - -Update your `.env` file with your MySQL connection string details: - -```bash title=".env" -DATABASE_URL="mysql://username:password@localhost:3306/mydb" -DATABASE_USER="username" # [!code ++] -DATABASE_PASSWORD="password" # [!code ++] -DATABASE_NAME="mydb" # [!code ++] -DATABASE_HOST="localhost" # [!code ++] -DATABASE_PORT=3306 # [!code ++] -``` - -Replace the placeholders with your actual database credentials: - -- `username`: Your MySQL username -- `password`: Your MySQL password -- `localhost:3306`: Your MySQL host and port -- `mydb`: Your database name - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? @db.Text // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaMariaDb } from "@prisma/adapter-mariadb"; -import { PrismaClient } from "../generated/prisma/client"; - -const adapter = new PrismaMariaDb({ - host: process.env.DATABASE_HOST, - user: process.env.DATABASE_USER, - password: process.env.DATABASE_PASSWORD, - database: process.env.DATABASE_NAME, - connectionLimit: 5, -}); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [MySQL database connector](/v6/orm/overview/databases/mysql) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/planetscale.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/planetscale.mdx deleted file mode 100644 index fbdf42e1a1..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/planetscale.mdx +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: PlanetScale -description: Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale MySQL and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/planetscale -metaTitle: 'Quickstart: Prisma ORM with PlanetScale MySQL (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale MySQL and generating a Prisma Client for database access. ---- - -[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale MySQL**. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PlanetScale MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -:::note - -PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [PostgreSQL quickstart guide](/v6/prisma-orm/quickstart/postgresql) instead. - -::: - -## Prerequisites - -You also need: - -- A [PlanetScale](https://planetscale.com) database -- Database connection string from PlanetScale - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-planetscale undici dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-planetscale`** - The PlanetScale driver adapter that connects Prisma Client to your database -- **`undici`** - A fast HTTP/1.1 client required by the PlanetScale adapter -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider mysql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" -} -``` - -Update your schema to include `relationMode = "prisma"` for PlanetScale: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" - relationMode = "prisma" -} -``` - -Update your `.env` file with your PlanetScale connection string: - -```text title=".env" -DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict" -``` - -Replace with your actual PlanetScale connection string from your database dashboard. - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "mysql" - relationMode = "prisma" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? @db.Text // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] - - @@index([authorId]) // [!code ++] -} // [!code ++] -``` - -:::note - -Note the `@@index([authorId])` on the `Post` model. PlanetScale requires indexes on foreign keys when using `relationMode = "prisma"`. - -::: - -## 6. Push your schema to PlanetScale - -PlanetScale uses a branching workflow instead of traditional migrations. Push your schema directly: - -```npm -npx prisma db push -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPlanetScale } from "@prisma/adapter-planetscale"; -import { PrismaClient } from "../generated/prisma/client"; -import { fetch as undiciFetch } from "undici"; - -const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -Prisma Studio is a visual editor for your database. Launch it with: - -```shell -npx prisma studio -``` - -This opens a web interface where you can view and edit your data. - -:::info[Supported databases] - -Prisma Studio currently supports PostgreSQL, MySQL, and SQLite. For more details, see [Databases supported by Prisma Studio](/studio#supported-databases). - -::: - -## Next steps - -## More info - -- [PlanetScale database connector](/v6/orm/overview/databases/planetscale) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/postgresql.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/postgresql.mdx deleted file mode 100644 index 4a4e5d81b3..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/postgresql.mdx +++ /dev/null @@ -1,270 +0,0 @@ ---- -title: PostgreSQL -description: Create a new TypeScript project from scratch by connecting Prisma ORM to PostgreSQL and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/postgresql -metaTitle: 'Quickstart: Prisma ORM with PostgreSQL (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to PostgreSQL and generating a Prisma Client for database access. ---- - -[PostgreSQL](https://www.postgresql.org) is a powerful, open-source relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PostgreSQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -You also need: - -- A [PostgreSQL](https://www.postgresql.org/) database server running and accessible -- Database connection details (host, port, username, password, database name) - -:::tip[Need a PostgreSQL database?] - -If you don't already have a PostgreSQL database, follow the quickstart to set up a production-ready [Prisma Postgres](/v6/prisma-orm/quickstart/prisma-postgres) database with Prisma ORM in a new project. - -::: - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider postgresql --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} -``` - -Update your `.env` file with your PostgreSQL connection string: - -```text title=".env" -DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public" -``` - -Replace the placeholders with your actual database credentials: - -- `username`: Your PostgreSQL username -- `password`: Your PostgreSQL password -- `localhost:5432`: Your PostgreSQL host and port -- `mydb`: Your database name - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -## Next steps - -You've successfully set up Prisma ORM. Here's what you can explore next: - -- **Learn more about Prisma Client**: Explore the [Prisma Client API](/orm/prisma-client/setup-and-configuration/introduction) for advanced querying, filtering, and relations -- **Database migrations**: Learn about [Prisma Migrate](/orm/prisma-migrate) for evolving your database schema -- **Performance optimization**: Discover [query optimization techniques](/orm/prisma-client/queries/advanced/query-optimization-performance) -- **Build a full application**: Check out our [framework guides](/guides) to integrate Prisma ORM with Next.js, Express, and more -- **Join the community**: Connect with other developers on [Discord](https://pris.ly/discord) - -## More info - -- [PostgreSQL database connector](/v6/orm/overview/databases/postgresql) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/prisma-postgres.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/prisma-postgres.mdx deleted file mode 100644 index d7009d7758..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/prisma-postgres.mdx +++ /dev/null @@ -1,252 +0,0 @@ ---- -title: Prisma Postgres -description: Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/prisma-postgres -metaTitle: 'Quickstart: Prisma ORM with Prisma Postgres (5 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access. ---- - -[Prisma Postgres](/v6/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to Prisma Postgres using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM and create a Prisma Postgres database - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --db --output ../generated/prisma -``` - -:::info - -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database. - -::: - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a new Prisma Postgres database (when using `--db` flag) -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} -``` - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip - -If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/v6/postgres/database/serverless-driver#use-with-prisma-orm). - -::: - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [Prisma Postgres documentation](/v6/postgres) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) -- [Cache your queries](/v6/postgres/database/caching#setting-up-caching-in-prisma-postgres) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sql-server.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sql-server.mdx deleted file mode 100644 index 036a7c3f8d..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sql-server.mdx +++ /dev/null @@ -1,275 +0,0 @@ ---- -title: SQL Server -description: Create a new TypeScript project from scratch by connecting Prisma ORM to SQL Server and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/sql-server -metaTitle: 'Quickstart: Prisma ORM with SQL Server (10 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to SQL Server and generating a Prisma Client for database access. ---- - -[Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server) is an enterprise-grade relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to SQL Server using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -You also need: - -- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database - - [Microsoft SQL Server on Linux for Docker](/v6/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/v6/orm/overview/databases/sql-server/sql-server-local) -- Database connection details (host, port, username, password, database name) - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node @types/mssql --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-mssql dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-mssql`** - The SQL Server driver adapter that connects Prisma Client to your database -- **`@types/mssql`** - TypeScript type definitions for mssql -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider sqlserver --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlserver" -} -``` - -Update your `.env` file with your SQL Server connection string details: - -```bash title=".env" -DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=username;password=password;encrypt=true" -DB_USER="username" # [!code ++] -DB_PASSWORD="password" # [!code ++] -DB_NAME="mydb" # [!code ++] -HOST="localhost" # [!code ++] -``` - -Replace the placeholders with your actual database credentials: - -- `localhost:1433`: Your SQL Server host and port -- `mydb`: Your database name -- `username`: Your SQL Server username -- `password`: Your SQL Server password - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlserver" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaMssql } from "@prisma/adapter-mssql"; -import { PrismaClient } from "../generated/prisma/client"; - -const sqlConfig = { - user: process.env.DB_USER, - password: process.env.DB_PASSWORD, - database: process.env.DB_NAME, - server: process.env.HOST, - pool: { - max: 10, - min: 0, - idleTimeoutMillis: 30000, - }, - options: { - encrypt: true, // for azure - trustServerCertificate: false, // change to true for local dev / self-signed certs - }, -}; - -const adapter = new PrismaMssql(sqlConfig); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [SQL Server database connector](/v6/orm/overview/databases/sql-server) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sqlite.mdx b/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sqlite.mdx deleted file mode 100644 index 263ef82b41..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-orm/quickstart/sqlite.mdx +++ /dev/null @@ -1,296 +0,0 @@ ---- -title: SQLite -description: Create a new TypeScript project from scratch by connecting Prisma ORM to SQLite and generating a Prisma Client for database access. -url: /v6/prisma-orm/quickstart/sqlite -metaTitle: 'Quickstart: Prisma ORM with SQLite (5 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to SQLite and generating a Prisma Client for database access. ---- - -[SQLite](https://sqlite.org) is a lightweight, file-based database that's perfect for development, prototyping, and small applications. It requires no setup and stores data in a local file. - -In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to SQLite using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node @types/better-sqlite3 -D -``` - -```npm -npm install @prisma/client @prisma/adapter-better-sqlite3 dotenv -``` - -:::note[pnpm users with SQLite] -If using pnpm 10+ with `pnpx`, you'll need the [`--allow-build=better-sqlite3`](https://pnpm.io/cli/dlx#--allow-build) flag when running Prisma Studio due to SQLite's native dependency requirements. -::: - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-better-sqlite3`** - The SQLite driver adapter that connects Prisma Client to your database -- **`@types/better-sqlite3`** - TypeScript type definitions for better-sqlite3 -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```npm -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --datasource-provider sqlite --output ../generated/prisma -``` - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a `.env` file in the root directory for environment variables -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlite" -} -``` - -A `.env` file should be created with the following value: - -```text title=".env" -DATABASE_URL="file:./dev.db" -``` - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "sqlite" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaBetterSqlite3({ url: connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip[Using SQLite with Bun] -When targeting Bun, use the `@prisma/adapter-libsql` adapter instead of `@prisma/adapter-better-sqlite3`. Bun doesn’t support the native SQLite driver that `better-sqlite3` relies on (see the [`node:sqlite` reference](https://bun.com/reference/node/sqlite)). Instantiate Prisma Client like so: - -```ts -import "dotenv/config"; -import { PrismaLibSql } from "@prisma/adapter-libsql"; -import { PrismaClient } from "../generated/prisma/client"; - -const adapter = new PrismaLibSql({ - url: process.env.DATABASE_URL ?? "", -}); - -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -::: - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -:::note[SQLite requirements for Prisma Studio] - -- File paths must have a `file:` protocol right now in the database url for SQLite -- **Node.js 22.5+**: Works out of the box with the built-in `node:sqlite` module - - May require `NODE_OPTIONS=--experimental-sqlite` environment variable -- **Node.js 20**: Requires installing `better-sqlite3` as a dependency - - If using pnpm 10+ with `pnpx`, you'll need the [`--allow-build=better-sqlite3`](https://pnpm.io/cli/dlx#--allow-build) flag -- **Deno >= 2.2**: Supported via [built-in SQLite module](https://docs.deno.com/api/node/sqlite/) -- **Bun**: Support for Prisma Studio with SQLite is coming soon and is not available yet - -::: - -:::tip[Using `npx` with `better-sqlite3`] - -If you don't have `node:sqlite` available in your runtime or prefer not to install `better-sqlite3` as a hard dependency (it adds ~10MB), you can use `npx` to temporarily install the required packages: - -```npm -npx -p better-sqlite3 -p prisma prisma studio --url file:./dev.db -``` - -This command: - -- Temporarily installs `better-sqlite3` without adding it to your project dependencies -- Runs Prisma Studio with the specified SQLite database file -- Avoids the 10MB overhead of `better-sqlite3` in your project - -::: - -## Next steps - -## More info - -- [SQLite database connector](/v6/orm/overview/databases/sqlite) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/from-the-cli.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/from-the-cli.mdx deleted file mode 100644 index d12d9d8a13..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/from-the-cli.mdx +++ /dev/null @@ -1,524 +0,0 @@ ---- -title: From the CLI -description: Start building a Prisma application with a Prisma Postgres database from the CLI -url: /v6/prisma-postgres/from-the-cli -metaTitle: From the CLI -metaDescription: Start building a Prisma application with a Prisma Postgres database from the CLI ---- - -This page provides a step-by-step guide for Prisma Postgres after setting it up with `prisma init --db`: - -1. Set up a TypeScript app with Prisma ORM -1. Migrate the schema of your database -1. Query your database from TypeScript - -## Prerequisites - -This guide assumes you set up [Prisma Postgres](/v6/postgres) instance with `prisma init --db`: - -```npm -npx prisma@latest init --db -``` - -```text no-copy wrap -✓ Select an authentication method Google -Authenticating to Prisma Platform via browser. - -Visit the following URL in your browser to authenticate: -https://console.prisma.io/auth/cli?state=eyJjb6ll... - -Successfully authenticated as jon@doe.com. -Let's set up your Prisma Postgres database! -✓ Select your region: ap-southeast-1 - Asia Pacific (Singapore) -✓ Enter a project name: My Prisma Project -✓ Success! Your Prisma Postgres database is ready ✅ - -We found an existing schema.prisma file in your current project directory. - ---- Database URL --- - -Connect Prisma ORM to your Prisma Postgres database with this URL: - ---- Next steps --- - -Go to https://pris.ly/ppg-init for detailed instructions. - -1. Install the Postgres adapter -npm install @prisma/adapter-pg - -...and add it to your Prisma Client instance: - -import { PrismaClient } from "./generated/prisma/client"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -2. Apply migrations -Run the following command to create and apply a migration: -npx prisma migrate dev - -3. Manage your data -View and edit your data locally by running this command: -npx prisma studio - -...or online in Console: -https://console.prisma.io/$path - -4. Send queries from your app -If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance. - -5. Learn more -For more info, visit the Prisma Postgres docs: https://pris.ly/ppg-docs -``` - -Once this command terminated: - -- You're logged into Prisma Data Platform. -- A new Prisma Postgres instance was created. -- The `prisma/` folder was created with an empty `schema.prisma` file. -- The `DATABASE_URL` env var was set in a `.env` file. -- The `prisma.config.ts` file was created with the default configuration. - -## 1. Organize your project directory - -:::note - -If you ran the `prisma init --db` command inside a folder where you want your project to live, you can skip this step and [proceed to the next section](/v6/prisma-postgres/from-the-cli#2-set-up-your-project). - -::: - -If you ran the command outside your intended project directory (e.g., in your home folder or another location), you need to move the generated `prisma` folder and the `.env` file into a dedicated project directory. - -Create a new folder (e.g. `hello-prisma`) where you want your project to live and move the necessary files into it: - -```bash -mkdir hello-prisma -mv .env ./hello-prisma/ -mv prisma ./hello-prisma/ -``` - -Navigate into your project folder: - -```bash -cd ./hello-prisma -``` - -Now that your project is in the correct location, continue with the setup. - -## 2. Set up your project - -### 2.1. Set up TypeScript - -Initialize a TypeScript project and add the Prisma CLI as a development dependency: - -```npm -npm init -y -``` - -```npm -npm install typescript tsx @types/node @types/pg -D -``` - -This creates a `package.json` file with an initial setup for your TypeScript app. - -Next, initialize TypeScript with a `tsconfig.json` file in the project: - -```npm -npx tsc --init -``` - -### 2.2. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -### 2.3. Set up Prisma ORM - -Install the required dependencies to use Prisma Postgres: - -```npm -npm install prisma --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma migrate` and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`pg`** - The node-postgres database driver -- **`@types/pg`** - TypeScript type definitions for node-postgres -- **`dotenv`** - Loads environment variables from your `.env` file - -### 2.4. Review the generated prisma.config.ts - -The `prisma init --db` command automatically created a `prisma.config.ts` file that looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -### 2.5. Create a script to query the database - -Create an `index.ts` file in the root directory, this will be used to query your application with Prisma ORM: - -```bash -touch index.ts -``` - -## 3. Migrate the database schema - -Update your `prisma/schema.prisma` file to include the `User` and `Post` models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] -} - -model Post { - id Int @id @default(autoincrement()) - title String - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} -``` - -After adding the models, migrate your database using [Prisma Migrate](/v6/orm/prisma-migrate/getting-started): - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 4. Send queries with Prisma ORM - -### 4.1. Instantiate Prisma Client - -Create a `lib/prisma.ts` file to instantiate Prisma Client with the driver adapter: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip - -If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/v6/postgres/database/serverless-driver#use-with-prisma-orm). - -::: - -### 4.2. Write your first query - -Paste the following boilerplate into `index.ts`: - -```ts title="index.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // ... you will write your Prisma ORM queries here -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -This code contains a `main` function that's invoked at the end of the script. It also instantiates `PrismaClient` which you'll use to send queries to your database. - -### 4.3. Create a new `User` record - -Let's start with a small query to create a new `User` record in the database and log the resulting object to the console. Add the following code to your `index.ts` file: - -```ts title="index.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - const user = await prisma.user.create({ - // [!code ++] - data: { - // [!code ++] - name: "Alice", // [!code ++] - email: "alice@prisma.io", // [!code ++] - }, // [!code ++] - }); // [!code ++] - console.log(user); // [!code ++] -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Next, execute the script with the following command: - -```npm -npx tsx index.ts -``` - -```text no-copy -{ id: 1, email: 'alice@prisma.io', name: 'Alice' } -``` - -Great job, you just created your first database record with Prisma Postgres! 🎉 - -### 4.4. Retrieve all `User` records - -Prisma ORM offers various queries to read data from your database. In this section, you'll use the `findMany` query that returns _all_ the records in the database for a given model. - -Delete the previous Prisma ORM query and add the new `findMany` query instead: - -```ts title="index.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - const users = await prisma.user.findMany(); // [!code ++] - console.log(users); // [!code ++] -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Execute the script again: - -```npm -npx tsx index.ts -``` - -```text no-copy -[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }] -``` - -Notice how the single `User` object is now enclosed with square brackets in the console. That's because the `findMany` returned an array with a single object inside. - -### 4.5. Explore relation queries - -One of the main features of Prisma ORM is the ease of working with [relations](/v6/orm/prisma-schema/data-model/relations). In this section, you'll learn how to create a `User` and a `Post` record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the `include` option. - -First, adjust your script to include the nested query: - -```ts title="index.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - const user = await prisma.user.create({ - // [!code ++] - data: { - // [!code ++] - name: "Bob", // [!code ++] - email: "bob@prisma.io", // [!code ++] - posts: { - // [!code ++] - create: [ - // [!code ++] - { - // [!code ++] - title: "Hello World", // [!code ++] - published: true, // [!code ++] - }, // [!code ++] - { - // [!code ++] - title: "My second post", // [!code ++] - content: "This is still a draft", // [!code ++] - }, // [!code ++] - ], // [!code ++] - }, // [!code ++] - }, // [!code ++] - }); // [!code ++] - console.log(user); // [!code ++] -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the query by executing the script again: - -```npm -npx tsx index.ts -``` - -```text no-copy -{ id: 2, email: 'bob@prisma.io', name: 'Bob' } -``` - -In order to also retrieve the `Post` records that belong to a `User`, you can use the `include` option via the `posts` relation field: - -```ts title="index.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - const usersWithPosts = await prisma.user.findMany({ - // [!code ++] - include: { - // [!code ++] - posts: true, // [!code ++] - }, // [!code ++] - }); // [!code ++] - console.dir(usersWithPosts, { depth: null }); // [!code ++] -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script again to see the results of the nested read query: - -```npm -npx tsx index.ts -``` - -```text no-copy -[ - { id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] }, - { - id: 2, - email: 'bob@prisma.io', - name: 'Bob', - posts: [ - { - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 2 - }, - { - id: 2, - title: 'My second post', - content: 'This is still a draft', - published: false, - authorId: 2 - } - ] - } -] -``` - -This time, you're seeing two `User` objects being printed. Both of them have a `posts` field (which is empty for `"Alice"` and populated with two `Post` objects for `"Bob"`) that represents the `Post` records associated with them. - -## Next steps - -You just got your feet wet with a basic Prisma Postgres setup. If you want to explore more complex queries, such as [adding caching functionality](/v6/postgres/database/caching#setting-up-caching-in-prisma-postgres), check out the official [Quickstart](/v6/prisma-orm/quickstart/prisma-postgres). - -### View and edit data in Prisma Studio - -Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command: - -```npm -npx prisma studio --config ./prisma.config.ts -``` - -With Prisma Postgres, you can also directly use Prisma Studio inside the [Console](https://console.prisma.io) by selecting the **Studio** tab in your project. - -### Build a fullstack app with Next.js - -Learn how to use Prisma Postgres in a fullstack app: - -- [Build a fullstack app with Next.js 15](/v6/guides/nextjs) -- [Next.js 15 example app](https://github.com/prisma/nextjs-prisma-postgres-demo) (including authentication) - -### Explore ready-to-run examples - -Check out the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more. - -These examples use SQLite by default but you can follow the instructions in the project README to switch to Prisma Postgres in a few simple steps. diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-mysql.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-mysql.mdx deleted file mode 100644 index 0ef8bda5de..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-mysql.mdx +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: Import from MySQL -description: Learn how to import data from an existing MySQL database into Prisma Postgres. -url: /v6/prisma-postgres/import-from-existing-database-mysql -metaTitle: Import from existing MySQL database into Prisma Postgres -metaDescription: Learn how to import data from an existing MySQL database into Prisma Postgres. ---- - -This guide provides step-by-step instructions for importing data from an existing MySQL database into Prisma Postgres. - -You can accomplish this migration in four steps: - -1. Create a new Prisma Postgres database. -1. Connect directly to a Prisma Postgres instance using a [direct connection](/v6/postgres/database/direct-connections). -1. Migrate your MySQL data to Prisma Postgres using [pgloader](https://pgloader.io/). -1. Configure your Prisma project for Prisma Postgres. - -## Prerequisites - -- The connection URL to your existing MySQL database. -- A [Prisma Data Platform](https://console.prisma.io) account. -- Node.js 18+ installed. -- [pgloader](https://pgloader.io/) installed. - -:::info[Make sure your PostgreSQL tools match the Prisma Postgres version] - -Prisma Postgres runs PostgreSQL 17. Your `pgloader` and any other PostgreSQL tools you use need to be compatible with PostgreSQL 17. - -::: - -We recommend attempting this migration in a separate git development branch. - -## 1. Create a new Prisma Postgres database - -Follow these steps to create a new Prisma Postgres database: - -1. Log in to [Prisma Data Platform](https://console.prisma.io/) and open the Console. -1. In a [workspace](/v6/platform/about#workspace) of your choice, click the **New project** button. -1. Type a name for your project in the **Name** field, e.g. **hello-ppg**. -1. In the **Prisma Postgres** section, click the **Get started** button. -1. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. -1. Click the **Create project** button. - -Once your database was provisioned, find your direct Prisma Postgres connection string: - -1. Navigate to your active Prisma Postgres instance. -1. Click the **API Keys** tab in the project's sidenav. -1. Click the **Create API key** button. -1. In the popup, provide a **Name** for the API key and click **Create**. -1. Copy the connection string starting with `postgres://`, this is your direct connection string. - -Save the connection string, you'll need it in the next step. - -## 2. Prepare your direct connection string - -In this step, you'll use the [direct connection string](/v6/postgres/database/direct-connections) you obtained in step 1 to connect to your Prisma Postgres instance. - -Your direct connection string should look like this: - -```text -postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require -``` - -You'll use this connection string in the next step when configuring pgloader. - -## 3. Migrate your MySQL data to Prisma Postgres using pgloader - -Now that you have an active connection to your Prisma Postgres instance, you'll use [pgloader](https://pgloader.io/) to export data from your MySQL database to Prisma Postgres. - -Open a separate terminal window and create a `config.load` file: - -```bash -touch config.load -``` - -Open the `config.load` file in your preferred text editor and copy-paste the following configuration: - -```text title="config.load" -LOAD DATABASE - FROM mysql://username:password@host:PORT/database_name - INTO postgres://__USER__:__PASSWORD__@db.prisma.io:5432/?sslmode=require - -WITH quote identifiers, -- preserve table/column name case by quoting them - include drop, - create tables, - create indexes, - reset sequences - -ALTER SCHEMA 'database_name' RENAME TO 'public'; -``` - -Make sure to update the following details in the `config.load` file: - -- `FROM` url (MySQL database URL): - - Replace `username`, `password`, `host`, `PORT`, and `database_name` with the actual connection details for your MySQL database. - - Ensure that your connection string includes `useSSL=true` if SSL is required, for example: `mysql://username:password@host:PORT/database_name?useSSL=true`. Note that when using PlanetScale, appending `sslaccept=strict` will not work. -- `INTO` url (Postgres database URL): - - Update this with your direct connection string from above, replacing the `__USER__` and `__PASSWORD__` placeholders. -- Update the `database_name` in `ALTER SCHEMA 'database_name' RENAME TO 'public';` to exactly match the `database_name` in your MySQL connection string. - -After saving the configuration file with your updated credentials, in the same terminal window, execute the following command: - -```bash -pgloader config.load -``` - -You should see a log similar to this, which confirms the successful migration of your data: - -```bash -LOG report summary reset - table name errors rows bytes total time -------------------------- --------- --------- --------- -------------- - fetch meta data 0 9 2.546s - Create Schemas 0 0 0.325s - Create SQL Types 0 0 0.635s - Create tables 0 6 5.695s - Set Table OIDs 0 3 0.328s -------------------------- --------- --------- --------- -------------- - public.post 0 8 0.5 kB 4.255s - public."user" 0 4 0.1 kB 2.775s -public._prisma_migrations 0 1 0.2 kB 4.278s -------------------------- --------- --------- --------- -------------- - COPY Threads Completion 0 4 5.095s - Index Build Completion 0 5 9.601s - Create Indexes 0 5 4.116s - Reset Sequences 0 2 4.540s - Primary Keys 0 3 2.917s - Create Foreign Keys 0 1 1.121s - Create Triggers 0 0 0.651s - Install Comments 0 0 0.000s -------------------------- --------- --------- --------- -------------- - Total import time ✓ 13 0.8 kB 28.042s -``` - -If you see output like this, it means your data has been successfully exported to your Prisma Postgres instance. - -:::note - -You also can use [Prisma Studio](/v6/postgres/integrations/viewing-data#viewing-and-editing-data-in-prisma-studio) and verify whether the migration was successful: - -```npm -npx prisma studio -``` - -::: - -## 4. Configure your Prisma project for Prisma Postgres - -After migrating your data, you need to set up your Prisma project to work with Prisma Postgres. The steps differ depending on whether you were already using Prisma ORM. - -### If you **were not** previously using Prisma ORM - -Initialize Prisma in your project by running `npx prisma init` in your project directory. This creates a `prisma` folder with a `schema.prisma` file and `.env` file (if not already present). - -In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/v6/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): - -```bash title=".env" no-copy -DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" -``` - -[Introspect](/v6/orm/prisma-schema/introspection) your newly migrated database by running: - -```npm -npx prisma db pull -``` - -This command updates your `schema.prisma` file with models representing your migrated tables, so you can start using [Prisma Client](/v6/orm/prisma-client/setup-and-configuration/introduction) to query your data or [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) to manage future changes. - -Congratulations! You've successfully migrated your MySQL database to Prisma Postgres and configured your Prisma project. Your migration tutorial is now complete. - -:::note - -For a comprehensive guide on getting started with Prisma and Prisma Postgres, see [start from scratch with Prisma and Prisma Postgres](/v6/prisma-orm/quickstart/prisma-postgres). - -::: - -### If you **were** already using Prisma ORM - -In your `schema.prisma` file, change the `provider` in the `datasource` block from `mysql` to `postgresql`: - -```prisma title="schema.prisma" -datasource db { - provider = "mysql" // [!code --] - provider = "postgres" // [!code ++] -} -``` - -In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/v6/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): - -```bash title=".env" no-copy -DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" -``` - -Introspect your newly migrated Prisma Postgres database and generate Prisma Client: - -```npm -npx prisma db pull -``` - -This command refreshes your Prisma models based on the new database schema. - -If you were using [Prisma Migrate](/v6/orm/prisma-migrate/getting-started) before: - -- Delete your existing `migrations` folder in the `prisma` directory. -- [Baseline your database](/v6/orm/prisma-migrate/workflows/baselining#baselining-a-database) to begin creating new migrations. - -Congratulations! You've successfully migrated your MySQL database to Prisma Postgres and configured your Prisma project. Your migration tutorial is now complete. - -If you encounter any issues during the migration, please don't hesitate to reach out to us on [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=conclusion) or via [X](https://pris.ly/x?utm_source=docs&utm_medium=conclusion). diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-postgresql.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-postgresql.mdx deleted file mode 100644 index d41ab26648..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/import-from-existing-database-postgresql.mdx +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Import from PostgreSQL -description: Learn how to import data from an existing PostgreSQL database into Prisma Postgres. -url: /v6/prisma-postgres/import-from-existing-database-postgresql -metaTitle: Import from existing Postgres database into Prisma Postgres -metaDescription: Learn how to import data from an existing PostgreSQL database into Prisma Postgres. ---- - -This guide provides step-by-step instructions for importing data from an existing PostgreSQL database into Prisma Postgres. - -You can accomplish this migration in three steps: - -1. Create a new Prisma Postgres database. -1. Export your existing data via `pg_dump`. -1. Import the previously exported data into Prisma Postgres via `pg_restore`. - -In the third step, you will be using a [direct connection](/v6/postgres/database/direct-connections) to securely connect to your Prisma Postgres database to run `pg_restore`. - -## Prerequisites - -- The connection URL to your existing PostgreSQL database -- A [Prisma Data Platform](https://console.prisma.io) account -- Node.js 18+ installed -- PostgreSQL CLI Tools (`pg_dump`, `pg_restore`) for creating and restoring backups - -:::info[Make sure your PostgreSQL tools match the Prisma Postgres version] - -Prisma Postgres runs PostgreSQL 17. Your `pg_dump` and `pg_restore` tools need to be version 17 to ensure compatibility. You can check your version by running `pg_dump --version` or `pg_restore --version`. - -::: - -## 1. Create a new Prisma Postgres database - -Follow these steps to create a new Prisma Postgres database: - -1. Log in to [Prisma Data Platform](https://console.prisma.io/) and open the Console. -1. In a [workspace](/v6/platform/about#workspace) of your choice, click the **New project** button. -1. Type a name for your project in the **Name** field, e.g. **hello-ppg**. -1. In the **Prisma Postgres** section, click the **Get started** button. -1. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. -1. Click the **Create project** button. - -Once your database is provisioned, obtain your direct connection string: - -1. Navigate to your active Prisma Postgres instance. -1. Click the **API Keys** tab in the project's sidenav. -1. Click the **Create API key** button. -1. In the popup, provide a **Name** for the API key and click **Create**. -1. Copy the connection string starting with `postgres://`, this is your direct connection string. - -Save the connection string, you'll need it in step 3. - -## 2. Export data from your existing database - -In this step, you're going to export the data from your existing database and store it in a `.bak` file on your local machine. - -Make sure to have the connection URL for your existing database ready, it should be [structured](/v6/orm/overview/databases/postgresql#connection-url) like this: - -```text -postgresql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Expand below for provider-specific instructions that help you determine the right connection string: - -
-Neon - -
- -- Make sure to select non-pooled connection string by switching off the **Connection pooling** toggle. -- The `sslmode` has to be set to `require` and appended to your Neon database url for the command to work. -- The connection URL should look similar to this: - ```text - postgresql://USER:PASSWORD@YOUR-NEON-HOST/DATABASE?sslmode=require - ``` - -
- -
-Supabase - -- Use a database connection URL that uses [Supavisor session mode](https://supabase.com/docs/guides/database/connecting-to-postgres#supavisor-session-mode). -- The connection URL should look similar to this: - ```text - postgres://postgres.apbkobhfnmcqqzqeeqss:[YOUR-PASSWORD]@aws-0-ca-central-1.pooler.supabase.com:5432/postgres - ``` - -
- -Next, run the following command to export the data of your PostgreSQL database (replace the `__DATABASE_URL__` placeholder with your actual database connection URL): - -```bash -pg_dump \ - -Fc \ - -v \ - -d __DATABASE_URL__ \ - -n public \ - -f db_dump.bak -``` - -Here's a quick overview of the CLI options that were used for this command: - -- `-Fc`: Uses the custom format for backups, recommended for `pg_restore` -- `-v`: Runs `pg_dump` in verbose mode -- `-d`: Specifies the database connection string -- `-n`: Specifies the target PostgreSQL schema -- `-f`: Specifies the output name for the backup file - -Running this command will create a backup file named `db_dump.bak` which you will use to restore the data into your Prisma Postgres database in the next step. - -## 3. Import data into Prisma Postgres - -In this section, you'll use your [direct connection string](/v6/postgres/database/direct-connections) to connect to your Prisma Postgres instance and import data via `pg_restore`. - -Your direct connection string from step 1 should look like this: - -```text -postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require -``` - -Use the backup file from **Step 2** to restore data into your Prisma Postgres database with `pg_restore` by running this command (replace `__USER__`, `__PASSWORD__` with the values from your direct connection string): - -```bash -pg_restore \ - -h db.prisma.io \ - -p 5432 \ - -U __USER__ \ - -d postgres \ - -v \ - ./db_dump.bak \ -&& echo "-complete-" -``` - -When prompted, enter the `__PASSWORD__` from your direct connection string. - -:::tip - -You can also use the full connection string format: - -```bash -pg_restore \ - -d "postgres://USER:PASSWORD@db.prisma.io:5432/postgres?sslmode=require" \ - -v \ - ./db_dump.bak \ -&& echo "-complete-" -``` - -::: - -Once the command completes execution, you will have successfully imported the data from your existing PostgreSQL database into Prisma Postgres 🎉 - -To validate that the import worked, you can use [Prisma Studio](/v6/postgres/integrations/viewing-data#viewing-and-editing-data-in-prisma-studio). Either open it in the [Platform Console](https://console.prisma.io) by clicking the **Studio** tab in the left-hand sidenav in your project or run this command to launch Prisma Studio locally: - -```npm -npx prisma studio -``` - -## 4. Update your application code to query Prisma Postgres - -### Scenario A: You are already using Prisma ORM - -If you're already using Prisma ORM, you need to update your database connection URL to point to your new Prisma Postgres instance. - -Update the `DATABASE_URL` in your `.env` file to match your Prisma Postgres direct connection string from step 1: - -```bash title=".env" -DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" -``` - -Then, re-generate Prisma Client so that the updated environment variable takes effect: - -```npm -npx prisma generate -``` - -Once this is done, you can run your application and it should work as before. - -:::tip - -For a complete guide on setting up Prisma ORM with Prisma Postgres from scratch, including driver adapter configuration and best practices, see the [Prisma ORM with Prisma Postgres quickstart](/v6/prisma-orm/quickstart/prisma-postgres). - -::: - -### Scenario B: You are not yet using Prisma ORM - -If you are not yet using Prisma ORM, you'll need to go through the following steps to use Prisma Postgres from your application: - -1. Install the Prisma CLI and other required dependencies in your project -1. Introspect the database to generate a Prisma schema -1. Generate Prisma Client -1. Update the queries in your application to use Prisma ORM - -You can find the detailed step-by-step instructions for this process in this guide: [Add Prisma ORM to an existing project](/v6/prisma-orm/add-to-existing-project/prisma-postgres). diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/index.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/index.mdx deleted file mode 100644 index 4270dd79c6..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/index.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Prisma Postgres -description: 'Get started with Prisma ORM and your favorite database. Learn about data modeling, migrations and querying.' -url: /v6/prisma-postgres -metaTitle: Prisma Postgres -metaDescription: 'Get started with Prisma ORM and your favorite database. Learn about data modeling, migrations and querying.' ---- - -## Getting started - -- [Quickstart](/v6/prisma-postgres/quickstart/prisma-orm) - Start a new project with Prisma Postgres -- [From the CLI](/v6/prisma-postgres/from-the-cli) - Create databases from the command line -- [Add to existing project](/v6/prisma-orm/add-to-existing-project/prisma-postgres) - Connect an existing Prisma project diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/meta.json b/apps/docs/content/docs.v6/(index)/prisma-postgres/meta.json deleted file mode 100644 index 9196473e5f..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "title": "Prisma Postgres", - "defaultOpen": true, - "pages": [ - "index", - "from-the-cli", - "import-from-existing-database-postgresql", - "import-from-existing-database-mysql", - "quickstart" - ] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/drizzle-orm.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/drizzle-orm.mdx deleted file mode 100644 index da036b4457..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/drizzle-orm.mdx +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: Drizzle ORM -description: Get started with Drizzle ORM and Prisma Postgres. -url: /v6/prisma-postgres/quickstart/drizzle-orm -metaTitle: 'Quickstart: Drizzle ORM with Prisma Postgres (10 min)' -metaDescription: Get started with Drizzle ORM and Prisma Postgres. ---- - -[Drizzle ORM](https://orm.drizzle.team) is a TypeScript ORM. In this guide, you'll learn how to connect Drizzle ORM to [Prisma Postgres](/v6/postgres). - -## Prerequisites - -- Node.js version 16 or higher -- TypeScript version 5.0 or higher - -## 1. Create a new project - -Create a new directory for your project and initialize it with npm: - -```npm -mkdir drizzle-quickstart -cd drizzle-quickstart -npm init -y -``` - -Install TypeScript and initialize it: - -```npm -npm install --save-dev typescript -``` - -```npm -npx tsc --init -``` - -In your `package.json`, set the `type` to `module`: - -```json title="package.json" -{ - // ... - "type": "module" // [!code ++] - // ... -} -``` - -## 2. Create a Prisma Postgres database - -You can create a Prisma Postgres database using the `create-db` CLI tool. Follow these steps to create your Prisma Postgres database: - -```npm -npx create-db -``` - -Then the CLI tool should output: - -```bash -┌ 🚀 Creating a Prisma Postgres database -│ -│ Provisioning a temporary database in us-east-1... -│ -│ It will be automatically deleted in 24 hours, but you can claim it. -│ -◇ Database created successfully! -│ -│ -● Database Connection -│ -│ -│ Connection String: -│ -│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require -│ -│ -◆ Claim Your Database -│ -│ Keep your database for free: -│ -│ https://create-db.prisma.io/claim?CLAIM_CODE -│ -│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed. -│ -└ -``` - -Create a `.env` file and add the connection string from the output: - -```text title=".env" -DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require" -``` - -:::warning - -**Never commit `.env` files to version control.** Add `.env` to your `.gitignore` file to keep credentials secure. - -::: - -The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your [Prisma Data Platform](https://console.prisma.io) account. Visit the claim URL from the output to keep your database. - -:::note - -To learn more about the `create-db` CLI tool, see the [create-db documentation](/v6/postgres/introduction/npx-create-db). - -::: - -## 3. Install dependencies - -Install Drizzle ORM and the PostgreSQL driver: - -```npm -npm install drizzle-orm pg dotenv -``` - -```npm -npm install --save-dev drizzle-kit @types/pg tsx -``` - -**Package breakdown:** - -- `drizzle-orm`: The lightweight TypeScript ORM -- `pg`: PostgreSQL driver for Node.js -- `dotenv`: Loads environment variables from `.env` file -- `drizzle-kit`: CLI tool for migrations and schema management -- `@types/pg`: TypeScript type definitions for the pg driver -- `tsx`: TypeScript execution engine for running `.ts` files directly - -## 4. Run a query - -Create a `src/script.ts` file: - -```typescript title="src/script.ts" -import "dotenv/config"; -import { drizzle } from "drizzle-orm/node-postgres"; -import { Pool } from "pg"; - -const pool = new Pool({ - connectionString: process.env.DATABASE_URL, -}); - -const db = drizzle({ client: pool }); - -async function main() { - const result = await db.execute("select 1"); - console.log("Query result:", result); -} - -main() - .then(async () => { - await pool.end(); - console.log("Connection closed"); - }) - .catch(async (error) => { - console.error("Error:", error); - await pool.end(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx src/script.ts -``` - -You should receive output similar to: - -```bash -Query result: Result { - command: 'SELECT', - rowCount: 1, - oid: null, - rows: [ { '?column?': 1 } ], - fields: [ - Field { - name: '?column?', - tableID: 0, - columnID: 0, - dataTypeID: 23, - dataTypeSize: 4, - dataTypeModifier: -1, - format: 'text' - } - ], - _parsers: [ [Function: parseInteger] ], - _types: { getTypeParser: [Function: getTypeParser] }, - RowCtor: null, - rowAsArray: false, - _prebuiltEmptyResultObject: { '?column?': null } -} -Connection closed -``` - -## Next steps - -You've successfully connected Drizzle ORM to Prisma Postgres! For more advanced features like schemas, migrations, and queries, see the [Drizzle ORM documentation](https://orm.drizzle.team/docs/get-started). diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/kysely.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/kysely.mdx deleted file mode 100644 index e9a5ccd856..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/kysely.mdx +++ /dev/null @@ -1,270 +0,0 @@ ---- -title: Kysely -description: Get started with Kysely and Prisma Postgres by creating a type-safe SQL query builder for your database. -url: /v6/prisma-postgres/quickstart/kysely -metaTitle: 'Quickstart: Kysely with Prisma Postgres (10 min)' -metaDescription: Get started with Kysely and Prisma Postgres by creating a type-safe SQL query builder for your database. ---- - -[Kysely](https://kysely.dev) is a type-safe TypeScript SQL query builder that provides TypeScript support and a fluent API for building SQL queries. In this guide, you'll learn how to connect Kysely to [Prisma Postgres](/v6/postgres) and start querying your database with full type safety. - -## Prerequisites - -- Node.js version 14 or higher -- TypeScript version 4.6 or higher (5.4+ recommended for improved type inference, 5.9+ for better compilation performance) -- Strict mode enabled in your `tsconfig.json` for Kysely's type safety - -## 1. Create a new project - -Create a new directory for your project and initialize it with npm: - -```npm -mkdir kysely-quickstart -cd kysely-quickstart -npm init -y -``` - -Install TypeScript and initialize it: - -```npm -npm install --save-dev typescript -``` - -```npm -npx tsc --init -``` - -## 2. Configure TypeScript - -Kysely requires TypeScript's strict mode for proper type safety. Update your `tsconfig.json` file: - -```json title="tsconfig.json" -{ - // ... - "compilerOptions": { - // ... - "strict": true, // [!code ++] - "allowImportingTsExtensions": true, // [!code ++] - "noEmit": true // [!code ++] - // ... - } - // ... -} -``` - -:::note - -The `strict: true` setting is **required** for Kysely's type safety to work correctly. - -::: - -In your `package.json`, set the `type` to `module`: - -```json -{ - // ... - "type": "module" // [!code ++] - // ... -} -``` - -## 3. Create a Prisma Postgres database - -You can create a Prisma Postgres database using the `create-db` CLI tool. Follow these steps to create your Prisma Postgres database: - -```npm -npx create-db -``` - -Then the CLI tool should output: - -```bash -┌ 🚀 Creating a Prisma Postgres database -│ -│ Provisioning a temporary database in us-east-1... -│ -│ It will be automatically deleted in 24 hours, but you can claim it. -│ -◇ Database created successfully! -│ -│ -● Database Connection -│ -│ -│ Connection String: -│ -│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require -│ -│ -◆ Claim Your Database -│ -│ Keep your database for free: -│ -│ https://create-db.prisma.io/claim?CLAIM_CODE -│ -│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed. -│ -└ -``` - -Create a `.env` file and add the connection string from the output: - -```text title=".env" -DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require" -``` - -:::warning - -**Never commit `.env` files to version control.** Add `.env` to your `.gitignore` file to keep credentials secure. - -::: - -The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your [Prisma Data Platform](https://console.prisma.io) account. Visit the claim URL from the output to keep your database. - -:::note - -To learn more about the `create-db` CLI tool, see the [create-db documentation](/v6/postgres/introduction/npx-create-db). - -::: - -## 4. Install dependencies - -Install Kysely and the PostgreSQL driver: - -```npm -npm install kysely pg dotenv -``` - -```npm -npm install --save-dev @types/pg tsx -``` - -**Package breakdown:** - -- `kysely`: The type-safe SQL query builder -- `pg`: PostgreSQL driver for Node.js (required by Kysely's PostgresDialect) -- `dotenv`: Loads environment variables from `.env` file -- `@types/pg`: TypeScript type definitions for the pg driver -- `tsx`: TypeScript execution engine for running `.ts` files directly - -## 5. Define database types - -Create a `src/types.ts` file to define your database schema types: - -```typescript title="src/types.ts" -import type { Generated } from "kysely"; - -export interface Database { - users: UsersTable; -} - -export interface UsersTable { - id: Generated; - email: string; - name: string | null; -} -``` - -## 6. Configure database connection - -Create a `src/database.ts` file to instantiate Kysely with your Prisma Postgres connection: - -```typescript title="src/database.ts" -import "dotenv/config"; -import type { Database } from "./types.ts"; -import { Pool } from "pg"; -import { Kysely, PostgresDialect } from "kysely"; - -// Parse DATABASE_URL into connection parameters -function parseConnectionString(url: string) { - const parsed = new URL(url); - return { - host: parsed.hostname, - port: parseInt(parsed.port), - user: parsed.username, - password: parsed.password, - database: parsed.pathname.slice(1), // Remove leading '/' - }; -} - -const connectionParams = parseConnectionString(process.env.DATABASE_URL!); - -const dialect = new PostgresDialect({ - pool: new Pool({ - ...connectionParams, - ssl: true, - max: 10, - }), -}); - -// Database interface is passed to Kysely's constructor, and from now on, Kysely -// knows your database structure. -// Dialect is passed to Kysely's constructor, and from now on, Kysely knows how -// to communicate with your database. -export const db = new Kysely({ - dialect, -}); -``` - -## 7. Run queries - -Create a `src/script.ts` file: - -```typescript title="src/script.ts" -import { db } from "./database.ts"; - -async function main() { - // Create the users table - await db.schema - .createTable("users") - .ifNotExists() - .addColumn("id", "serial", (col) => col.primaryKey()) - .addColumn("email", "varchar(255)", (col) => col.notNull().unique()) - .addColumn("name", "varchar(255)") - .execute(); - - // Insert a user - const user = await db - .insertInto("users") - .values({ - email: "alice@prisma.io", - name: "Alice", - }) - .returningAll() - .executeTakeFirstOrThrow(); - - console.log("Created user:", user); - - // Query all users - const users = await db.selectFrom("users").selectAll().execute(); - - console.log("All users:", users); -} - -main() - .then(async () => { - await db.destroy(); - }) - .catch(async (error) => { - console.error("Error:", error); - await db.destroy(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx src/script.ts -``` - -You should receive the following output: - -```bash -Created user: { id: 1, email: 'alice@prisma.io', name: 'Alice' } -All users: [ { id: 1, email: 'alice@prisma.io', name: 'Alice' } ] -``` - -## Next steps - -You've successfully connected Kysely to Prisma Postgres! For more advanced features like schemas, migrations, and complex queries, see the [Kysely documentation](https://kysely.dev/docs/intro). diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/meta.json b/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/meta.json deleted file mode 100644 index bbfa7c4d52..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/meta.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "Quickstart", - "pages": ["prisma-orm", "kysely", "drizzle-orm", "typeorm"] -} diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/prisma-orm.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/prisma-orm.mdx deleted file mode 100644 index 16599db3e1..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/prisma-orm.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Prisma ORM -description: Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access. -url: /v6/prisma-postgres/quickstart/prisma-orm -metaTitle: 'Quickstart: Prisma ORM with Prisma Postgres (5 min)' -metaDescription: Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access. ---- - -[Prisma Postgres](/v6/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to Prisma Postgres using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. - -## Prerequisites - -## 1. Create a new project - -## 2. Install required dependencies - -Install the packages needed for this quickstart: - -```npm -npm install prisma @types/node --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv -``` - -Here's what each package does: - -- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` -- **`@prisma/client`** - The Prisma Client library for querying your database -- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/v6/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database -- **`dotenv`** - Loads environment variables from your `.env` file - -## 3. Configure ESM support - -Update `tsconfig.json` for ESM compatibility: - -```json title="tsconfig.json" -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true, - "ignoreDeprecations": "6.0" - } -} -``` - -Update `package.json` to enable ESM: - -```json title="package.json" -{ - "type": "module" // [!code ++] -} -``` - -## 4. Initialize Prisma ORM and create a Prisma Postgres database - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/v6/orm/prisma-schema/overview) file with the following command: - -```npm -npx prisma init --db --output ../generated/prisma -``` - -:::info - -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database. - -::: - -This command does a few things: - -- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models -- Creates a new Prisma Postgres database (when using `--db` flag) -- Creates a `.env` file in the root directory for environment variables -- Generates the Prisma Client in the `generated/prisma/` directory -- Creates a `prisma.config.ts` file for Prisma configuration - -The generated `prisma.config.ts` file looks like this: - -```typescript title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -The generated schema uses [the ESM-first `prisma-client` generator](/v6/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} -``` - -## 5. Define your data model - -Open `prisma/schema.prisma` and add the following models: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - authorId Int // [!code ++] -} // [!code ++] -``` - -## 6. Create and apply your first migration - -Create your first migration to set up the database tables: - -```npm -npx prisma migrate dev --name init -``` - -This command creates the database tables based on your schema. - -Now run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -## 7. Instantiate Prisma Client - -Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: - -```typescript title="lib/prisma.ts" -import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { PrismaClient } from "../generated/prisma/client"; - -const connectionString = `${process.env.DATABASE_URL}`; - -const adapter = new PrismaPg({ connectionString }); -const prisma = new PrismaClient({ adapter }); - -export { prisma }; -``` - -:::tip - -If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/v6/postgres/database/serverless-driver#use-with-prisma-orm). - -::: - -## 8. Write your first query - -Create a `script.ts` file to test your setup: - -```typescript title="script.ts" -import { prisma } from "./lib/prisma"; - -async function main() { - // Create a new user with a post - const user = await prisma.user.create({ - data: { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: { - title: "Hello World", - content: "This is my first post!", - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - console.log("Created user:", user); - - // Fetch all users with their posts - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }); - console.log("All users:", JSON.stringify(allUsers, null, 2)); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); -``` - -Run the script: - -```npm -npx tsx script.ts -``` - -You should see the created user and all users printed to the console! - -## 9. Explore your data with Prisma Studio - -## Next steps - -## More info - -- [Prisma Postgres documentation](/v6/postgres) -- [Prisma Config reference](/v6/orm/reference/prisma-config-reference) -- [Database connection management](/v6/orm/prisma-client/setup-and-configuration/databases-connections) -- [Cache your queries](/v6/postgres/database/caching#setting-up-caching-in-prisma-postgres) diff --git a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/typeorm.mdx b/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/typeorm.mdx deleted file mode 100644 index 2629a20c81..0000000000 --- a/apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/typeorm.mdx +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: TypeORM -description: Get started with TypeORM and Prisma Postgres by connecting your TypeScript ORM to a managed PostgreSQL database. -url: /v6/prisma-postgres/quickstart/typeorm -metaTitle: 'Quickstart: TypeORM with Prisma Postgres (10 min)' -metaDescription: Get started with TypeORM and Prisma Postgres by connecting your TypeScript ORM to a managed PostgreSQL database. ---- - -[TypeORM](https://typeorm.io) is a TypeScript ORM. In this guide, you'll learn how to connect TypeORM to [Prisma Postgres](/v6/postgres). - -## Prerequisites - -- Node.js version 16 or higher -- TypeScript version 4.5 or higher - -## 1. Generate a TypeORM project - -Use the TypeORM CLI to generate a starter project: - -```npm -npx typeorm init --name typeorm-quickstart --database postgres -``` - -This command will generate a new project with the following structure: - -``` -typeorm-quickstart -├── src -│ ├── entity -│ │ └── User.ts # Sample entity -│ ├── migration # Migrations folder -│ ├── data-source.ts # Data source configuration -│ └── index.ts # Application entry point -├── .gitignore -├── package.json -├── README.md -└── tsconfig.json -``` - -## 2. Install dependencies - -Navigate to the project directory and install dependencies: - -```npm -cd typeorm-quickstart -npm install -``` - -Install dotenv to load environment variables: - -```npm -npm install dotenv -``` - -## 3. Create a Prisma Postgres database - -You can create a Prisma Postgres database using the `create-db` CLI tool. Follow these steps to create your Prisma Postgres database: - -```npm -npx create-db -``` - -Then the CLI tool should output: - -```bash -┌ 🚀 Creating a Prisma Postgres database -│ -│ Provisioning a temporary database in us-east-1... -│ -│ It will be automatically deleted in 24 hours, but you can claim it. -│ -◇ Database created successfully! -│ -│ -● Database Connection -│ -│ -│ Connection String: -│ -│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require -│ -│ -◆ Claim Your Database -│ -│ Keep your database for free: -│ -│ https://create-db.prisma.io/claim?CLAIM_CODE -│ -│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed. -│ -└ -``` - -Create a `.env` file and add the connection string from the output: - -```text title=".env" -DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require" -``` - -:::warning - -**Never commit `.env` files to version control.** Add `.env` to your `.gitignore` file to keep credentials secure. - -::: - -The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your [Prisma Data Platform](https://console.prisma.io) account. Visit the claim URL from the output to keep your database. - -:::note - -To learn more about the `create-db` CLI tool, see the [create-db documentation](/v6/postgres/introduction/npx-create-db). - -::: - -## 4. Configure database connection - -Update the `src/data-source.ts` file to use your Prisma Postgres connection: - -```typescript title="src/data-source.ts" -import "reflect-metadata"; -import "dotenv/config"; // [!code ++] -import { DataSource } from "typeorm"; -import { User } from "./entity/User"; - -// Parse DATABASE_URL into connection parameters // [!code ++] -function parseConnectionString(url: string) { - // [!code ++] - const parsed = new URL(url); // [!code ++] - return { - // [!code ++] - host: parsed.hostname, // [!code ++] - port: parseInt(parsed.port), // [!code ++] - username: parsed.username, // [!code ++] - password: parsed.password, // [!code ++] - database: parsed.pathname.slice(1), // Remove leading '/' // [!code ++] - }; // [!code ++] -} // [!code ++] - -const connectionParams = parseConnectionString(process.env.DATABASE_URL!); // [!code ++] - -export const AppDataSource = new DataSource({ - type: "postgres", - host: "localhost", // [!code --] - port: 5432, // [!code --] - username: "test", // [!code --] - password: "test", // [!code --] - database: "test", // [!code --] - ...connectionParams, // [!code ++] - ssl: true, // [!code ++] - synchronize: true, - logging: false, - entities: [User], - migrations: [], - subscribers: [], -}); -``` - -## 5. Run the application - -Start the application: - -```npm -npm start -``` - -You should see output indicating the connection was successful and a new user was inserted into the database: - -```bash -Inserting a new user into the database... -Saved a new user with id: 1 -Loading users from the database... -Loaded users: [ User { id: 1, firstName: 'Timber', lastName: 'Saw', age: 25 } ] -``` - -## Next steps - -You've successfully connected TypeORM to Prisma Postgres! For more advanced features like entities, migrations, and queries, see the [TypeORM documentation](https://typeorm.io/docs/getting-started). diff --git a/apps/docs/content/docs.v6/accelerate/api-reference.mdx b/apps/docs/content/docs.v6/accelerate/api-reference.mdx deleted file mode 100644 index c3de72e55f..0000000000 --- a/apps/docs/content/docs.v6/accelerate/api-reference.mdx +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: API Reference -description: API reference documentation for Accelerate. -url: /v6/accelerate/api-reference -metaTitle: 'Accelerate: API Reference' -metaDescription: API reference documentation for Accelerate. ---- - -The Accelerate API reference documentation is based on the following schema: - -```prisma -model User { - id Int @id @default(autoincrement()) - name String? - email String @unique -} -``` - -All example are based on the `User` model. - -## `cacheStrategy` - -With the Accelerate extension for Prisma Client, you can use the `cacheStrategy` parameter for model queries and use the [`ttl`](/v6/postgres/database/caching#time-to-live-ttl) and [`swr`](/v6/postgres/database/caching#stale-while-revalidate-swr) parameters to define a cache strategy for Accelerate. The Accelerate extension requires that you install Prisma Client version `4.10.0`. - -### Options - -The `cacheStrategy` parameter takes an option with the following keys: - -| Option | Example | Type | Required | Description | -| ------ | ---------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `swr` | `60` | `Int` | No | The stale-while-revalidate time in seconds. | -| `ttl` | `60` | `Int` | No | The time-to-live time in seconds. | -| `tags` | `["user"]` | `String[]` | No | The `tag` serves as a variable to control the invalidation of specific queries within your application. It is an optional array of strings to [invalidate](/v6/accelerate/api-reference#accelerateinvalidate) the cache, with each tag containing only alphanumeric characters and underscores, and a maximum length of 64 characters. | - -| - -### Examples - -Add a caching strategy to the query, defining a 60-second stale-while-revalidate (SWR) value, a 60-second time-to-live (TTL) value, and a cache tag of `"emails_with_alice"`: - -```ts highlight=7:11;normal -await prisma.user.findMany({ - where: { - email: { - contains: "alice@prisma.io", - }, - }, - cacheStrategy: { - // [!code highlight] - swr: 60, // [!code highlight] - ttl: 60, // [!code highlight] - tags: ["emails_with_alice"], // [!code highlight] - }, // [!code highlight] -}); -``` - -### Supported Prisma Client operations - -The following is a list of all read query operations that support `cacheStrategy`: - -- [`findUnique()`](/v6/orm/reference/prisma-client-reference#findunique) -- [`findUniqueOrThrow()`](/v6/orm/reference/prisma-client-reference#finduniqueorthrow) -- [`findFirst()`](/v6/orm/reference/prisma-client-reference#findfirst) -- [`findFirstOrThrow()`](/v6/orm/reference/prisma-client-reference#findfirstorthrow) -- [`findMany()`](/v6/orm/reference/prisma-client-reference#findmany) -- [`count()`](/v6/orm/reference/prisma-client-reference#count) -- [`aggregate()`](/v6/orm/reference/prisma-client-reference#aggregate) -- [`groupBy()`](/v6/orm/reference/prisma-client-reference#groupby) - -The `cacheStrategy` parameter is not supported on any write operations, such as `create()`. - -## `withAccelerateInfo` - -Any query that supports the `cacheStrategy` can append `withAccelerateInfo()` to wrap the response data and include additional information about the Accelerate response. - -To retrieve the status of the response, use: - -```ts -const { data, info } = await prisma.user - .count({ - cacheStrategy: { ttl: 60, swr: 600 }, - where: { myField: "value" }, - }) - .withAccelerateInfo(); - -console.dir(info); -``` - -Notice the `info` property of the response object. This is where the request information is stored. - -### Return type - -The `info` object is of type `AccelerateInfo` and follows the interface below: - -```ts -interface AccelerateInfo { - cacheStatus: "ttl" | "swr" | "miss" | "none"; - lastModified: Date; - region: string; - requestId: string; - signature: string; -} -``` - -| Property | Type | Description | -| -------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cacheStatus` | `"ttl" \| "swr" \| "miss" \| "none" ` | The cache status of the response.
  • `ttl` indicates a cache hit within the `ttl` duration and no database query was executed
  • `swr` indicates a cache hit within the `swr` duration and the data is being refreshed by Accelerate in the background
  • `miss` indicates that both `ttl` and `swr` have expired and the database query was executed by the request
  • `none` indicates that no cache strategy was specified and the database query was executed by the request
| -| `lastModified` | `Date` | The date the response was last refreshed. | -| `region` | `String` | The data center region that received the request. | -| `requestId` | `String` | Unique identifier of the request. Useful for troubleshooting. | -| `signature` | `String` | The unique signature of the Prisma operation. | - -## `$accelerate.invalidate` - -You can invalidate the cache using the [`$accelerate.invalidate` API](/v6/accelerate). - -:::note - -To invalidate cached query results on-demand, a paid plan is required. Each plan has specific limits on the number of cache tag-based invalidations allowed per day, though there are no limits on calling the `$accelerate.invalidate` API itself. See our [pricing for more details](https://www.prisma.io/pricing#accelerate). - -::: - -### Example - -To invalidate the query below: - -```ts -await prisma.user.findMany({ - where: { - email: { - contains: "alice@prisma.io", - }, - }, - cacheStrategy: { - swr: 60, - ttl: 60, - tags: ["emails_with_alice"], // [!code highlight] - }, -}); -``` - -You need to provide the cache tag in the `$accelerate.invalidate` API: - -```ts -try { - await prisma.$accelerate.invalidate({ - // [!code highlight] - tags: ["emails_with_alice"], // [!code highlight] - }); // [!code highlight] -} catch (e) { - if (e instanceof Prisma.PrismaClientKnownRequestError) { - // The .code property can be accessed in a type-safe manner - if (e.code === "P6003") { - console.log("The cache invalidation rate limit has been reached. Please try again later."); - } - } - throw e; -} -``` - -:::note -You can invalidate up to 5 tags per call. -::: - -## `$accelerate.invalidateAll` - -You can invalidate the entire cache using the `$accelerate.invalidateAll` API. - -### Example - -To invalidate the query below: - -```ts -await prisma.user.findMany({ - where: { - email: { - contains: "alice@prisma.io", - }, - }, - cacheStrategy: { - swr: 60, - ttl: 60, - tags: ["emails_with_alice"], // [!code highlight] - }, -}); -``` - -Just call the `$accelerate.invalidateAll` API: - -```ts -try { - await prisma.$accelerate.invalidateAll(); // [!code highlight] -} catch (e) { - if (e instanceof Prisma.PrismaClientKnownRequestError) { - if (e.code === "P6003") { - console.log("The cache invalidation rate limit has been reached. Please try again later."); - } - } - throw e; -} -``` - -### Why use `$accelerate.invalidateAll`? - -This method offers better editor support (e.g. IntelliSense) than alternatives like `invalidate("all")`. - -:::warning - -This clears cache for the entire environment—use with care. - -::: - -## Providing a Custom Fetch Implementation - -Starting from Accelerate version `2.0.0`, you can provide a custom implementation of the fetch function when extending the Prisma Client with Accelerate. This allows you greater flexibility and control over how HTTP requests are handled within your application. - -To pass a custom fetch implementation, you can use the following pattern: - -```ts -const myFetch = (input: URL, init?: RequestInit): Promise => { - // Your custom fetch logic here - return fetch(input, init); -}; - -const prisma = new PrismaClient().$extends(withAccelerate({ fetch: myFetch })); -``` - -## Errors - -Prisma Accelerate-related errors start with `P6xxx`. - -You can find the full error code reference for Prisma Accelerate [here](/v6/orm/reference/error-reference#prisma-accelerate). diff --git a/apps/docs/content/docs.v6/accelerate/caching.mdx b/apps/docs/content/docs.v6/accelerate/caching.mdx deleted file mode 100644 index eecf0ba009..0000000000 --- a/apps/docs/content/docs.v6/accelerate/caching.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Caching queries in Prisma Accelerate -description: Learn everything you need to know to use Accelerate's global database caching. -url: /v6/accelerate/caching -metaTitle: 'Accelerate: Caching' -metaDescription: Learn everything you need to know to use Accelerate's global database caching. ---- - -Prisma Accelerate provides global caching for read queries using TTL, Stale-While-Revalidate (SWR), or a combination of both. It's included as part of Prisma Postgres, but can also be used with your own database by enabling Accelerate in the [Prisma Data Platform](https://console.prisma.io?utm_source=docs) and [configuring it with your database](/v6/accelerate/getting-started). - -This content has moved — learn more on the updated [Caching in Accelerate](/v6/postgres/database/caching) page. diff --git a/apps/docs/content/docs.v6/accelerate/compare.mdx b/apps/docs/content/docs.v6/accelerate/compare.mdx deleted file mode 100644 index d4e1079117..0000000000 --- a/apps/docs/content/docs.v6/accelerate/compare.mdx +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Compare Accelerate -description: Learn how Prisma Accelerate compares to other connection poolers like pgbouncer. -url: /v6/accelerate/compare -metaTitle: Comparing Prisma Accelerate to other connection pooling options -metaDescription: Learn how Prisma Accelerate compares to other connection poolers like pgbouncer. ---- - -Prisma Accelerate supports products that serve a global audience, with a global caching system and connection pool that spans multiple regions, providing consistent access to data with low latency no matter where your user (or your database) is located in the world. - -The managed connection pool is designed to support serverless infrastructure, capable of handling high volumes of connections and adapting to traffic spikes with ease. - -Explore how Prisma Accelerate compares to other global cache and connection pool solutions on the market, and discover what sets it apart. - -## What makes Accelerate unique? - -Prisma Accelerate is chosen and loved by many for a number of key reasons which make Accelerate unique: - -- [**Query-Level policies**](/v6/accelerate/compare#accelerate-global-cache): Accelerate is the only solution that offers query-level cache policies, allowing you to control the cache strategy for each query specifically. It is common to have some values that need to be cached for a long time, others that need caching for a short time, and some that should not be cached at all. With Accelerate you can do this, and even set different cache strategies per query. -- [**Global by default**](/v6/accelerate/compare#accelerate-global-cache): Accelerate is globally distributed by default. You never need to worry about where a user is located with respect to your database location. -- [**Fully managed**](/v6/accelerate/compare#management): You don't need to manage a server or worry about uptime. Accelerate is fully managed for you. -- [**Auto-scaling**](/v6/accelerate/compare#performance): Accelerate automatically adjusts resources to match workload demands, providing fast and consistent performance during traffic spikes. - -## Accelerate global cache - -Prisma Accelerate offers a powerful global cache, so you can serve data to your users at the edge — the closest point to where the users are located — no matter where your database is hosted. This not only speeds up the experience for users, but also reduces read load on your database as well by avoiding roundtrips. - -| | Accelerate | Hyperdrive | PlanetScale Boost | -| ----------------------------------- | ---------- | ---------- | ----------------- | -| **Fully Managed** | ✅ | ✅ | ✅ | -| **Globally distributed edge infra** | ✅ | ✅ | ✅ | -| **Control cache policy from code** | ✅ | ❌ | ❌ | -| **Query-level cache policies** | ✅ | ❌ | ❌ | -| **Postgres compatible** | ✅ | ✅ | ❌ | -| **MySQL compatible** | ✅ | ❌ | ✅ | -| **MongoDB compatible** | ✅ | ❌ | ❌ | -| **Automatic cache updates** | ❌ | ❌ | ✅ | - -**Why are these important?** - -- Since Accelerate extends the Prisma client, you can control caching policies directly from your codebase with just an extra line of code. Integration is seamless. Here is an example using [the stale-while-revalidating caching strategy](/v6/postgres/database/caching#stale-while-revalidate-swr): - ```jsx - await prisma.user.findMany({ - cacheStrategy: { - swr: 60, - }, - }); - ``` -- Query level cache policies are critical for serious applications, so that you can control which queries are cached, and the characteristics of the policy. You may want certain data in your app to be cached for several days, other data to be cached for a just a few minutes, and other data to be not cached at all. This is only possible with Prisma Accelerate. -- Authenticating with an API key can be a helpful security measure, allowing you to decouple database credentials from application secrets. Easily rotate API keys as often as you like, without needing any credential changes in your database -- Automatic cache updates means that the cache is automatically updated when a change in the database occurs. With Accelerate, you are in control of how the cache is invalidated, using [various caching strategies](/v6/postgres/database/caching). - -## Accelerate connection pool - -Prisma Accelerate includes a globally hosted connection pooler, which allows you to handle peak loads without any problem. Using a connection pool is important especially for serverless infrastructure, which by nature is not able to control connection volume to the database on its own. Prisma Accelerate offers a fully managed, globally colocated option, which auto scales to support any workload. - -### Management - -| | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | -| ------------------------------ | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | -| **Fully managed** | ✅ | ❌ | ❌ | 🟠 | ✅ | ❌ | ✅ | -| **Globally distributed** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | -| **Integrated with ORM client** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **Redundancy** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | - -**Why are these important?** - -- If you decide to manage a connection pooler yourself (eg. using pgbouncer or pgcat) you will also be responsible for managing its uptime. If the server crashes, your application may be down until you recover it. Accelerate, as a fully managed solution will be recovered for you transparently, in the unlikely case of any infrastructure issue. -- The hosted pgbouncer option on Digital Ocean is semi-managed, you will need to set it up in your Digital Ocean account, and ensure it is running smoothly at all times. -- Redundancy is helpful in the unlikely scenario that your connection pool service goes down. With Accelerate, it is automatically and seamlessly handed over to another server and recovered without any interruption. - -### Performance - -| | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | -| ------------------------------- | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | -| **Auto scaling** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **Globally distributed** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | -| **Optimized queries over HTTP** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | -| **Isolated compute** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | - -**Why are these important?** - -- Accelerate will automatically scale up and down to suit your application workload, meaning you'll never run out of compute resource. Additionally, this provides important redundancy to protect against any single compute instance failing — in the unlikely event of an instance going down, Accelerate will automatically spawn a new instance. -- Cross-region TCP handshakes between the application server and PgBouncer or the database are costly and time-consuming. If connections are reused only at the PgBouncer layer, the TCP handshake and connection setup still consume unnecessary time on every single request, which undermines the efficiency of connection reuse. Prisma Accelerate improves this by leveraging HTTP, which is more efficient for connection management. It reduces the overhead associated with TCP handshakes, resulting in faster, more responsive interactions between your application and the database. -- Never worry about 'noisy neighbors' with isolated compute resources. Other customers never impact on your own performance. - -### Database Support - -| | Accelerate | pgbouncer | pgcat | Digital Ocean (pgbouncer) | Neon (pgbouncer) | Supavisor | Hyperdrive | -| --------------- | ---------- | --------- | ----- | ------------------------- | ---------------- | --------- | ---------- | -| **PostgreSQL** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| **MySQL** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **PlanetScale** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **CockroachDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **MongoDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | diff --git a/apps/docs/content/docs.v6/accelerate/connection-pooling.mdx b/apps/docs/content/docs.v6/accelerate/connection-pooling.mdx deleted file mode 100644 index 68a0c6bd4b..0000000000 --- a/apps/docs/content/docs.v6/accelerate/connection-pooling.mdx +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Connection Pooling -description: Learn about everything you need to know to use Accelerate's connection pooling. -url: /v6/accelerate/connection-pooling -metaTitle: 'Prisma Accelerate: Connection Pooling' -metaDescription: Learn about everything you need to know to use Accelerate's connection pooling. ---- - -Accelerate provides built-in connection pooling to efficiently manage database connections. It's included as part of [Prisma Postgres](/v6/postgres), but you can also use it with your own database by enabling Accelerate in the [Prisma Data Platform](https://console.prisma.io?utm_source=docs) and [connecting it to your database](/v6/accelerate/getting-started). -This page has moved, connection pooling in Prisma Accelerate is now documented in the [Prisma Postgres section](/v6/postgres/database/connection-pooling). diff --git a/apps/docs/content/docs.v6/accelerate/evaluating.mdx b/apps/docs/content/docs.v6/accelerate/evaluating.mdx deleted file mode 100644 index 4d21c1a969..0000000000 --- a/apps/docs/content/docs.v6/accelerate/evaluating.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Evaluating -description: Learn about evaluating Prisma Accelerate. -url: /v6/accelerate/evaluating -metaTitle: 'Accelerate: Evaluating' -metaDescription: Learn about evaluating Prisma Accelerate. ---- - -Prisma Accelerate optimizes database interactions through advanced connection pooling and global edge caching. Its connection pooler is available in 16 regions and helps applications load-balance and scale database requests based on demand. - -Considering the information above, we recommend evaluating Accelerate with high volume to see it perform under load. - -## How Accelerate's connection pool optimizes performance under load - -Prisma Accelerate employs a dynamic, serverless connection pooling infrastructure. When a request is made, a connection pool is quickly provisioned for the project in the region assigned while configuring Prisma Accelerate. This connection pool remains active, serving many additional requests while reusing established database connections. The connection pool will disconnect after a period of inactivity, so it’s important to evaluate Prisma Accelerate with a consistent stream of traffic. - -**Key Benefits:** - -- **Optimized Query Performance:** The serverless connection pooler adapts to the query load, ensuring the database connections are managed efficiently during peak demand. - - > Prisma Accelerate’s connection pooler cannot improve the performance of queries in the database. In scenarios where query performance is an issue, we recommend optimizing the Prisma query, applying indexes, or utilizing Accelerate’s edge caching. - -- **Maximize Connection Reuse:** Executing a consistent volume of queries helps maintain active instances of Accelerate connection poolers. This increases connection reuse, ensuring faster response times for subsequent queries. - -By understanding and harnessing this mechanism, you can ensure that your database queries perform consistently and efficiently at scale. - -## Evaluating Prisma Accelerate connection pooling performance - -Below you will find an example of how to evaluate Prisma Accelerate using a sample model: - -```prisma -model Notes { - id Int @id @default(autoincrement()) - title String - createdAt DateTime @default(now()) - updatedAt DateTime? @updatedAt -} -``` - -```typescript -import { PrismaClient } from "@prisma/client"; -import { withAccelerate } from "@prisma/extension-accelerate"; - -const prisma = new PrismaClient().$extends(withAccelerate()); - -function calculateStatistics(numbers: number[]): { - average: number; - p50: number; - p75: number; - p99: number; -} { - if (numbers.length === 0) { - throw new Error("The input array is empty."); - } - - // Sort the array in ascending order - numbers.sort((a, b) => a - b); - - const sum = numbers.reduce((acc, num) => acc + num, 0); - const count = numbers.length; - - const average = sum / count; - const p50 = getPercentile(numbers, 50); - const p75 = getPercentile(numbers, 75); - const p99 = getPercentile(numbers, 99); - - return { average, p50, p75, p99 }; -} - -function getPercentile(numbers: number[], percentile: number): number { - if (percentile <= 0 || percentile >= 100) { - throw new Error("Percentile must be between 0 and 100."); - } - - const index = (percentile / 100) * (numbers.length - 1); - if (Number.isInteger(index)) { - // If the index is an integer, return the corresponding value - return numbers[index]; - } else { - // If the index is not an integer, interpolate between two adjacent values - const lowerIndex = Math.floor(index); - const upperIndex = Math.ceil(index); - const lowerValue = numbers[lowerIndex]; - const upperValue = numbers[upperIndex]; - const interpolationFactor = index - lowerIndex; - return lowerValue + (upperValue - lowerValue) * interpolationFactor; - } -} - -async function main() { - const timings = []; - - // fire a query before going to the loop - await prisma.notes.findMany({ - take: 20, - }); - - // we recommend evaluationg Prisma Accelerate with a large loop - const LOOP_LENGTH = 10000; - - for (let i = 0; i < LOOP_LENGTH; i++) { - const start = Date.now(); - await prisma.notes.findMany({ - take: 20, - }); - - timings.push(Date.now() - start); - } - - const statistics = calculateStatistics(timings); - console.log("Average:", statistics.average); - console.log("P50:", statistics.p50); - console.log("P75:", statistics.p75); - console.log("P99:", statistics.p99); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch((e) => { - await prisma.$disconnect(); - process.exit(1); - }); -``` - -## Evaluating Prisma Accelerate caching performance - -Prisma Accelerate’s edge cache is also optimized for a high volume of queries. The cache automatically optimizes for repeated queries. As a result, the cache hit rate will increase as the query frequency does. Adding a query result to the cache is also non-blocking, so a short burst of queries might not utilize the cache or a sustained load. - -To evaluate Accelerate’s edge caching, you can modify the above script with the below: - -```typescript -import { PrismaClient } from "@prisma/client"; -import { withAccelerate } from "@prisma/extension-accelerate"; - -const prisma = new PrismaClient().$extends(withAccelerate()); - -function calculateStatistics(numbers: number[]): { - average: number; - p50: number; - p75: number; - p99: number; -} { - if (numbers.length === 0) { - throw new Error("The input array is empty."); - } - - // Sort the array in ascending order - numbers.sort((a, b) => a - b); - - const sum = numbers.reduce((acc, num) => acc + num, 0); - const count = numbers.length; - - const average = sum / count; - const p50 = getPercentile(numbers, 50); - const p75 = getPercentile(numbers, 75); - const p99 = getPercentile(numbers, 99); - - return { average, p50, p75, p99 }; -} - -function getPercentile(numbers: number[], percentile: number): number { - if (percentile <= 0 || percentile >= 100) { - throw new Error("Percentile must be between 0 and 100."); - } - - const index = (percentile / 100) * (numbers.length - 1); - if (Number.isInteger(index)) { - // If the index is an integer, return the corresponding value - return numbers[index]; - } else { - // If the index is not an integer, interpolate between two adjacent values - const lowerIndex = Math.floor(index); - const upperIndex = Math.ceil(index); - const lowerValue = numbers[lowerIndex]; - const upperValue = numbers[upperIndex]; - const interpolationFactor = index - lowerIndex; - return lowerValue + (upperValue - lowerValue) * interpolationFactor; - } -} - -async function main() { - const timings = []; - - // fire a query before going to the loop - await prisma.notes.findMany({ - take: 20, - cacheStrategy: { - ttl: 30, - }, - }); - - // we recommend evaluating Prisma Accelerate with a large loop - const LOOP_LENGTH = 10000; - - for (let i = 0; i < LOOP_LENGTH; i++) { - const start = Date.now(); - await prisma.notes.findMany({ - take: 20, - cacheStrategy: { - ttl: 30, - }, - }); - - timings.push(Date.now() - start); - } - - const statistics = calculateStatistics(timings); - console.log("Average:", statistics.average); - console.log("P50:", statistics.p50); - console.log("P75:", statistics.p75); - console.log("P99:", statistics.p99); -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch((e) => { - await prisma.$disconnect(); - process.exit(1); - }); -``` diff --git a/apps/docs/content/docs.v6/accelerate/examples.mdx b/apps/docs/content/docs.v6/accelerate/examples.mdx deleted file mode 100644 index b3a2f92a80..0000000000 --- a/apps/docs/content/docs.v6/accelerate/examples.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Prisma Accelerate examples -description: Check out ready-to-run examples for Prisma Accelerate. -url: /v6/accelerate/examples -metaTitle: 'Prisma Accelerate: Examples' -metaDescription: Check out ready-to-run examples for Prisma Accelerate. ---- - -Here is a list of ready-to-run example projects that demonstrate how to use Prisma Accelerate: - -| Demo | Description | -| ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| [`nextjs-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nextjs-starter) | A Next.js project using Prisma Accelerate's caching and connection pooling | -| [`svelte-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/svelte-starter) | A SvelteKit project using Prisma Accelerate's caching and connection pooling | -| [`solidstart-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/solidstart-starter) | A Solidstart project using Prisma Accelerate's caching and connection pooling | -| [`remix-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/remix-starter) | A Remix project using Prisma Accelerate's caching and connection pooling | -| [`nuxt-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nuxtjs-starter) | A Nuxt.js project using Prisma Accelerate's caching and connection pooling | -| [`astro-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/astro-starter) | An Astro project using Prisma Accelerate's caching and connection pooling | -| [`accelerate-hacker-news`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/accelerate-hacker-news) | A simple Hacker News clone built with Prisma Accelerate, demonstrating the use of on-demand cache invalidation | -| [`prisma-accelerate-invalidation`](https://github.com/prisma/prisma-accelerate-invalidation) | An app demonstrating how long it takes to invalidate a cached query result using on-demand cache invalidation. | diff --git a/apps/docs/content/docs.v6/accelerate/faq.mdx b/apps/docs/content/docs.v6/accelerate/faq.mdx deleted file mode 100644 index 699d09ab37..0000000000 --- a/apps/docs/content/docs.v6/accelerate/faq.mdx +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Accelerate FAQ -description: Frequently asked questions about Accelerate. -url: /v6/accelerate/faq -metaTitle: 'Accelerate: FAQ' -metaDescription: Frequently asked questions about Accelerate. ---- - -## When should I enable static IP for Prisma Accelerate? - -Enable static IP for Accelerate when your security setup requires IP allowlisting or if you're implementing firewalls that only permit access from trusted IPs, ensuring controlled and secure database connections. - -![Result of enabling static IP Accelerate with a database using IP allowlisting](/img/accelerate/result-of-adding-static-ip-to-accelerate.png) - -Learn more on [how to enable static IP for Accelerate in the Platform Console](/v6/accelerate/static-ip). - -:::info -**What is a static IP?** - -A static IP address is an IPv4 or an IPv6 address that is fixed. Unlike dynamic IP addresses, which can change unpredictably, traffic from static IP addresses can be easily identified. - -![What is a static IP](/img/accelerate/static-ip.png) -::: - -> ℹ️ To enable static IP support for Accelerate within your existing or new project environment, your workspace will need to be on our **Pro** or **Business** plans. Take a look at the [pricing page](https://www.prisma.io/pricing#accelerate) for more information. - -## Why do I sometimes see unexpected cache behavior? - -Accelerate's cache performs best when it observes a higher load from a project. Many cache operations, such as committing data to cache and refreshing stale data, happen asynchronously. When benchmarking Accelerate, we recommend doing so with loops or a load testing approach. This will mimic higher load scenarios better and reduce outliers from low frequency operations. - -Prisma operations are sent to Accelerate over HTTP. As a result, the first request to Accelerate must establish an HTTP handshake and may have additional latency as a result. We're exploring ways to reduce this initial request latency in the future. - -## What is the pricing of Accelerate? - -You can find more details on our [Accelerate pricing page](https://www.prisma.io/pricing) - -## VS Code does not recognize the `$extends` method - -If you add the Prisma Client extension for Accelerate to an existing project that is currently open in VS Code, the editor might not immediately recognize the `$extends` method. - -This might be an issue with the TypeScript server not yet recognizing the regenerated Prisma Client. To resolve this, you need to restart TypeScript. - -1. In VS Code, open the Command Palette. You can do so when you press F1 or select **View** > **Command Palette**. -2. Enter `typescript` and select and run the **TypeScript: Restart TS server** command. - -VS Code should now recognize the `$extends` method. - -## What regions are Accelerate's cache nodes available in? - -Accelerate runs on Cloudflare's network and cache hits are served from Cloudflare's 300+ locations. You can find the regions where Accelerate's cache nodes are available here: [https://www.cloudflare.com/network/](https://www.cloudflare.com/network/). - -## What regions is Accelerate's connection pool available in? - -When no cache strategy is specified or in the event of a cache miss, the Prisma Client query is routed through Accelerate's connection pool. Currently, queries can be routed through any chosen region among the 16 available locations. - -Currently, the list of available regions are: - -- Asia Pacific, Mumbai (`ap-south-1`) -- Asia Pacific, Seoul (`ap-northeast-2`) -- Asia Pacific, Singapore (`ap-southeast-1`) -- Asia Pacific, Sydney (`ap-southeast-2`) -- Asia Pacific, Tokyo (`ap-northeast-1`) -- Canada, Central (`ca-central-1`) -- Europe, Frankfurt (`eu-central-1`) -- Europe, Ireland (`eu-west-1`) -- Europe, London (`eu-west-2`) -- Europe, Paris (`eu-west-3`) -- Europe, Stockholm (`eu-north-1`) -- South America, Sao Paulo (`sa-east-1`) -- US East, N. Virginia (`us-east-1`) -- US East, Ohio (`us-east-2`) -- US West, N. California (`us-west-1`) -- US West, Oregon (`us-west-2`) - -You can also view the available regions when you're about to set up Accelerate or by visiting the **Settings** tab for Accelerate under the **Region** section in the Prisma Cloud Platform [dashboard](https://pris.ly/pdp). - -## How does Accelerate know what region to fetch the cache from? - -Under the hood, Accelerate uses Cloudflare, which uses [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/) for network addressing and routing. An incoming request will be routed to the nearest data center or "node" in their network that has the capacity to process the request efficiently. To learn more about how this works, we recommend looking into [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/). - -## How can I invalidate a cache on Accelerate? - -You can invalidate the cache on-demand via the [`$accelerate.invalidate` API](/v6/accelerate/api-reference#accelerateinvalidate) if you're on a [paid plan](https://www.prisma.io/pricing#accelerate), or you can invalidate your entire cache, on a project level, a maximum of five times a day. This limit is set based on [your plan](https://www.prisma.io/pricing#accelerate). You can manage this via the Accelerate configuration page. - -## What is Accelerate's consistency model? - -Accelerate does not have a consistency model. It is not a distributed system where nodes need to reach a consensus (because data is only stored in the cache node(s) closest to the user). However, the data cached in Accelerate's cache nodes doesn't propagate to other nodes, so Accelerate by design doesn't need a consistency model. - -Accelerate implements a [read-through caching strategy](https://www.prisma.io/dataguide/managing-databases/introduction-database-caching#read-through) particularly suitable for read-heavy workloads. - -The freshness of the data served by the cache depends on the cache strategy defined in your query. Refer to [this section](/v6/postgres/database/caching#selecting-a-cache-strategy) for more information on selecting the right cache strategy for your query. - -## How is Accelerate different from other caching tools, such as Redis? - -- Accelerate is a _specialized_ cache that allows you to optimize data access in code at the query level with a cache strategy. On the other hand, tools such as Redis and Memcached are _general-purpose_ caches designed to be adaptable and flexible. -- Accelerate is a managed service that reduces the time, risk, and engineering effort of building and maintaining a cache service. -- By default, Accelerate is globally distributed, reducing the latency of your queries. Other cache tools would require additional configuration to make them available globally. - -## When should I not use Accelerate's caching features? - -Accelerate is a global data cache and connection pool that allows you to optimize data access in code at the query level. While caching with Accelerate can greatly boost the performance of your app, it may not always the best choice for your use case. - -Accelerate's global cache feature may not be a good fit for your app if: - -- Your app is exclusively used within a specific region and both your application server and database are situated in that same region on the same network. For example, database queries will likely be much faster if your application server and database are in the same region and network. However, If your application server is in different regions or networks from your database, Accelerate will speed up your queries because the data will be cached in the closest data center to your application. - -- You _only_ need a general-purpose cache. Accelerate is a connection pooler and a _specialized cache_ that only caches your database query responses in code. A general-purpose cache, such as Redis, would allow you to cache data from multiple sources, such as external APIs, which Accelerate currently doesn't support. If general-purpose caching interests you, please share your feedback with us via our [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=inline_text). - -- Your application data _always_ needs to be up-to-date on retrieval, making it difficult to establish a reasonable cache strategy. - -Even without using Accelerate's global cache, you can still greatly benefit from Accelerate by using its connection pool, especially in serverless or edge functions, where it is difficult to manage and scale database connections. You can learn more about the serverless challenge [here](/v6/orm/prisma-client/setup-and-configuration/databases-connections#the-serverless-challenge). - -## Can I use Accelerate with other ORMs/query builders/drivers? - -No. We currently do not have any plans for supporting other ORMs/query builders or drivers. However, if you're interested in support for other libraries, feel free to reach out and let us know in our [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=inline_text) community in the `#help-and-questions` channel. - -## What is the maximum allowed value for the `ttl` parameter when configuring `cacheStrategy`? - -The [Time-to-live](/v6/postgres/database/caching#time-to-live-ttl) (`ttl`) parameter can be set for up to a _year_. However, it's important to note that items within the cache may be evicted if they are not frequently accessed. - -Based on our experimentation, we’ve seen cache items persist for around 18 hours. While items may remain in the cache for an extended period if they are actively accessed, there is no guarantee. - -> **Note**: Even frequently accessed items may occasionally be evicted from the cache. It's unlikely for an item to survive for up to or longer than a month, regardless of its activity level. - -## Why doesn’t Accelerate fall back to the direct connection string during a service disruption? - -In the rare event of a service disruption, falling back to a direct connection would bypass the connection pool. This could potentially deplete the database's available connections and cause other issues on the database level. - -If there is a service disruption, it's recommended to verify on the [status page](https://pris.ly/data-platform-status). You can reach out to one of Prisma's [support channels](/v6/platform/support) for assistance. - -> **Note:** Additionally, it's worth noting that some edge function runtime environments may not support direct connections with Prisma ORM. For further details, refer to our [Edge functions documentation](/v6/orm/prisma-client/deployment/edge/overview). - -## Are each of the queries within an interactive transaction counted separately for billing? - -Yes, [interactive transactions](/v6/orm/prisma-client/queries/transactions#interactive-transactions) are billed based on the individual operations within the transaction. There is no charge for the start, commit, or rollback of the transaction itself. For example, in the following query, there are two billable queries: - -```ts -await prisma.$transaction(async (tx) => { - await tx.user.deleteMany({ where: { name: "John Doe" } }); - await tx.user.createMany({ data }); -}); -``` - -However, when using the [`$transaction` API for sequential client operations](/v6/orm/prisma-client/queries/transactions#sequential-prisma-client-operations), regardless of the number of queries within the array, it counts as only one billable query. For example: - -```ts -await prisma.$transaction([ - prisma.user.deleteMany({ where: { name: "John Doe" } }), - prisma.user.createMany({ data }), -]); -``` - -If you don't need [interactive transactions](/v6/orm/prisma-client/queries/transactions#interactive-transactions), you can save costs and improve performance by using [sequential operations transactions](/v6/orm/prisma-client/queries/transactions#sequential-prisma-client-operations). Sequential operations transactions perform better on Accelerate because they execute in one round-trip to the database, while interactive transactions require separate round-trips for start, commit, and each individual operation on the transaction. - -## Can I increase my Accelerate query duration and response size limits? - -Yes, you can increase your Accelerate limits based on your subscription plan. Here are the configurable limits: - -| Limit | Free | Starter | Pro Plan | Business Plan | -| ------------------------------------ | ---------------- | ---------------- | ---------------- | ---------------- | -| **Query timeout** | Up to 10 seconds | Up to 10 seconds | Up to 20 seconds | Up to 60 seconds | -| **Interactive transactions timeout** | Up to 15 seconds | Up to 15 seconds | Up to 30 seconds | Up to 90 seconds | -| **Response size** | Up to 5 MB | Up to 5 MB | Up to 10 MB | Up to 20 MB | - -Check the [pricing page](https://www.prisma.io/pricing#accelerate) for more details on the available plans and their corresponding limits. - -:::warning -While you can increase these limits based on your subscription plan, it's _still_ recommended to optimize your database operations. [Learn more in our troubleshooting guide.](/v6/postgres/database/api-reference/error-reference) -::: - -## How long does it take to invalidate a cache query result? - -As the cache needs to be cleared globally, it is difficult to provide a specific time frame. However, the cached data is eventually consistent and typically propagates to all PoPs within a few seconds. In very rare cases, it may take longer. - -Here is a [demo app](https://pris.ly/test-cache-invalidation) to test the time it takes to invalidate a cache query result. - -## What is the difference between **Invalidate** and **Revalidate**? - -**Invalidate**: The cache entry is deleted, and new data will be fetched on the next request, causing a cache miss. This removes stale data but may lead to slower responses until the cache is repopulated. - -**Revalidate**: The cache entry is updated proactively, ensuring the next request uses fresh data from the cache. This keeps the cache valid and maintains faster response times by avoiding cache misses. - -## What is on-demand cache invalidation? - -[On-demand cache invalidation](/v6/postgres/database/caching#on-demand-cache-invalidation) lets applications instantly update specific cached data when it changes, instead of waiting for regular cache refresh cycles. This keeps information accurate and up-to-date for users. - -## When should I use the cache invalidate API? - -The [cache invalidate API](/v6/postgres/database/caching#on-demand-cache-invalidation) is essential when data consistency cannot wait for the cache’s standard expiration or revalidation. Key use cases include: - -- **Content updates**: When critical changes occur, such as edits to a published article, product updates, or profile modifications, that need to be visible immediately. -- **Inventory management**: In real-time applications, like inventory or booking systems, where stock levels, availability, or reservation statuses must reflect the latest information. -- **High-priority data**: For time-sensitive data, like breaking news or urgent notifications, where it’s essential for users to see the most current information right away. - -Using on-demand cache invalidation in these scenarios helps keep only the necessary data refreshed, preserving system performance while ensuring accurate, up-to-date information for users. - -## How does Accelerate count queries for billing? - -Accelerate counts queries at the Prisma Client invocation level. A single Prisma query may translate into multiple SQL statements under the hood, but it will only count as one query for billing purposes. This ensures straightforward, predictable billing that reflects the Prisma Client usage rather than the complexity of the underlying SQL operations. - -Queries are counted regardless of whether they are served from the cache or the database. Even if a query is retrieved from the cache, it still counts toward your query limit. - -## How do I switch from GitHub login to email and password login? - -If you previously signed up using GitHub and want to switch to email and password login, follow these steps: - -### 1. Verify Your GitHub Email Address - -- Check the primary email address associated with your GitHub account (e.g., from your GitHub profile or notification settings). - -### 2. Create a New Email/Password Account - -- Go to the email/password sign-up page. -- Use the **same email address** linked to your GitHub account to create the new account. -- Our system will automatically connect your new email/password account to your existing data. - -### 3. Test Your Login - -- Log out and try logging in with your email and the password you just created. - -> **Note**: If you encounter any issues, please contact our support team for help linking your accounts. diff --git a/apps/docs/content/docs.v6/accelerate/feedback.mdx b/apps/docs/content/docs.v6/accelerate/feedback.mdx deleted file mode 100644 index e2742de529..0000000000 --- a/apps/docs/content/docs.v6/accelerate/feedback.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Feedback -description: Learn where to submit feedback about Accelerate. -url: /v6/accelerate/feedback -metaTitle: 'Accelerate: Feedback' -metaDescription: Learn where to submit feedback about Accelerate. ---- - -You can submit any feedback about Accelerate in our [Discord server](https://pris.ly/discord?utm_source=docs&utm_medium=intro_text). diff --git a/apps/docs/content/docs.v6/accelerate/getting-started.mdx b/apps/docs/content/docs.v6/accelerate/getting-started.mdx deleted file mode 100644 index 7284e7ba98..0000000000 --- a/apps/docs/content/docs.v6/accelerate/getting-started.mdx +++ /dev/null @@ -1,252 +0,0 @@ ---- -title: Getting started with Prisma Accelerate -description: Learn how to get up and running with Prisma Accelerate. -url: /v6/accelerate/getting-started -metaTitle: Getting started with Prisma Accelerate -metaDescription: Learn how to get up and running with Prisma Accelerate. ---- - -## Prerequisites - -To get started with Accelerate, you will need the following: - -- A [Prisma Data Platform account](https://console.prisma.io) -- A project that uses [Prisma Client](/v6/orm/prisma-client/setup-and-configuration/introduction) `4.16.1` or higher. If your project is using interactive transactions, you need to use `5.1.1` or higher. (We always recommend using the latest version of Prisma.) -- A hosted PostgreSQL, MySQL/MariaDB, PlanetScale, CockroachDB, or MongoDB database - -## 1. Enable Accelerate - -Navigate to your Prisma Data Platform project, choose an environment, and enable Accelerate by providing your database connection string and selecting the region nearest your database. - -:::note - -If you require IP allowlisting or firewall configurations with trusted IP addresses, enable Static IP for enhanced security. Learn more on [how to enable static IP for Accelerate in the Platform Console](/v6/accelerate/static-ip). - -::: - -## 2. Add Accelerate to your application - -### 2.1. Update your database connection string - -Once enabled, you'll be prompted to generate a connection string that you'll use to authenticate requests. - -Replace your direct database url with your new Accelerate connection string. - -```bash title=".env" -# New Accelerate connection string -DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" - -# Previous (direct) database connection string -# DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" -``` - -Prisma Client reads the `prisma://` URL from `DATABASE_URL` at runtime, while Prisma CLI commands use the connection string defined in `prisma.config.ts`. - -Prisma Migrate and Introspection do not work with a `prisma://` connection string. In order to continue using these features add a new variable to the `.env` file named `DIRECT_DATABASE_URL` whose value is the direct database connection string: - -```bash title=".env" -DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" -DIRECT_DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" # [!code ++] -``` - -Then point `prisma.config.ts` to the direct connection string: - -```ts title="prisma.config.ts" showLineNumbers -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - datasource: { - url: env("DIRECT_DATABASE_URL"), - }, -}); -``` - -Migrations and introspections will use the `directUrl` connection string rather than the one defined in `url` when this configuration is provided. - -> `directUrl` is useful for you to carry out migrations and introspections. However, you don't need `directUrl` to use Accelerate in your application. - -:::note -If you are using Prisma with PostgreSQL, there is no need for `directUrl`, as Prisma Migrate and Introspection work with the `prisma+postgres://` connection string. -::: - -### 2.2. Install the Accelerate Prisma Client extension - -:::info - -💡 Accelerate requires [Prisma Client](/v6/orm/prisma-client/setup-and-configuration/introduction) version `4.16.1` or higher and [`@prisma/extension-accelerate`](https://www.npmjs.com/package/@prisma/extension-accelerate) version `1.0.0` or higher. - -💡 Accelerate extension [`@prisma/extension-accelerate`](https://www.npmjs.com/package/@prisma/extension-accelerate) version `2.0.0` and above requires Node.js version `18` or higher. - -::: - -Install the latest version of Prisma Client and Accelerate Prisma Client extension - -```npm -npm install @prisma/client@latest @prisma/extension-accelerate -``` - -### 2.3. Generate Prisma Client for Accelerate - -If you're using Prisma version `5.2.0` or greater, Prisma Client will automatically determine how it should connect to the database depending on the protocol in the database connection string. If the connection string in the `DATABASE_URL` starts with `prisma://`, Prisma Client will try to connect to your database using Prisma Accelerate. - -When using Prisma Accelerate in long-running application servers, such as a server deployed on AWS EC2, you can generate the Prisma Client by executing the following command: - -```npm -npx prisma generate -``` - -When using Prisma Accelerate in a Serverless or an Edge application, we recommend you to run the following command to generate Prisma Client: - -```npm -npx prisma generate --no-engine -``` - -The `--no-engine` flag prevents a Query Engine file from being included in the generated Prisma Client, this ensures the bundle size of your application remains small. - -:::warning - -If your Prisma version is below `5.2.0`, generate Prisma Client with the `--accelerate` option: - -```npm -npx prisma generate --accelerate -``` - -If your Prisma version is below `5.0.0`, generate Prisma Client with the `--data-proxy` option: - -```npm -npx prisma generate --data-proxy -``` - -::: - -### 2.4. Extend your Prisma Client instance with the Accelerate extension - -Add the following to extend your existing Prisma Client instance with the Accelerate extension: - -```ts -import { PrismaClient } from "@prisma/client"; -import { withAccelerate } from "@prisma/extension-accelerate"; - -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, -}).$extends(withAccelerate()); -``` - -If you are going to deploy to an edge runtime (like Cloudflare Workers, Vercel Edge Functions, Deno Deploy, or Supabase Edge Functions), use our edge client instead: - -```ts -import { PrismaClient } from "@prisma/client/edge"; -import { withAccelerate } from "@prisma/extension-accelerate"; - -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, -}).$extends(withAccelerate()); -``` - -If VS Code does not recognize the `$extends` method, refer to [this section](/v6/accelerate/faq#vs-code-does-not-recognize-the-extends-method) on how to resolve the issue. - -#### Using the Accelerate extension with other extensions - -Since [extensions are applied one after another](/v6/orm/prisma-client/client-extensions#conflicts-in-combined-extensions), make sure you apply them in the correct order. Extensions cannot share behavior and the last extension applied takes precedence. - -If you are using [Query Insights](/query-insights) in your application, make sure you apply it _before_ the Accelerate extension. For example: - -```ts -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, -}) - .$extends(withOptimize()) - .$extends(withAccelerate()); -``` - -### 2.5. Use Accelerate in your database queries - -The `withAccelerate` extension primarily does two things: - -- Gives you access to the `cacheStrategy` field within each applicable model method that allows you to define a cache strategy per-query. -- Routes all of your queries through a connection pooler. - -#### No cache strategy to only use connection pool - -If you simply want to take advantage of Accelerate's connection pooling feature without applying a cache strategy, you may run your query the same way you would have without Accelerate. - -By enabling Accelerate and supplying the Accelerate connection string, your queries now use the connection pooler by default. - -#### Define a cache strategy - -Update a query with the new `cacheStrategy` property which allows you to define a cache strategy for that specific query: - -```ts -const user = await prisma.user.findMany({ - where: { - email: { - contains: "alice@prisma.io", - }, - }, - cacheStrategy: { swr: 60, ttl: 60 }, -}); -``` - -In the example above, `swr: 60` and `ttl: 60` means Accelerate will serve cached data for 60 seconds and then another 60 seconds while Accelerate fetches fresh data in the background. - -You should now see improved performance for your cached queries. - -For information about which strategy best serves your application, see [Select a cache strategy](/v6/postgres/database/caching#selecting-a-cache-strategy). - -:::info - -As of Prisma version `5.2.0` you can use Prisma Studio with the Accelerate connection string. - -::: - -#### Invalidate the cache and keep your cached query results up-to-date - -If your application requires real-time or near-real-time data, cache invalidation ensures that users see the most current data, even when using a large `ttl` (Time-To-Live) or `swr` (Stale-While-Revalidate) [cache strategy](/v6/postgres/database/caching#cache-strategies). By invalidating your cache, you can bypass extended caching periods to show live data whenever it's needed. - -For example, if a dashboard displays customer information and a customer’s contact details change, cache invalidation allows you to refresh only that data instantly, ensuring support staff always see the latest information without waiting for the cache to expire. - -To invalidate a cached query result, you can add tags and then use the `$accelerate.invalidate` API. - -:::note - -On-demand cache invalidation is available with our paid plans. For more details, please see our [pricing](https://www.prisma.io/pricing#accelerate). - -::: - -To invalidate the query below: - -```ts -await prisma.user.findMany({ - where: { - email: { - contains: "alice@prisma.io", - }, - }, - cacheStrategy: { - swr: 60, - ttl: 60, - tags: ["emails_with_alice"], // [!code highlight] - }, -}); -``` - -You need to provide the cache tag in the `$accelerate.invalidate` API: - -```ts -try { - await prisma.$accelerate.invalidate({ - // [!code highlight] - tags: ["emails_with_alice"], // [!code highlight] - }); // [!code highlight] -} catch (e) { - if (e instanceof Prisma.PrismaClientKnownRequestError) { - // The .code property can be accessed in a type-safe manner - if (e.code === "P6003") { - console.log("You've reached the cache invalidation rate limit. Please try again shortly."); - } - } - throw e; -} -``` diff --git a/apps/docs/content/docs.v6/accelerate/index.mdx b/apps/docs/content/docs.v6/accelerate/index.mdx deleted file mode 100644 index ac53dae537..0000000000 --- a/apps/docs/content/docs.v6/accelerate/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Prisma Accelerate -description: Prisma Accelerate is a global database cache with built-in connection pooling that helps improve database performance in Serverless and Edge applications. -url: /v6/accelerate -metaTitle: Prisma Accelerate -metaDescription: Prisma Accelerate is a global database cache with built-in connection pooling that helps improve database performance in Serverless and Edge applications. ---- - -[Prisma Accelerate](https://www.prisma.io/accelerate) is a fully managed global connection pool and caching layer for your existing database, enabling query-level cache policies directly from the Prisma ORM. - -With 15+ global regions, the connection pool scales your app for a global audience, particularly for serverless deployments that risk connection timeouts during peak times. - -Accelerate's global cache, hosted in 300+ locations, ensures a fast experience for users, regardless of your database's location. - -You can configure query-level caching strategies directly in your code with Prisma ORM, making setup and tuning easy. - -Together, the connection pool and cache allow you to scale effortlessly and handle traffic spikes without infrastructure concerns. - -## Supported databases - -Accelerate works with the database you already have, whether it is publicly accessible, or via an IP allowlist. - -- PostgreSQL -- MySQL -- MariaDB -- PlanetScale -- CockroachDB -- MongoDB - -## Getting started - -- [Getting started](/v6/accelerate/getting-started) - Set up connection pooling and global caching -- [Connection pooling](/v6/accelerate/connection-pooling) - Scale your database connections -- [Caching](/v6/accelerate/caching) - Global database cache with TTL and SWR diff --git a/apps/docs/content/docs.v6/accelerate/known-limitations.mdx b/apps/docs/content/docs.v6/accelerate/known-limitations.mdx deleted file mode 100644 index 4ffe4eb5ab..0000000000 --- a/apps/docs/content/docs.v6/accelerate/known-limitations.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Known limitations about Prisma Accelerate -description: Learn about limitations of Accelerate. -url: /v6/accelerate/known-limitations -metaTitle: 'Accelerate: limitations' -metaDescription: Learn about limitations of Accelerate. ---- - -Below are descriptions of known limitations when using Accelerate. If you encounter any additional ones, please share them with us via [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=intro_text). - -## Cannot cache raw queries - -At the moment, it is not possible to cache the responses of [raw queries](/v6/orm/prisma-client/using-raw-sql/raw-queries). - -## Not compatible with the fluent API - -Client Extensions (which are used in Accelerate) currently do not correctly forward the [fluent API](/v6/orm/prisma-client/queries/relation-queries#fluent-api) types. We hope to get a fix into Client Extensions soon. - -## Not compatible with extremely heavy or long-running queries - -Accelerate is designed to work with high-performance, low-latency queries. It is not intended for use with extremely heavy or long-running queries that may cause performance issues or resource contention. While limits are configurable, we recommend optimizing your queries to ensure they fit within the recommended guidelines. - -For queries that cannot be optimized or pared down, we recommend one of two solutions: - -1. **Use the read replica extension**: The Prisma ORM [read replica extension](https://www.npmjs.com/package/@prisma/extension-read-replicas) allows you to set up two different connections: a `primary` and a `replica`. You can set up your Accelerate connection as the `primary` and then a direct connection as the `replica`. Any queries that are resource-intensive or long-running can then be routed to the `replica`, while the `primary` (your Accelerate connection) will handle normal queries. **Please note** that this solution requires you to both set up a direct connection and requires the full generated Prisma Client (i.e. without `--no-engine`). - -2. **Separate analytics queries**: Our preferred solution is to separate your analytics queries into a separate application. This separate application can then use a direct connection so that it can run heavy queries without impacting the performance or cost of your Accelerate-powered application. - -If you have a use case that requires running extremely heavy or long-running queries and Prisma Accelerate, please reach out to us. - -## Not compatible with direct IPv4 addresses in MongoDB connection strings - -Accelerate does not support direct IPv4 addresses in MongoDB connection strings. When an IPv4 address is provided, Accelerate converts it to an IPv6 format to route through its NAT gateway. This conversion may cause the connection string to be considered invalid due to the formatting of the port value. - -**Workaround**: To resolve this issue, create a DNS record that points to your IPv4 address and use that DNS record in your connection string instead of the direct IP. - -### Example - -- **IPv4 connection string** (not supported): `mongodb://user:password@192.168.1.100:27017/db_name` -- **DNS record connection string** (supported): `mongodb://user:password@my-database.example.com:27017/db_name` - -For additional details on Accelerate’s IPv6-first design, refer to our [blog post](https://www.prisma.io/blog/accelerate-ipv6-first). diff --git a/apps/docs/content/docs.v6/accelerate/local-development.mdx b/apps/docs/content/docs.v6/accelerate/local-development.mdx deleted file mode 100644 index 657f161964..0000000000 --- a/apps/docs/content/docs.v6/accelerate/local-development.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Local development for Prisma Accelerate -description: Learn how to use Prisma Accelerate in a development environment. -url: /v6/accelerate/local-development -metaTitle: 'Accelerate: Local development' -metaDescription: Learn how to use Prisma Accelerate in a development environment. ---- - -Prisma Accelerate efficiently scales production traffic with integrated connection pooling and a global database cache. - -In development environments, you may want to use a local database to minimize expenses. Furthermore, you may consider extending Prisma Client with the Accelerate client extension once so that you can use a local database in development and a hosted database with Accelerate’s connection pooling and caching enabled. This eliminates the need for conditional logic to switch clients between development and production. - -This guide will explain how to use Prisma Accelerate client extension in a development environment with a local database. - -## Using Prisma Accelerate client extension in development and production - -
- -![Using Prisma Accelerate client extension in development](/img/accelerate/accelerate-in-dev.png) - -Accelerate does not work with a local database. However, in a development environment, you can still use Prisma Client with the Accelerate client extension. This setup will not provide Accelerate's connection pooling and caching features. - -The following steps outline how to use Prisma ORM and Prisma Accelerate with a local PostgreSQL database. - -1. Update the `DATABASE_URL` environment variable with your local database's connection string: - - ```bash - DATABASE_URL="postgres://username:password@127.0.0.1:5432/localdb" - ``` - -2. Generate a Prisma Client: - - ```npm - npx prisma generate - ``` - - > Note: The `--no-engine` flag should only be used in preview and production environments. The command generates Prisma Client artifacts without a [Query Engine](/v6/orm/more/internals/engines) file, which requires an Accelerate connection string. - -3. Set up Prisma Client with the Accelerate client extension: - - ```typescript - import { PrismaClient } from "@prisma/client"; - import { withAccelerate } from "@prisma/extension-accelerate"; - - const prisma = new PrismaClient().$extends(withAccelerate()); - ``` - - > The extended instance of Prisma Client will use the local database. Hence, Prisma Accelerate will not be used in your development environment to respond to your Prisma Client queries. - -![Using Prisma Accelerate client extension in production](/img/accelerate/accelerate-in-prod.png) - -If an Accelerate connection string is used as the `DATABASE_URL` environment variable, Prisma Client will route your queries through Accelerate. - -## Using Prisma Accelerate locally in an edge function - -When using an edge function, e.g., [Vercel's edge runtime](https://vercel.com/docs/functions/runtimes/edge-runtime), for your development environment, update your Prisma Client import as follows: - -```typescript -import { PrismaClient } from "@prisma/client/edge"; -``` - -Generally, edge function environments lack native support for existing APIs enabling TCP-based database connections. Prisma Accelerate provides a connection string that allows querying your database over HTTP, a protocol supported in all edge runtimes. diff --git a/apps/docs/content/docs.v6/accelerate/meta.json b/apps/docs/content/docs.v6/accelerate/meta.json deleted file mode 100644 index 6fab8f1bfa..0000000000 --- a/apps/docs/content/docs.v6/accelerate/meta.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "title": "Accelerate", - "root": true, - "pages": [ - "index", - "getting-started", - "caching", - "connection-pooling", - "local-development", - "static-ip", - "examples", - "evaluating", - "compare", - "troubleshoot", - "faq", - "known-limitations", - "api-reference", - "feedback" - ] -} diff --git a/apps/docs/content/docs.v6/accelerate/static-ip.mdx b/apps/docs/content/docs.v6/accelerate/static-ip.mdx deleted file mode 100644 index f570a8e869..0000000000 --- a/apps/docs/content/docs.v6/accelerate/static-ip.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Static IP -description: Learn enabling Static IP for Prisma Accelerate. -url: /v6/accelerate/static-ip -metaTitle: Enable Static IP for Prisma Accelerate -metaDescription: Learn enabling Static IP for Prisma Accelerate. ---- - -You can enable static IP for Accelerate when your security setup requires IP allowlisting or if you're implementing firewalls that only permit access from trusted IPs, ensuring controlled and secure database connections. - -![Result of enabling static IP Accelerate with a database using IP allowlisting](/img/accelerate/result-of-adding-static-ip-to-accelerate.png) - -:::info - -To enable static IP support for Accelerate within an existing or a new project environment, your workspace will need to be on our Pro or Business plans. Take a look at the [pricing page](https://www.prisma.io/pricing#accelerate) for more information. - -::: - -## Enable static IP in Accelerate - -You can opt-in to use static IP for Accelerate in the [Platform Console](https://pris.ly/pdp) in two ways: - -### 1. When enabling Accelerate for your project environment: - -1. Specify your database connection string and connection pool region. -2. Enable static IP by toggling the **Static IP** switch in the **Network restrictions** section. -3. Click on the **Enable Accelerate** button. - -### 2. For projects already using Accelerate: - -1. Navigate to the Accelerate **Settings** tab in the project environment. -2. Enable static IP by toggling the **Static IP** switch in the **Network restrictions** section. - -Enabling static IP for Accelerate will provide you with a list of static IPv4 and IPv6 addresses. - -Once you have these addresses, configure your database firewall to allow incoming connections only from these IPs and any other trusted IPs that need access to your database. - -:::note - -Since you cannot enable static IP for an existing Accelerate-enabled environment, we recommend opting for static IP when enabling Accelerate in a new environment. Use the same database URL as your existing Accelerate environment to instantly access static IP support for Accelerate. - -::: diff --git a/apps/docs/content/docs.v6/accelerate/troubleshoot.mdx b/apps/docs/content/docs.v6/accelerate/troubleshoot.mdx deleted file mode 100644 index 2e21373712..0000000000 --- a/apps/docs/content/docs.v6/accelerate/troubleshoot.mdx +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: Troubleshooting Prisma Accelerate issues -description: Troubleshooting Prisma Accelerate. -url: /v6/accelerate/troubleshoot -metaTitle: 'Troubleshooting: Prisma Accelerate' -metaDescription: Troubleshooting Prisma Accelerate. ---- - -When working with Prisma Accelerate, you may encounter errors often highlighted by specific error codes during development and operations. It is important to understand the meaning of these errors, why they occur, and how to resolve them in order to ensure the smooth operation of your applications. This guide aims to provide insights and steps to troubleshoot specific error codes encountered with Prisma Accelerate. - -## [`P6009`](/v6/orm/reference/error-reference#p6009-responsesizelimitexceeded) (`ResponseSizeLimitExceeded`) - -This error is triggered when the response size from a database query exceeds [the configured query response size limit](/v6/postgres/database/connection-pooling#response-size-limit). We've implemented this restriction to safeguard your application performance, as retrieving data over 5MB can significantly slow down your application due to multiple network layers. Typically, transmitting more than 5MB of data is common when conducting ETL (Extract, Transform, Load) operations. However, for other scenarios such as transactional queries, real-time data fetching for user interfaces, bulk data updates, or aggregating large datasets for analytics outside of ETL contexts, it should generally be avoided. These use cases, while essential, can often be optimized to work within [the configured query response size limit](/v6/postgres/database/connection-pooling#response-size-limit), ensuring smoother performance and a better user experience. - -### Possible causes for [`P6009`](/v6/orm/reference/error-reference#p6009-responsesizelimitexceeded) - -#### Transmitting images/files in response - -This error may arise if images or files stored within your table are being fetched, resulting in a large response size. Storing assets directly in the database is generally discouraged because it significantly impacts database performance and scalability. In addition to performance, it makes database backups slow and significantly increases the cost of storing routine backups. - -**Suggested solution:** Configure the [query response size limit](/v6/postgres/database/connection-pooling#response-size-limit) to be larger. If the limit is still exceeded, consider storing the image or file in a BLOB store like [Cloudflare R2](https://developers.cloudflare.com/r2/), [AWS S3](https://aws.amazon.com/pm/serv-s3/), or [Cloudinary](https://cloudinary.com/). These services allow you to store assets optimally and return a URL for access. Instead of storing the asset directly in the database, store the URL, which will substantially reduce the response size. - -#### Over-fetching of data - -In certain cases, a large number of records or fields are unintentionally fetched, which results in exceeding [the configured query response size limit](/v6/postgres/database/connection-pooling#response-size-limit). This could happen when the [`where`](/v6/orm/reference/prisma-client-reference#where) clause in the query is incorrect or entirely missing. - -**Suggested solution:** Configure the [query response size limit](/v6/postgres/database/connection-pooling#response-size-limit) to be larger. If the limit is still exceeded, double-check that the `where` clause is filtering data as expected. To prevent fetching too many records, consider using [pagination](/v6/orm/prisma-client/queries/pagination). Additionally, use the [`select`](/v6/orm/reference/prisma-client-reference#select) clause to return only the necessary fields, reducing the response size. - -#### Fetching a large volume of data - -In many data processing workflows, especially those involving ETL (Extract-Transform-Load) processes or scheduled CRON jobs, there's a need to extract large amounts of data from data sources (like databases, APIs, or file systems) for analysis, reporting, or further processing. If you are running an ETL/CRON workload that fetches a huge chunk of data for analytical processing then you might run into this limit. - -**Suggested solution:** Configure the [query response size limit](/v6/postgres/database/connection-pooling#response-size-limit) to be larger. If the limit is exceeded, consider splitting your query into batches. This approach ensures that each batch fetches only a portion of the data, preventing you from exceeding the size limit for a single operation. - -## [`P6004`](/v6/orm/reference/error-reference#p6004-querytimeout) (`QueryTimeout`) - -This error occurs when a database query fails to return a response within [the configured query timeout limit](/v6/postgres/database/connection-pooling#query-timeout-limit). The query timeout limit includes the duration of waiting for a connection from the pool, network latency to the database, and the execution time of the query itself. We enforce this limit to prevent unintentional long-running queries that can overload system resources. - -> The time for Accelerate's cross-region networking is excluded from [the configured query timeout limit](/v6/postgres/database/connection-pooling#query-timeout-limit) limit. - -### Possible causes for [`P6004`](/v6/orm/reference/error-reference#p6004-querytimeout) - -This error could be caused by numerous reasons. Some of the prominent ones are: - -#### High traffic and insufficient connections - -If the application is receiving very high traffic and there are not a sufficient number of connections available to the database, then the queries would need to wait for a connection to become available. This situation can lead to queries waiting longer than [the configured query timeout limit](/v6/postgres/database/connection-pooling#query-timeout-limit) for a connection, ultimately triggering a timeout error if they do not get serviced within this duration. - -**Suggested solution**: Review and possibly increase the `connection_limit` specified in the connection string parameter when setting up Accelerate in a platform environment ([reference](/v6/postgres/database/connection-pooling#configuring-the-connection-pool-size)). This limit should align with your database's maximum number of connections. - -By default, the connection limit is set to 10 unless a different `connection_limit` is specified in your database connection string. - -#### Long-running queries - -Queries may be slow to respond, hitting [the configured query timeout limit](/v6/postgres/database/connection-pooling#query-timeout-limit) even when connections are available. This could happen if a very large amount of data is being fetched in a single query or if appropriate indexes are missing from the table. - -**Suggested solution**: Configure the [query timeout limit](/v6/postgres/database/connection-pooling#query-timeout-limit) to be larger. If the limit is exceeded, identify the slow-running queries and fetch only the necessary data. Use the `select` clause to retrieve specific fields and avoid fetching unnecessary data. Additionally, consider adding appropriate indexes to improve query efficiency. You might also isolate long-running queries into separate environments to prevent them from affecting transactional queries. - -#### Database resource contention - -A common yet challenging issue is when other services operating on the same database perform heavy analytics or data processing tasks, significantly consuming database resources. These operations can monopolize database connections and processing power, leading to a scenario where even simple queries cannot be executed in a timely manner. This "busy" or "noisy" database environment can cause queries that are typically fast to run slowly or even timeout, particularly during periods of high activity from other services. - -Users often rely on CPU and memory usage metrics to gauge database load, which can be misleading. While these are important indicators, they might not fully represent the database's operational state. Direct metrics like the number of reads, writes, and wait times offer a clearer view of the database's performance and should be monitored closely. A noticeable degradation in these metrics, especially in the absence of changes to the queries or data model, suggests that external pressures are affecting database performance. - -**Suggested solution**: If normally quick queries are intermittently slow or timing out without any modifications to them, it's probable that competing queries are exerting pressure on the same database tables. To diagnose this, adopt monitoring tools or leverage your database's inherent capabilities to observe reads, writes, and wait times. Such monitoring will unveil activity patterns or spikes that align with the observed performance dips. - -Moreover, it's crucial to periodically scrutinize and refine essential queries and verify that tables are properly indexed. This proactive approach minimizes the vulnerability of these queries to slowdowns caused by competing workloads. - -### Considerations for [`P6009`](/v6/orm/reference/error-reference#p6009-responsesizelimitexceeded) and [`P6004`](/v6/orm/reference/error-reference#p6004-querytimeout) errors - -For runtimes that support Prisma ORM natively, you could consider creating two `PrismaClient` Instances. One with the Accelerate connection string (prefixed with `prisma://`) and the other one with the direct database connection string (prefixed with `postgres://`, `mysql://` etc). The main idea behind this approach is to bypass Accelerate for certain specific queries. - -However, please note that the available connections would be split between both of your `PrismaClient` Instances. It's crucial to understand the implications of managing multiple instances, particularly in regards to direct database connections. Utilizing a `PrismaClient` instance with a direct database connection string means that this connection will interact directly with your database. - -This approach requires careful consideration because the direct connections and those managed by Accelerate share the same underlying database connection pool. This can lead to competition for resources, potentially affecting the performance and availability of your database services. - -Additionally, direct connections could have a significant impact on your database's performance and availability. Operations that consume a considerable amount of resources could potentially degrade the service for other users or processes that rely on the same database. - -If your application's runtime environment supports Prisma ORM natively and you're considering this strategy to circumvent P6009 and P6004 errors, you might create two `PrismaClient` instances: - -1. An instance using the Accelerate connection string (prefixed with `prisma://`) for general operations. -2. Another instance with the direct database connection string (e.g., prefixed with `postgres://`, `mysql://`, etc.) for specific operations anticipated to exceed [the configured query limit timeout](/v6/postgres/database/connection-pooling#query-timeout-limit) or to result in responses larger than [the configured query response size limit](/v6/postgres/database/connection-pooling#response-size-limit). - -```jsx -export const prisma = new PrismaClient({ - datasourceUrl: process.env.DIRECT_DB_CONNECTION, -}); - -export const prismaAccelerate = new PrismaClient({ - datasourceUrl: process.env.ACCELERATE_CONNECTION, -}).$extends(withAccelerate()); -``` - -This setup allows you to strategically direct certain operations through the direct connection, mitigating the risk of encountering the aforementioned errors. However, this decision should be made with a comprehensive understanding of the potential consequences and an assessment of whether your database infrastructure can support this additional load without compromising overall performance and availability. - -> Also see [**why doesn’t Accelerate fall back to the direct connection string during a service disruption?**](/v6/accelerate/faq#why-doesnt-accelerate-fall-back-to-the-direct-connection-string-during-a-service-disruption) - -## [`P6008`](/v6/orm/reference/error-reference#p6008-connectionerrorenginestarterror) (`ConnectionError|EngineStartError`) - -This error indicates that Prisma Accelerate cannot establish a connection to your database, potentially due to several reasons. - -### Possible causes for [`P6008`](/v6/orm/reference/error-reference#p6008-connectionerrorenginestarterror) - -#### Database Not Publicly accessible - -If your database is within a VPC or access is limited to specific IP addresses, you might encounter this error if static IP is not enabled for Accelerate or if the static IPs are not permitted in your database firewall. - -**Suggested solution:** [Enable static IP for Accelerate](/v6/accelerate/static-ip) and configure your database firewall to allow access from the provided static IP addresses. - -#### Unreachable Database Host/Port - -If the database’s server address (hostname) and port are incorrect or unreachable then you may encounter this error. - -**Suggested solution:** Verify the hostname/port of the database connection string that was provided while creating the Prisma Accelerate project. Additionally, attempt to connect to the database using a Database GUI tool (e.g., [Prisma Studio](https://www.prisma.io/studio), [TablePlus](https://tableplus.com/), or [DataGrip](https://www.jetbrains.com/datagrip/)) for further investigation. - -#### Incorrect username/password/database name - -This error can happen when the wrong credentials are provided to Prisma Accelerate, preventing it from establishing a connection to your database. - -**Suggested solution:** Verify the correctness of your database's username, password, and name in the connection string provided to Prisma Accelerate. Ensure that these credentials match those required by your database. Testing the connection using a direct database GUI tool can also help in confirming if the provided credentials are correct. - -#### Database taking too long to respond - -If the database is taking too long to respond to the connection request, Prisma Accelerate may timeout and throw this error. This could happen if the database is not active or is waking up from sleep mode. - -**Suggested solution:** Verify that the database is active and reachable. If the database is in sleep mode, try to wake it up by sending a request to it using a direct database GUI tool or wake it up using the database's management console. - -## [`P5011`](/v6/orm/reference/error-reference#p5011-too-many-requests) (`TooManyRequests`) - -This error occurs when Prisma Accelerate detects a high volume of requests that surpasses allowable thresholds. It acts as a protective measure to safeguard both Prisma Accelerate and your underlying database from excessive load. - -### Possible causes for [`P5011`](/v6/orm/reference/error-reference#p5011-too-many-requests) - -#### Aggressive retry loops - -If your application retries queries immediately or with minimal delay, especially after receiving certain errors, the rapid accumulation of requests can surpass the threshold. - -**Suggested solution:** - -- Implement an exponential backoff strategy. Rather than retrying immediately or with a fixed delay, gradually increase the delay period after each failed attempt. -- This allows the system time to recover and reduces the likelihood of overwhelming Prisma Accelerate and your database. - -#### Sudden traffic spikes - -Unpredicted traffic surges (for example, during product launches, flash sales, or viral growth events) can cause the threshold to be met and result into `P5011`. - -**Suggested solution:** - -- Consider proactive scaling strategies for both Prisma Accelerate and your database. -- Monitor traffic and resource usage. If you anticipate a surge, please contact [support](/v6/platform/support) for capacity planning and potential configuration adjustments. - -#### Prolonged or planned high workloads - -Certain processes, such as bulk data imports, ETL operations, or extended CRON jobs, can generate continuous high query volume over time. - -**Suggested solution:** - -- Use batching or chunking techniques to break large operations into smaller parts. -- Establish throttling or scheduling to distribute the load more evenly. - -## Other errors - -### Error with MySQL (Aiven): "We were unable to process your request. Please refresh and try again." - -#### Issue - -When using an Aiven MySQL connection string that includes the `?ssl-mode=REQUIRED` parameter, you may encounter the following error: - -``` -We were unable to process your request. Please refresh and try again. -``` - -#### Cause - -The `ssl-mode=REQUIRED` parameter is incompatible with Accelerate, which leads to connection issues. - -#### Suggested solution - -To resolve this error, remove the `?ssl-mode=REQUIRED` parameter from your MySQL connection string. - -#### Example - -- Original connection string: `mysql://username:password@host:port/database?ssl-mode=REQUIRED` -- Updated connection string: `mysql://username:password@host:port/database` diff --git a/apps/docs/content/docs.v6/ai/index.mdx b/apps/docs/content/docs.v6/ai/index.mdx deleted file mode 100644 index 3750662629..0000000000 --- a/apps/docs/content/docs.v6/ai/index.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Build faster with Prisma + AI -description: Learn about AI features in Prisma -url: /v6/ai -metaTitle: AI -metaDescription: AI ---- - -In the era of AI, where code is increasingly written by agents, ensuring clarity, type safety, and reliable infrastructure is essential. With 5+ years of leadership in the TypeScript ecosystem, Prisma ORM and Prisma Postgres provide the proven foundation for AI-assisted development. - -## Get started - -Run the following command to bootstrap your database with a prompt: - -```npm -npx prisma init --prompt "Create a habit tracker application" -``` - -## AI Coding Tools - -Prisma ORM and Prisma Postgres integrate seamlessly with your AI coding tools. Check out our documentation with tips and tricks for working with Prisma in various AI editors. - -- [Cursor](/v6/orm/more/ai-tools/cursor) - Define project-specific rules and use your schema as context to generate accurate queries and code. -- [Windsurf](/v6/orm/more/ai-tools/windsurf) - Automate your database workflows by generating schemas, queries, and seed data in this AI-powered editor. -- [Github Copilot](/v6/orm/more/ai-tools/github-copilot) - Get Prisma-aware code suggestions, run CLI commands from chat, and query the Prisma docs. -- [ChatGPT](/v6/orm/more/ai-tools/chatgpt) - Learn how to connect the Prisma MCP server to ChatGPT to manage your databases with natural language. - -## MCP server - -With Prisma's MCP server, your AI tool can take database actions on your behalf: Provisioning a new Prisma Postgres instance, creating database backups and executing SQL queries are just a few of its capabilities. - -```json title="Integrate in AI tool" -{ - "mcpServers": { - "Prisma-Remote": { - "url": "https://mcp.prisma.io/mcp" - } - } -} -``` - -- [Capabilities and tools](/v6/postgres/integrations/mcp-server#tools) - Discover all the tools that make up the capabilities of the Prisma MCP server. -- [Integrating in AI tools](/v6/postgres/integrations/mcp-server#integrating-in-ai-tools) - Learn how to integrate Prisma's MCP server in your favorite AI tool, such as Cursor, Claude, Warp, and more. -- [How we built it](https://www.prisma.io/blog/about-mcp-servers-and-how-we-built-one-for-prisma) - Read this technical deep dive about the MCP protocol and how we built the Prisma MCP server. - -## Vibe Coding Tutorials - -Build complete, production-ready applications from scratch with AI assistance. - -- [Build a Linktree Clone SaaS](/v6/ai/tutorials/linktree-clone) - A complete vibe coding tutorial: build a full Linktree clone SaaS with Next.js, Prisma Postgres, and Clerk auth using AI assistance. - -## Resources - -- [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](/v6/guides/ai-sdk-nextjs) - in a Next.js application - -## Integrations - -- [Automate with Pipedream](https://pipedream.com/apps/prisma-management-api) - Connect Prisma Postgres to 2,800+ apps for powerful automations -- [Firebase Studio](/v6/postgres/integrations/idx) - Prompt your application with Firebase Studio & Prisma Postgres diff --git a/apps/docs/content/docs.v6/ai/meta.json b/apps/docs/content/docs.v6/ai/meta.json deleted file mode 100644 index 0fadf86aff..0000000000 --- a/apps/docs/content/docs.v6/ai/meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "title": "AI", - "root": true, - "pages": ["index"] -} diff --git a/apps/docs/content/docs.v6/ai/prompts/astro.mdx b/apps/docs/content/docs.v6/ai/prompts/astro.mdx deleted file mode 100644 index 7229d21b7e..0000000000 --- a/apps/docs/content/docs.v6/ai/prompts/astro.mdx +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Set up Astro + Prisma + Prisma Postgres -description: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project. -image: /img/ai/astro-prisma-cover.png -url: /v6/ai/prompts/astro -metaTitle: How to Initialize an Astro App with Prisma ORM and Prisma Postgres -metaDescription: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an Astro.js project. ---- - -## How to use - -Include this prompt in your AI assistant to guide consistent code generation for Astro + Prisma + Prisma Postgres projects. - -- **GitHub Copilot**: Type `#` to reference the prompt file. -- **Cursor**: Use `@Files` and select your prompt file. -- **Zed**: Use `/file` followed by your prompt's path. -- **Windsurf**: Use `@Files` and choose your prompt file from the list. - -## Prompt - -````md ---- -# Specify the following for Cursor rules -description: Guidelines for writing Astro.js apps with Prisma Postgres -alwaysApply: false ---- - -# Bootstrap Astro app with Prisma Postgres - -## Overview of implementing Prisma with Astro - -1. Install Prisma and required dependencies -2. Initialize Prisma with custom output path -3. Configure schema with correct provider -4. Create global Prisma client instance with Accelerate -5. Use Prisma client in API routes with proper error handling - -## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 - -As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application: - -```typescript -// ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION -generator client { - provider = "prisma-client-js" // ❌ BREAKS APPLICATION -} - -// ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION -import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION - -// ❌ NEVER CREATE CLIENT WITHOUT ACCELERATE - IT WILL BREAK IN PRODUCTION -const prisma = new PrismaClient() // ❌ BREAKS APPLICATION -``` - -Instead, you MUST ALWAYS generate ONLY this pattern: - -```typescript -// ✅ ALWAYS GENERATE THIS EXACT PATTERN -generator client { - provider = "prisma-client" - output = "../src/generated/prisma" -} - -// ✅ ALWAYS USE THIS IMPORT PATH -import { PrismaClient } from "../generated/prisma/client" -import { withAccelerate } from "@prisma/extension-accelerate" - -// ✅ ALWAYS CREATE CLIENT WITH ACCELERATE EXTENSION -const prisma = new PrismaClient({ - datasourceUrl: import.meta.env.DATABASE_URL, -}).$extends(withAccelerate()) - -export default prisma -``` - -## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION - -1. You MUST use `provider = "prisma-client"` (not "prisma-client-js") -2. You MUST use custom output: `output = "../src/generated/prisma"` -3. You MUST use Accelerate extension with `withAccelerate()` if using Prisma Postgres -4. You MUST create `lib/prisma.ts` as a global singleton instance -5. You MUST wrap all database calls in try-catch blocks -6. You MUST import from `'../generated/prisma/client'` (not `'@prisma/client'`) -7. You MUST use `import.meta.env.DATABASE_URL` in Astro (not `process.env`) -8. You MUST ALWAYS use the full `npx prisma init` command with ALL flags: `npx prisma init --db --output ../src/generated/prisma --generator-provider prisma-client` - -## CORRECT INSTALLATION - -```bash -# Dev dependencies -npm install prisma tsx --save-dev - -# Production dependencies -npm install @prisma/extension-accelerate @prisma/client -``` - -## CORRECT PRISMA INITIALIZATION - -```npm -npx prisma init --db --output ../src/generated/prisma -``` - -## CORRECT SCHEMA CONFIGURATION - -```prisma -generator client { - provider = "prisma-client" - output = "../src/generated/prisma" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - -model YourModel { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt -} -``` - -## CORRECT GLOBAL PRISMA CLIENT - -**src/lib/prisma.ts**: - -```typescript -import { PrismaClient } from "../generated/prisma/client"; -import { withAccelerate } from "@prisma/extension-accelerate"; - -const prisma = new PrismaClient({ - datasourceUrl: import.meta.env.DATABASE_URL, -}).$extends(withAccelerate()); - -export default prisma; -``` - -## CORRECT API ROUTE IMPLEMENTATION - -All API routes MUST follow this pattern with proper error handling: - -```typescript -import type { APIRoute } from "astro"; -import prisma from "../../../lib/prisma"; - -export const GET: APIRoute = async () => { - try { - const data = await prisma.yourModel.findMany(); - return new Response(JSON.stringify(data), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - } catch (error) { - console.error("Error:", error); - return new Response(JSON.stringify({ error: "Failed to fetch data" }), { - status: 500, - headers: { "Content-Type": "application/json" }, - }); - } -}; - -export const POST: APIRoute = async ({ request }) => { - try { - const body = await request.json(); - - // Validate required fields - if (!body.requiredField) { - return new Response(JSON.stringify({ error: "Required field missing" }), { - status: 400, - headers: { "Content-Type": "application/json" }, - }); - } - - const result = await prisma.yourModel.create({ - data: body, - }); - - return new Response(JSON.stringify(result), { - status: 201, - headers: { "Content-Type": "application/json" }, - }); - } catch (error) { - console.error("Error:", error); - return new Response(JSON.stringify({ error: "Failed to create data" }), { - status: 500, - headers: { "Content-Type": "application/json" }, - }); - } -}; -``` - -## CORRECT USAGE IN ASTRO PAGES - -Server-side data fetching in Astro pages: - -```astro ---- -import prisma from '../lib/prisma' - -// Fetch data on the server -const data = await prisma.yourModel.findMany() ---- - - - - {data.map(item => ( -
{item.name}
- ))} - - -``` - -## AI MODEL VERIFICATION STEPS - -Before generating any code, you MUST verify: - -1. Are you using `provider = "prisma-client"` (not "prisma-client-js")? If not, STOP and FIX. -2. Are you using `output = "../src/generated/prisma"`? If not, STOP and FIX. -3. Are you importing from `'../generated/prisma/client'`? If not, STOP and FIX. -4. Are you using `withAccelerate()` extension? If not, STOP and FIX. -5. Are you wrapping database operations in try-catch? If not, STOP and FIX. -6. Are you using `import.meta.env` (not `process.env`)? If not, STOP and FIX. -7. Did you use `--generator-provider prisma-client` (NOT `postgresql`)? If not, STOP and FIX. - -## CONSEQUENCES OF INCORRECT IMPLEMENTATION - -If you generate code using: - -- `prisma-client-js` provider -- Default import from `@prisma/client` -- PrismaClient without Accelerate extension -- Missing custom output path - -The implementation will: - -1. Break in production -2. Cause connection pool exhaustion -3. Fail to maintain proper database connections -4. Result in import errors -5. Cause performance issues - -## USEFUL COMMANDS - -```npm -npx prisma generate # Regenerate client after schema changes -``` - -```npm -npx prisma migrate dev --name X # Create and apply migration -``` - -```npm -npx prisma studio # Open visual database editor -``` - -```npm -npx prisma db push # Push schema without migration -``` - -## AI MODEL RESPONSE TEMPLATE - -When asked about Prisma + Astro implementation, you MUST: - -1. ONLY use code from this guide -2. NEVER suggest deprecated approaches -3. ALWAYS use the exact patterns shown above -4. VERIFY your response against the patterns shown here -5. ALWAYS include error handling in API routes -6. ALWAYS use the global prisma instance from `lib/prisma.ts` - -Remember: There are NO EXCEPTIONS to these rules. -```` - -## Running the application - -Get your application running locally in three quick steps: - -**1. Generate the Prisma Client:** - -```bash -npx prisma generate --no-engine -``` - -**2. View your database in Prisma Studio:** - -```bash -npm run db:studio -``` - -Prisma Studio opens at `localhost:5555` where you can inspect your `User` table and see the test user stored in your database. - -**3. Start your Next.js development server:** - -```bash -npm run dev -``` - -Visit `http://localhost:3000` to see your Next.js application live, displaying your first user fetched directly from your Prisma Postgres database! diff --git a/apps/docs/content/docs.v6/ai/prompts/nextjs.mdx b/apps/docs/content/docs.v6/ai/prompts/nextjs.mdx deleted file mode 100644 index 64abe95d8b..0000000000 --- a/apps/docs/content/docs.v6/ai/prompts/nextjs.mdx +++ /dev/null @@ -1,637 +0,0 @@ ---- -title: Set up NextJS + Prisma + Prisma Postgres -description: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project. -url: /v6/ai/prompts/nextjs -metaTitle: How to Initialize an NextJS App with Prisma ORM and Prisma Postgres -metaDescription: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in an NextJS project. ---- - -## Prerequisites - -Before using this prompt, you need to create a new Next.js project: - -```bash -npx create-next-app@latest my-app -cd my-app -``` - -When prompted, select the following recommended options: - -- **TypeScript**: Yes -- **ESLint**: Yes -- **Tailwind CSS**: Yes (optional) -- **`src/` directory**: No -- **App Router**: Yes -- **Turbopack**: Yes (optional) -- **Import alias**: Use default (`@/*`) - -Once your Next.js project is created, you can use the prompt below with your AI assistant to add Prisma and Prisma Postgres. - -## How to use - -Include this prompt in your AI assistant to guide consistent code generation for NextJS + Prisma + Prisma Postgres projects. - -- **GitHub Copilot**: Type `#` to reference the prompt file. -- **Cursor**: Use `@Files` and select your prompt file. -- **Zed**: Use `/file` followed by your prompt's path. -- **Windsurf**: Use `@Files` and choose your prompt file from the list. - -## Video Tutorial - -Watch this step-by-step walkthrough showing this prompt in action: - -
- -
- -## Prompt - -````md ---- -# Specify the following for Cursor rules -description: Guidelines for writing Next.js apps with Prisma Postgres -alwaysApply: false ---- - -# Bootstrap Next.js app with Prisma Postgres (Prisma 7) - -> **Note**: This guide is updated for **Prisma ORM 7**. Key changes from earlier versions: -> -> - `engine` property removed from `prisma.config.ts` -> - `url` removed from datasource in `schema.prisma` (now only in `prisma.config.ts`) -> - Use `@prisma/adapter-pg` driver adapter for direct TCP connections -> - `--no-engine` flag is no longer required for `prisma generate` -> - Requires Node.js 20.19+ and TypeScript 5.4.0+ - -## Overview of implementing Prisma with Next.js - -1. Install Prisma and required dependencies (including dotenv) -2. Initialize Prisma and configure schema -3. Configure dotenv for environment variables -4. Create global Prisma client instance with Pg Adapter -5. Add npm scripts for testing and database management -6. Create test script to verify setup -7. Use Prisma client in API routes and pages with proper error handling - -## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 - -As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application: - -```typescript -// ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION -generator client { - provider = "prisma-client-js" // ❌ BREAKS APPLICATION -} - -// ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION -import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION - -// ❌ WRONG IMPORT PATH - MISSING /client - IT WILL BREAK THE APPLICATION -import { PrismaClient } from "../app/generated/prisma" // ❌ BREAKS APPLICATION - -// ❌ NEVER USE ACCELERATE - IT IS NOT USED IN THIS WORKFLOW -import { withAccelerate } from "@prisma/extension-accelerate" // ❌ BREAKS APPLICATION - -// ❌ NEVER USE accelerateUrl - IT WILL BREAK THE APPLICATION -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, // ❌ BREAKS APPLICATION - use adapter -}) - -// ❌ NEVER include url in datasource block - IT WILL BREAK THE APPLICATION -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") // ❌ BREAKS APPLICATION - moved to prisma.config.ts -} - -// ❌ NEVER include engine property - IT WILL BREAK THE APPLICATION -export default defineConfig({ - engine: "classic", // ❌ BREAKS APPLICATION - removed in Prisma 7 -}) - -// ❌ NEVER use Prisma Postgres HTTP URLs - ONLY use TCP URLs -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..." // ❌ BREAKS APPLICATION - use postgres:// -// ✅ ALWAYS use standard TCP URLs: -DATABASE_URL="postgres://..." // ✅ CORRECT -``` - -Instead, you MUST ALWAYS generate ONLY this pattern: - -```typescript -// ✅ ALWAYS GENERATE THIS EXACT PATTERN -generator client { - provider = "prisma-client" - output = "../app/generated/prisma" -} - -// ✅ CRITICAL: MUST include /client at the end of import path -import { PrismaClient } from "../app/generated/prisma/client" -import { PrismaPg } from "@prisma/adapter-pg" - -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}) - -const globalForPrisma = global as unknown as { prisma: PrismaClient } - -const prisma = globalForPrisma.prisma || new PrismaClient({ - adapter, -}) - -if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma - -export default prisma -``` - -## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION - -1. You MUST use `provider = "prisma-client"` (not "prisma-client-js") -2. You MUST use custom output: `output = "../app/generated/prisma"` -3. You MUST use `@prisma/adapter-pg` driver adapter -4. You MUST create `lib/prisma.ts` as a global singleton instance -5. You MUST wrap all database calls in try-catch blocks -6. You MUST import from `'../app/generated/prisma/client'` (not `'@prisma/client'` or `'../app/generated/prisma'`) -7. You MUST use `adapter` property in PrismaClient constructor -8. You MUST install `dotenv` and add `import "dotenv/config"` to `prisma.config.ts` -9. You MUST add npm scripts for `db:test` and `db:studio` to package.json -10. You MUST create a test script at `scripts/test-database.ts` to verify setup -11. You MUST NOT include `url` in the datasource block of `schema.prisma` -12. You MUST NOT include `engine` property in `prisma.config.ts` -13. You MUST use `npx prisma init --db --output ../app/generated/prisma` to create a real cloud database -14. You MUST use standard TCP URLs (`postgres://...`) in .env -15. You MUST NOT use `accelerateUrl` or `withAccelerate` - -## VERSION REQUIREMENTS - -- **Node.js**: 20.19 or higher (Node.js 18 is NOT supported) -- **TypeScript**: 5.4.0 or higher (5.9.x recommended) -- **Prisma**: 7.0.0 or higher - -## CORRECT INSTALLATION - -```bash -# Dev dependencies -npm install prisma tsx --save-dev - -# Production dependencies -npm install @prisma/adapter-pg @prisma/client dotenv -``` - -## CORRECT PRISMA INITIALIZATION - -> **FOR AI ASSISTANTS**: This command is **interactive** and requires user input. You **MUST ask the user to run this command manually** in their own terminal, then **wait for them to confirm completion** before proceeding with the next steps. Do NOT attempt to run this command yourself. - -```bash -# Initialize Prisma AND create a real Prisma Postgres cloud database -npx prisma init --db --output ../app/generated/prisma -``` - -This command: - -- Authenticates you with Prisma Console (if needed) -- Prompts for **region** and **project name** -- **Creates a cloud Prisma Postgres database** -- Generates: - - `prisma/schema.prisma` (with correct output path) - - `prisma.config.ts` (with dotenv import) - - **`.env` with a `DATABASE_URL`** - -**IMPORTANT**: Ensure the generated `.env` uses a `postgres://` URL scheme. If it generates `prisma+postgres://`, replace it with the standard TCP connection string available in the Prisma Console. - -```text -DATABASE_URL="postgres://..." -``` - -**IMPORTANT**: Do NOT use `npx prisma init` without `--db` as this only creates local files without a database. - -## CORRECT PRISMA CONFIG (prisma.config.ts) - -When using `npx prisma init --db`, the `prisma.config.ts` is **auto-generated** with the correct configuration: - -```typescript -import "dotenv/config"; // ✅ Auto-included by prisma init --db -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - // ✅ NO engine property - removed in Prisma 7 - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -**Note**: If you need to manually create this file, ensure `import "dotenv/config"` is at the top. - -## CORRECT SCHEMA CONFIGURATION (prisma/schema.prisma) - -Update the generated `prisma/schema.prisma` file: - -```prisma -generator client { - provider = "prisma-client" - output = "../app/generated/prisma" -} - -datasource db { - provider = "postgresql" - // ✅ NO url here - now configured in prisma.config.ts -} - -// Example User model for testing -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt -} -``` - -## CORRECT GLOBAL PRISMA CLIENT - -Create `lib/prisma.ts` file: - -```typescript -import { PrismaClient } from "../app/generated/prisma/client"; // ✅ CRITICAL: Include /client -import { PrismaPg } from "@prisma/adapter-pg"; - -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}); - -const globalForPrisma = global as unknown as { prisma: PrismaClient }; - -const prisma = - globalForPrisma.prisma || - new PrismaClient({ - adapter, - }); - -if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; - -export default prisma; -``` - -## ADD NPM SCRIPTS TO PACKAGE.JSON - -Update your `package.json` to include these scripts: - -```json -{ - "scripts": { - "dev": "next dev", - "build": "next build", - "start": "next start", - "lint": "eslint", - "db:test": "tsx scripts/test-database.ts", - "db:studio": "prisma studio" - } -} -``` - -## CREATE TEST SCRIPT - -Create `scripts/test-database.ts` to verify your setup: - -```typescript -import "dotenv/config"; // ✅ CRITICAL: Load environment variables -import prisma from "../lib/prisma"; - -async function testDatabase() { - console.log("🔍 Testing Prisma Postgres connection...\n"); - - try { - // Test 1: Check connection - console.log("✅ Connected to database!"); - - // Test 2: Create a test user - console.log("\n📝 Creating a test user..."); - const newUser = await prisma.user.create({ - data: { - email: "demo@example.com", - name: "Demo User", - }, - }); - console.log("✅ Created user:", newUser); - - // Test 3: Fetch all users - console.log("\n📋 Fetching all users..."); - const allUsers = await prisma.user.findMany(); - console.log(`✅ Found ${allUsers.length} user(s):`); - allUsers.forEach((user) => { - console.log(` - ${user.name} (${user.email})`); - }); - - console.log("\n🎉 All tests passed! Your database is working perfectly.\n"); - } catch (error) { - console.error("❌ Error:", error); - process.exit(1); - } -} - -testDatabase(); -``` - -## CORRECT API ROUTE IMPLEMENTATION (App Router) - -Create `app/api/users/route.ts` with GET and POST handlers: - -```typescript -import { NextRequest, NextResponse } from "next/server"; -import prisma from "../../../lib/prisma"; - -export async function GET(request: NextRequest) { - try { - const users = await prisma.user.findMany(); - return NextResponse.json(users); - } catch (error) { - console.error("Error fetching users:", error); - return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 }); - } -} - -export async function POST(request: NextRequest) { - try { - const body = await request.json(); - const user = await prisma.user.create({ - data: { - email: body.email, - name: body.name, - }, - }); - return NextResponse.json(user, { status: 201 }); - } catch (error) { - console.error("Error creating user:", error); - return NextResponse.json({ error: "Failed to create user" }, { status: 500 }); - } -} -``` - -## CORRECT USAGE IN SERVER COMPONENTS - -Update `app/page.tsx` to display users from the database: - -```typescript -import prisma from "../lib/prisma" - -export default async function Home() { - let users: Array<{ - id: number - email: string - name: string | null - createdAt: Date - updatedAt: Date - }> = [] - let error = null - - try { - users = await prisma.user.findMany({ - orderBy: { - createdAt: "desc", - }, - }) - } catch (e) { - console.error("Error fetching users:", e) - error = "Failed to load users. Make sure your DATABASE_URL is configured." - } - - return ( -
-

Users from Database

- {error ? ( -

{error}

- ) : users.length === 0 ? ( -

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

- ) : ( -
    - {users.map((user) => ( -
  • -

    {user.name || "No name"}

    -

    {user.email}

    -
  • - ))} -
- )} -
- ) -} -``` - -## COMPLETE SETUP WORKFLOW - -User should follow these steps (AI should provide these instructions): - -1. **Install dependencies**: - - ```npm - npm install prisma tsx --save-dev - ``` - - ```npm - npm install @prisma/adapter-pg @prisma/client dotenv - ``` - -2. **Initialize Prisma AND create Prisma Postgres database** (⚠️ USER MUST RUN MANUALLY): - - > **AI ASSISTANT**: Ask the user to run this command in their own terminal. This is interactive and requires user input. Wait for the user to confirm completion before continuing. - - ```npm - npx prisma init --db --output ../app/generated/prisma - ``` - - The user should follow the terminal prompts to: - - Authenticate with Prisma Console (if needed) - - Choose a region (e.g., us-east-1) - - Name your project - - Once complete, this creates `prisma/schema.prisma`, `prisma.config.ts`, AND `.env` with the `DATABASE_URL`. - - **User should confirm when done** so the AI can proceed with the next steps. - -3. **Verify `.env` was created** - Ensure `DATABASE_URL` uses `postgres://`. If it uses `prisma+postgres://`, change it to the TCP connection string. - - ```text - DATABASE_URL="postgres://..." - ``` - - **Do NOT invent or manually change this URL. Use the one from Prisma Console.** - -4. **Update `prisma/schema.prisma`** - Add the User model (generator and datasource are already configured): - - ```prisma - model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - } - ``` - -5. **Create `lib/prisma.ts`** with correct import path including `/client` and using `@prisma/adapter-pg`. - -6. **Add npm scripts** to `package.json` for `db:test` and `db:studio` - -7. **Create `scripts/test-database.ts`** test script - -8. **Push schema to database**: - - ```npm - npx prisma db push - ``` - -9. **Generate Prisma Client**: - - ```npm - npx prisma generate - ``` - -10. **Test the setup**: - - ```bash - npm run db:test - ``` - -11. **Start development server**: - ```bash - npm run dev - ``` - -## AI MODEL VERIFICATION STEPS - -Before generating any code, you MUST verify: - -1. Are you using `provider = "prisma-client"` (not "prisma-client-js")? If not, STOP and FIX. -2. Are you using `output = "../app/generated/prisma"`? If not, STOP and FIX. -3. Are you importing from `'../app/generated/prisma/client'` (with `/client`)? If not, STOP and FIX. -4. Did you add `import "dotenv/config"` to `prisma.config.ts`? If not, STOP and FIX. -5. Did you add `import "dotenv/config"` to `scripts/test-database.ts`? If not, STOP and FIX. -6. Are you using `@prisma/adapter-pg`? If not, STOP and FIX. -7. Are you using `adapter` property in PrismaClient constructor? If not, STOP and FIX. -8. Are you wrapping database operations in try-catch? If not, STOP and FIX. -9. Did you create the test script at `scripts/test-database.ts`? If not, STOP and FIX. -10. Did you add `db:test` and `db:studio` scripts to package.json? If not, STOP and FIX. -11. Did you remove `url` from the datasource block in `schema.prisma`? If not, STOP and FIX. -12. Did you remove `engine` property from `prisma.config.ts`? If not, STOP and FIX. -13. Are you using `npx prisma init --db` (not just `npx prisma init`)? If not, STOP and FIX. -14. Is the DATABASE_URL a TCP URL (`postgres://...`)? If it's a `prisma+postgres://` URL, STOP and FIX. -15. Did Prisma generate the `.env` file? If you invented the URL manually, STOP and FIX. - -## CONSEQUENCES OF INCORRECT IMPLEMENTATION - -If you generate code using: - -- `prisma-client-js` provider → **CLIENT GENERATION FAILS** -- Wrong import path (missing `/client`) → **MODULE NOT FOUND ERROR** -- Missing `import "dotenv/config"` in prisma.config.ts → **DATABASE_URL NOT FOUND ERROR** -- Missing `import "dotenv/config"` in test scripts → **ENVIRONMENT VARIABLE ERROR** -- Default import from `@prisma/client` → **IMPORT ERROR** -- Using `accelerateUrl` or `withAccelerate` → **UNNECESSARY ACCELERATE DEPENDENCY / CONFIG ERROR** -- Missing custom output path → **WRONG CLIENT GENERATED** -- Including `url` in datasource block → **DEPRECATED CONFIGURATION ERROR** -- Including `engine` property → **DEPRECATED CONFIGURATION ERROR** -- Using local URL (`postgres://localhost:...`) → **VERSION INCOMPATIBILITY ERRORS WITH PRISMA 7** -- Using `npx prisma init` without `--db` → **NO DATABASE CREATED, ONLY LOCAL FILES** -- Manually inventing DATABASE_URL → **INVALID CONNECTION STRING ERRORS** - -The implementation will: - -1. Break immediately with module errors -2. Fail to read environment variables -3. Cause connection pool exhaustion in production -4. Result in import errors that prevent compilation -5. Cause performance issues and connection failures -6. Fail with "HTTP connection string is not supported" errors when using local URLs - -## USEFUL COMMANDS - -```bash -# After changing schema -npx prisma generate # Regenerate client (--no-engine flag no longer needed) - -# Push schema to database (no migrations) -npx prisma db push - -# Test database connection -npm run db:test - -# Open visual database editor -npm run db:studio - -# Create and apply migrations (for production) -npx prisma migrate dev --name your_migration_name -``` - -## TESTING WORKFLOW - -After setup, test with these steps: - -1. **Test database connection**: - - ```bash - npm run db:test - ``` - - Should create a demo user and display it. - -2. **Open Prisma Studio**: - - ```bash - npm run db:studio - ``` - - Visual interface at `localhost:5555` to view/edit data. - -3. **Test API routes**: - - ```bash - # Create a user via API - curl -X POST http://localhost:3000/api/users \ - -H "Content-Type: application/json" \ - -d '{"email":"test@example.com","name":"Test User"}' - - # Get all users - curl http://localhost:3000/api/users - ``` - -4. **View in browser**: - Open `localhost:3000` to see users displayed on the homepage. - -## AI MODEL RESPONSE TEMPLATE - -When asked about Prisma + Next.js implementation, you MUST: - -1. ONLY use code patterns from this guide -2. NEVER suggest deprecated approaches -3. ALWAYS use the exact patterns shown above -4. ALWAYS include `/client` in import paths -5. ALWAYS add `import "dotenv/config"` to prisma.config.ts -6. ALWAYS add `import "dotenv/config"` to test scripts -7. ALWAYS create the test script at `scripts/test-database.ts` -8. ALWAYS add npm scripts for `db:test` and `db:studio` -9. ALWAYS include error handling in API routes and server components -10. ALWAYS use the global prisma instance from `lib/prisma.ts` -11. ALWAYS use `@prisma/adapter-pg` and `adapter` property -12. NEVER include `url` in the datasource block of schema.prisma -13. NEVER include `engine` property in prisma.config.ts -14. ALWAYS ask the user to run `npx prisma init --db --output ../app/generated/prisma` **manually in their own terminal** (this command is interactive and requires user input for region and project name) -15. ALWAYS wait for user confirmation after they run the interactive `prisma init --db` command before proceeding -16. NEVER attempt to run interactive commands yourself - ask the user to do it -17. NEVER use `prisma+postgres://` URLs - ONLY `postgres://` TCP URLs -18. NEVER manually invent or fabricate DATABASE_URL values -19. ALWAYS let Prisma generate the `.env` file with the real DATABASE_URL (and ensure it's correct type) -20. VERIFY your response against ALL the patterns shown here before responding - -Remember: There are NO EXCEPTIONS to these rules. Every requirement is MANDATORY for the setup to work. -```` diff --git a/apps/docs/content/docs.v6/ai/prompts/prisma-7.mdx b/apps/docs/content/docs.v6/ai/prompts/prisma-7.mdx deleted file mode 100644 index 36515fc7a2..0000000000 --- a/apps/docs/content/docs.v6/ai/prompts/prisma-7.mdx +++ /dev/null @@ -1,459 +0,0 @@ ---- -title: Migrating to Prisma 7 -description: Step-by-step guide for migration your app to use the version 7 of Prisma ORM -url: /v6/ai/prompts/prisma-7 -metaTitle: How to upgrade to Prisma ORM version 7 -metaDescription: Step-by-step guide for migration your app to use the version 7 of Prisma ORM ---- - -## How to use - -Include this prompt in your AI assistant to guide in upgrading to Prisma ORM 7.0. - -- **GitHub Copilot**: Type `#` to reference the prompt file. -- **Cursor**: Use `@Files` and select your prompt file. -- **Zed**: Use `/file` followed by your prompt's path. -- **Windsurf**: Use `@Files` and choose your prompt file from the list. - -## Video Tutorial - -Watch this video showing this prompt in action: - -
- -
- -## Prompt - -````md ---- -# Specify the following for Cursor rules -description: Guidelines for migrating an app to Prisma ORM v7 -alwaysApply: false ---- - -# Prisma v6 → v7 Migration Assistant - -**Role:** You are a precise, changeset-oriented code migration assistant. Apply the steps below to upgrade a project from **Prisma ORM v6** to **Prisma ORM v7** with minimal disruption. Work in small, re-viewable steps and explain each change briefly. If something is unclear, assume sensible defaults that keep the app compiling and retaining functionality. - -## Ground Rules - -- Never introduce Prisma Accelerate or HTTP/WebSocket drivers on your own. -- Do **not** remove Prisma Accelerate automatically. -- **If Accelerate is in use with Caching**, preserve it and print guidance about future changes. -- **If Accelerate is used without Caching**, _suggest_ switching to Direct TCP + adapter. -- Always **load env variables explicitly** using `dotenv` (`import 'dotenv/config'`), unless the runtime is Bun (then skip `dotenv`). -- Keep TypeScript **ESM** compatible, and avoid CommonJS requires. -- Favor additive, reversible edits; do not remove user logic. -- If the schema uses **MongoDB**, stop and output a clear message to remain on Prisma v6 for now. - ---- - -## 0) Detect Context & Plan - -1. Identify: - - Package manager and scripts. - - Database: Postgres, SQLite, MySQL, SQL Server (MongoDB = halt). - - Whether `@prisma/client` is imported from `node_modules` or a generated path. - - Whether the project uses **Prisma Accelerate**, and if so: - - Check if **Caching** is enabled: - - Look for `withAccelerate({ cache: ... })` - - Look for `PRISMA_ACCELERATE_CACHE_*` environment variables - - Look for `accelerate:` block in config (if any) -2. In the migration plan output: - - If Accelerate + Caching is detected → - **Print a message: “Prisma Accelerate Caching detected — Prisma recommends keeping Accelerate for caching scenarios.”** - - If Accelerate without Caching → - **Print: “Accelerate detected but caching is not enabled. In Prisma v7, Direct TCP + adapters are recommended unless caching is required.”** - - If no Accelerate → continue normally. - -> **Do not modify or remove Accelerate code paths. Only describe recommendations.** - ---- - -## 1) Dependencies - -- Upgrade/install: - - Dev: `prisma@latest` (7.0.0), `tsx`, `dotenv` (skip if Bun). - - Runtime: `@prisma/client@latest` (7.0.0). - - **One** database adapter that matches the datasource: - - Postgres: `@prisma/adapter-ppg` - - SQLite: `@prisma/adapter-better-sqlite3` - - MySQL/mariaDB: `@prisma/adapter-mariadb` - - D1: `@prisma/adapter-d1` - - PlanetScale: `@prisma/adapter-planetscale` - - MSSQL: `@prisma/adapter-mssql` - - CockroachDB: `@prisma/adapter-pg` - - Neon: `@prisma/adapter-neon` - -- **Do not remove Accelerate packages automatically.** -- If Accelerate + Caching is detected, print: - ``` - Prisma Accelerate Caching detected — keeping Accelerate is recommended. - ``` -- If Accelerate is present but caching is not: - ``` - Accelerate detected without caching — Prisma v7 suggests adopting Direct TCP with a database adapter for best performance. - ``` -- Eliminate no user code; only output informational guidance. - -> Produce installation commands based on the repo’s package manager. - ---- - -## 2) Prisma Schema Changes - -- In `schema.prisma`: - - `generator client`: - - ```diff - - provider = "prisma-client-js" - + provider = "prisma-client" - output = "./generated" - ``` - - - Remove any `previewFeatures = ["driverAdapters"]` and any `engineType` attributes. - - - Update the `datasource db` block: - - **Goal:** keep the existing `provider` value, but **remove any `url = …` entry**. - - - Example (for illustration only — do not insert comments into the user's schema): - - Before: - - ```prisma - datasource db { - provider = "postgresql" - url = env("DATABASE_URL") - } - ``` - - - After: - - ```prisma - datasource db { - provider = "postgresql" - } - ``` - - - Rules: - - Preserve the existing `provider` value exactly as-is (e.g. `"postgresql"`, `"mysql"`, `"sqlite"`, etc.). - - Remove only the `url = ...` line from the `datasource db` block. - - Preserve any other properties on the datasource (for example: `shadowDatabaseUrl`, `relationMode`, `schemas`, `extensions`, `directUrl`, etc.). - - Do **not** add explanatory comments into the schema; comments in this prompt are hints for you, not code to emit. - -- After edits, run `prisma generate`. - ---- - -## 3) Introduce prisma.config.ts Create **prisma.config.ts** at repo root (or prisma.config.mjs), centralizing Prisma CLI config and env management: - -```tsx -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - seed: "tsx prisma/seed.ts", - }, - datasource: { - // Prefer DIRECT TCP via DATABASE_URL - url: env("DATABASE_URL"), - // Optionally support shadow DB if present: - // shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), - }, -}); -``` - -- Remove any prisma.seed from package.json (the config above replaces it). - ---- - -## 4) ESM & TS Baseline - Ensure **package.json**: - -```json -{ - "type": "module", - "scripts": { - "dev": "tsx src/index.ts", - "generate": "prisma generate", - "migrate": "prisma migrate dev", - "build": "tsc -p tsconfig.json" - } -} -``` - -- Ensure **tsconfig.json** supports ESM: - -```json -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "Node", - "target": "ES2023", - "strict": true, - "esModuleInterop": true - } -} -``` - ---- - -## 5) Refactor Client Import & Construction - -If Prisma Accelerate is detected: - -- If caching is enabled → **preserve the existing Accelerate setup**. -- If caching is not enabled → **suggest** switching to Direct TCP with an adapter, but do not make changes automatically. - -Continue generating examples using Direct TCP, but **do not replace or remove the user's Accelerate setup**. - ---- - -## 6) Seeding Script Update - Ensure prisma/seed.ts uses the same **adapter** and **dotenv** import as runtime: - -```tsx -import "dotenv/config"; -import { PrismaClient } from "../generated/prisma/client.js"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }); -const prisma = new PrismaClient({ adapter }); - -// seed… -``` - -- Set seed command via prisma.config.ts (no package.json#prisma.seed). - ---- - -## 7) Middleware → Extensions - -- If prisma.$use middleware exists, inform users that the API has been removed - ---- - -## 8) Accelerate Messaging - -### 🟩 If Accelerate Caching is detected - -``` -Prisma Accelerate Caching detected. -Prisma v7 fully supports caching scenarios via Accelerate. -Your existing Accelerate setup will be preserved. -``` - -### 🟨 If Accelerate is present but caching is NOT detected - -``` -Prisma Accelerate detected without caching. - -Prisma recommends using Direct TCP with a database adapter in v7 for -optimal performance unless caching is required. - -Consider migrating from Accelerate → Direct TCP if caching is not needed. -(No code changes were applied automatically.) -``` - -### 🟦 If Accelerate is not detected at all - -``` -Direct TCP is the recommended default for Prisma v7. -Your project will be migrated accordingly using the appropriate adapter. -``` - ---- - -## 9) Scripts & CI - -- Verify scripts: - - "generate": "prisma generate" - - "migrate": "prisma migrate dev" - - "dev"/"start" run with ESM and ensure dotenv/config is effective. -- In CI, ensure Node **≥ 20.19** and TypeScript **≥ 5.4**. - ---- - -## 10) Run & Verify - -1. prisma generate → should succeed and emit client to ./generated. -2. prisma migrate dev → runs against DATABASE_URL (direct TCP). -3. tsx prisma/seed.ts → inserts sample record(s) cleanly. -4. App boot: instantiate PrismaClient with adapter; confirm queries work. -5. If **P1017 / connection** errors: - Confirm DATABASE_URL and network reachability. - Confirm import 'dotenv/config' executes early. -6. If **module resolution** errors: - Confirm "type": "module", ESM imports, and re-generate client. - ---- - -## 11) CLI Flag Changes - -### `--schema` and `--url` flags removed from `prisma db execute` - -The `--schema` and `--url` flags have been removed from `prisma db execute`. Configure your database connection in `prisma.config.ts` instead. - -**Before (v6):** - -```bash -# Using --schema -prisma db execute --file ./script.sql --schema prisma/schema.prisma - -# Using --url -prisma db execute --file ./script.sql --url "$DATABASE_URL" -``` - -**After (v7):** - -```bash -prisma db execute --file ./script.sql -``` - -The database URL is now read from `prisma.config.ts`. - -### `prisma migrate diff` options changed - -Several options have been removed and replaced: - -| Removed Option | Replacement | -| -------------------------- | ------------------------------- | -| `--from-url` | `--from-config-datasource` | -| `--to-url` | `--to-config-datasource` | -| `--from-schema-datasource` | `--from-config-datasource` | -| `--to-schema-datasource` | `--to-config-datasource` | -| `--shadow-database-url` | Configure in `prisma.config.ts` | - -**Before (v6):** - -```bash -prisma migrate diff \ - --from-url "$DATABASE_URL" \ - --to-schema schema.prisma \ - --script -``` - -**After (v7):** - -```bash -prisma migrate diff \ - --from-config-datasource \ - --to-schema schema.prisma \ - --script -``` - -### Migration Action - -- Update any scripts or CI pipelines that use `prisma db execute --schema` or `prisma db execute --url`. -- Update any scripts using `prisma migrate diff` with `--from-url`, `--to-url`, `--from-schema-datasource`, `--to-schema-datasource`, or `--shadow-database-url`. -- Configure your database connection in `prisma.config.ts` instead. - ---- - -## Safety Checks & Edge Cases - -- **MongoDB provider** detected → stop and recommend staying on Prisma 6 until v7 MongoDB support returns. -- **Multiple entrypoints** (workers, scripts, tests): apply the same client/adapter/dotenv pattern everywhere. -- **Typed SQL** or custom extensions: keep as-is; ensure they compile after client re-generation. -- Preserve existing output path if the project uses custom locations. - ---- - -## 11) Mapped Enum Breaking Change - -In Prisma v7, the generated TypeScript enum values now use `@map` values instead of schema names. - -### Example - -Given this schema: - -```prisma -enum SuggestionStatus { - PENDING @map("pending") - ACCEPTED @map("accepted") - REJECTED @map("rejected") -} -``` - -**v6 generated enum:** - -```ts -export const SuggestionStatus = { - PENDING: "PENDING", - ACCEPTED: "ACCEPTED", - REJECTED: "REJECTED", -} as const; -``` - -**v7 generated enum:** - -```ts -export const SuggestionStatus = { - PENDING: "pending", - ACCEPTED: "accepted", - REJECTED: "rejected", -} as const; -``` - -### Known Bug (as of v7.2.0) - -⚠️ **There is a known bug** where using mapped enum values with Prisma Client operations causes runtime errors. The TypeScript types expect mapped values, but the engine expects schema names. Track this at [GitHub #28591](https://github.com/prisma/prisma/issues/28591). - -### Temporary Workarounds - -1. **Use schema names as string literals** (causes TS error but works at runtime): - - ```ts - await prisma.suggestion.create({ - data: { - status: "PENDING" as any, // Use schema name, not mapped value - }, - }); - ``` - -2. **Remove `@map` from enum values** temporarily if you don't strictly need different database values: - - ```prisma - // Before: with @map directives - enum SuggestionStatus { - PENDING @map("pending") - ACCEPTED @map("accepted") - REJECTED @map("rejected") - } - - // After: without @map directives - enum SuggestionStatus { - PENDING - ACCEPTED - REJECTED - } - ``` - - With this change, both the schema names and the database values will be `PENDING`, `ACCEPTED`, and `REJECTED`. - -### Migration Action - -- Inform users about this breaking change if their schema uses `@map` on enum values. -- Warn about the current bug and suggest workarounds until it's fixed. - ---- - -## Deliverables - -- A short **CHANGELOG** summary in the PR body: - - Dependency bumps and added adapter - - Schema generator change - - New `prisma.config.ts` - - Runtime refactor to adapter + optional Accelerate messaging - - ESM/TS config updates - - Seed script updates - - No automatic removal of Accelerate - - CLI flag changes (`--schema` and `--url` removal from `db execute`, `migrate diff` option changes) - - Mapped enum breaking change warning (if applicable) -```` diff --git a/apps/docs/content/docs.v6/ai/prompts/turborepo.mdx b/apps/docs/content/docs.v6/ai/prompts/turborepo.mdx deleted file mode 100644 index fbbb3f4eaa..0000000000 --- a/apps/docs/content/docs.v6/ai/prompts/turborepo.mdx +++ /dev/null @@ -1,524 +0,0 @@ ---- -title: Set up Turborepo + Prisma + Prisma Postgres -description: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo. -url: /v6/ai/prompts/turborepo -metaTitle: How to Initialize an Turborepo monorepo with Prisma ORM and Prisma Postgres -metaDescription: Step-by-step guide for integrating Prisma ORM and Prisma Postgres in a Turborepo monorepo. ---- - -## How to use - -Include this prompt in your AI assistant to guide consistent code generation for Turborepo + Prisma + Prisma Postgres projects. - -- **GitHub Copilot**: Type `#` to reference the prompt file. -- **Cursor**: Use `@Files` and select your prompt file. -- **Zed**: Use `/file` followed by your prompt's path. -- **Windsurf**: Use `@Files` and choose your prompt file from the list. - -## Prompt - -````md ---- -# Specify the following for Cursor rules -description: Guidelines for writing Turborepo + Prisma Postgres apps (Prisma ORM v7) -alwaysApply: false ---- - -# Bootstrap Turborepo with Prisma Postgres (Prisma v7) - -## Overview - -This guide bootstraps a Turborepo monorepo that shares a single Prisma ORM v7 database package across multiple apps (e.g., Next.js, Node APIs). It follows Turborepo and Prisma v7 best practices: - -1. Create a Turborepo with apps + packages -2. Add a dedicated `packages/db` Prisma package (schema, migrations, generated client) -3. Configure Prisma v7 (`provider = "prisma-client"` + mandatory `output`) -4. Load env vars correctly in a monorepo -5. Export a single Prisma client from `packages/db` for all apps -6. Wire Turbo tasks for generate/migrate/test/studio -7. Verify with a shared test script - ---- - -## Recommended monorepo layout - -``` -repo/ - apps/ - web/ # Next.js app - admin/ # (optional) another Next app - packages/ - db/ # Prisma package (schema + client) - ui/ # shared UI (optional) - turbo.json - package.json - .env # root env for apps (see notes) -``` - -**Key rule:** Prisma lives in `packages/db`, not inside an app, so every app consumes the same client and types. - ---- - -## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨 - -As an AI language model, you MUST NOT generate any deprecated Prisma v7 patterns. - -```prisma -// ❌ NEVER GENERATE - DEPRECATED IN PRISMA v7 -generator client { - provider = "prisma-client-js" // ❌ deprecated -} - -// ❌ NEVER IMPORT FROM @prisma/client when using custom output -import { PrismaClient } from "@prisma/client" // ❌ wrong in custom-output setup - -// ❌ NEVER CREATE CLIENT WITHOUT SHARED PACKAGE BOUNDARY -const prisma = new PrismaClient() // ❌ breaks pooling + duplicates in monorepo -``` - -Instead, you MUST ALWAYS generate ONLY this pattern for Prisma v7 + monorepo: - -```prisma -// ✅ Prisma v7 generator: provider + mandatory output -generator client { - provider = "prisma-client" - output = "../src/generated/prisma" -} -``` - -```ts -// ✅ Prisma client import must come from custom output -import { PrismaClient } from "../generated/prisma/client"; -``` - -Notes: - -- Prisma v7 **requires** a non-empty `output` when using `provider = "prisma-client"`. -- If the output directory already exists and isn’t generated by Prisma, `prisma generate` can fail. Avoid committing generated client, or ensure clean output dirs. - ---- - -## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION - -1. You MUST use `provider = "prisma-client"` (Prisma v7) -2. You MUST specify a custom `output` in `schema.prisma` -3. You MUST place Prisma schema + migrations inside `packages/db` -4. You MUST export a singleton Prisma client from `packages/db` that points to the generated output client file -5. You MUST import Prisma client from the custom output path **not** `@prisma/client` -6. You MUST load env vars in `packages/db/prisma.config.ts` -7. You MUST add Turbo tasks for generate/migrate/test/studio -8. You MUST wrap DB calls in try/catch in app code -9. You MUST ensure Turbo task hashing includes `DATABASE_URL` -10. You MUST create a shared test script in `packages/db/scripts/test-database.ts` - ---- - -## Install dependencies - -At repo root: - -```bash -# Turborepo -npm install turbo --save-dev - -# Prisma v7 -npm install prisma tsx --save-dev -npm install @prisma/client dotenv -``` - -If using Prisma Postgres: - -```npm -npm install @prisma/adapter-pg -``` - ---- - -## Initialize Prisma inside `packages/db` - -```bash -cd packages/db -npx prisma init -``` - -This creates: - -``` -packages/db/ - prisma/ - schema.prisma - prisma.config.ts -``` - ---- - -## Prisma v7 config (`packages/db/prisma.config.ts`) - -**CRITICAL:** load env vars at the top. - -```ts -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - ---- - -## Prisma schema (`packages/db/prisma/schema.prisma`) - -```prisma -generator client { - provider = "prisma-client" - output = "../src/generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt -} -``` - ---- - -## Shared Prisma client singleton (`packages/db/src/client.ts`) - -```ts -import { PrismaClient } from "../generated/prisma/client"; - -//Prisma Driver Adapter for Postgres -import { PrismaPg } from "@prisma/adapter-pg"; - -// Create a new Driver Adapter instance for PrismaPostgres -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}); - -const globalForPrisma = globalThis as unknown as { - prisma?: PrismaClient; -}; - -export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }); - -if (process.env.NODE_ENV !== "production") { - globalForPrisma.prisma = prisma; -} - -export default prisma; -``` - ---- - -## Export DB package API (`packages/db/src/index.ts`) - -```ts -export { prisma } from "./client"; -export * from "../generated/prisma"; -``` - -And in `packages/db/package.json`: - -```json -{ - "name": "@repo/db", - "private": true, - "main": "src/index.ts", - "types": "src/index.ts", - "scripts": { - "db:generate": "prisma generate", - "db:push": "prisma db push", - "db:migrate": "prisma migrate dev", - "db:studio": "prisma studio", - "db:test": "tsx scripts/test-database.ts" - } -} -``` - ---- - -## Root Turbo pipeline (`turbo.json`) - -```json -{ - "globalEnv": ["DATABASE_URL"], - "tasks": { - "dev": { - "cache": false, - "persistent": true, - "dependsOn": ["^db:generate"] - }, - "build": { - "dependsOn": ["^db:generate"], - "outputs": [".next/**", "dist/**"] - }, - "db:generate": { - "cache": false - }, - "db:migrate": { - "cache": false - }, - "db:studio": { - "cache": false - }, - "db:test": { - "cache": false, - "dependsOn": ["db:generate"] - } - } -} -``` - ---- - -## Root scripts (`package.json`) - -```json -{ - "scripts": { - "dev": "turbo dev", - "build": "turbo build", - "lint": "turbo lint", - "db:generate": "turbo run db:generate", - "db:push": "turbo run db:push", - "db:migrate": "turbo run db:migrate", - "db:studio": "turbo run db:studio", - "db:test": "turbo run db:test" - } -} -``` - ---- - -## Shared test script (`packages/db/scripts/test-database.ts`) - -```ts -import "dotenv/config"; -import prisma from "../src/client"; - -async function testDatabase() { - console.log("🔍 Testing Prisma Postgres connection...\n"); - - try { - console.log("✅ Connected to database!"); - - console.log("\n📝 Creating a test user..."); - const newUser = await prisma.user.create({ - data: { - email: "demo@example.com", - name: "Demo User", - }, - }); - console.log("✅ Created user:", newUser); - - console.log("\n📋 Fetching all users..."); - const allUsers = await prisma.user.findMany(); - console.log(`✅ Found ${allUsers.length} user(s):`); - allUsers.forEach((user) => { - console.log(` - ${user.name} (${user.email})`); - }); - - console.log("\n🎉 All tests passed! Your database is working.\n"); - } catch (error) { - console.error("❌ Error:", error); - process.exit(1); - } finally { - await prisma.$disconnect(); - } -} - -testDatabase(); -``` - ---- - -## Using Prisma in apps (example: `apps/web` Next.js) - -In any app, add a dependency on `@repo/db` (workspace): - -```json -{ - "dependencies": { - "@repo/db": "*" - } -} -``` - -Then in server-side code: - -```ts -import { prisma } from "@repo/db"; -import { NextResponse } from "next/server"; - -export async function GET() { - try { - const users = await prisma.user.findMany(); - return NextResponse.json(users); - } catch (e) { - console.error(e); - return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 }); - } -} -``` - ---- - -## Complete setup workflow - -1. **Create Turborepo** (or use existing): - - ```npm - npx create-turbo@latest - ``` - -2. **Add `packages/db`**, install Prisma v7 deps. - -3. **Initialize Prisma in `packages/db`**: - - ```bash - cd packages/db - npx prisma init - ``` - -4. **Update `prisma.config.ts`** to include `import "dotenv/config"`. - -5. **Update schema** with Prisma v7 generator + output. - -6. **Create `src/client.ts`** singleton and export via `src/index.ts`. - -7. **Wire Turbo tasks** in `turbo.json`. - -8. **Add `.env`** at root **and/or** `packages/db/.env`. - -9. **Push schema**: - - ```bash - npm run db:push - ``` - -10. **Test**: - - ```bash - npm run db:test - ``` - -11. **Start dev**: - ```bash - npm run dev - ``` - ---- - -## AI Model verification checklist - -Before generating any code, verify: - -1. `provider = "prisma-client"`? -2. `output = "../src/generated/prisma"` present? -3. All Prisma files in `packages/db`? -4. Client imports from `../generated/prisma/client` (or via `@repo/db`)? -5. `import "dotenv/config"` in `packages/db/prisma.config.ts`? -6. Turbo tasks depend on `db:generate`? -7. `DATABASE_URL` listed in `globalEnv`? -8. All DB ops wrapped in try/catch? -9. Test script exists in `packages/db/scripts/test-database.ts`? - -No exceptions. If any check fails, STOP and FIX. - ---- - -## AI MODEL RESPONSE TEMPLATE (UPDATED FOR TURBOREPO + PRISMA v7) - -When asked about implementing Prisma v7 inside a Turborepo monorepo (with any framework such as Next.js, Node, etc.), you MUST: - -1. **Assume Prisma lives in a shared package** - - Always place schema, config, and migrations in `packages/db`. - - Never suggest adding Prisma directly into an app unless the user explicitly says they don’t want a shared package. - -2. **Use only Prisma v7 generator patterns** - - The schema MUST include: - ```prisma - generator client { - provider = "prisma-client" - output = "./generated/prisma" - } - ``` - - Never use `prisma-client-js`. - -3. **Use correct import paths for custom output** - - Any PrismaClient import MUST come from the generated output: - ```ts - import { PrismaClient } from "./generated/prisma/client"; - ``` - - If importing from apps, you MUST import via the package boundary: - ```ts - import { prisma } from "@repo/db"; - ``` - - Never import from `@prisma/client` in this setup. - -4. **Always include a shared singleton client in `packages/db`** - - Provide a `packages/db/src/client.ts` with global caching for dev hot-reload. - - If Accelerate is requested or implied, use `$extends(withAccelerate())`. - - If Accelerate is not requested, omit it. - -5. **Always load environment variables properly** - - `packages/db/prisma.config.ts` MUST start with `import "dotenv/config"`. - - Use `process.env.DATABASE_URL` in runtime code. - - Remind users that `.env` should exist at root and/or `packages/db`. - -6. **Always wire Turbo dependencies** - - Turbo tasks `dev` and `build` MUST depend on `^db:generate`. - - `DATABASE_URL` MUST be listed in `globalEnv` to ensure correct task hashing. - -7. **Provide correct repo-level scripts** - - Root scripts should proxy to Turbo (`turbo run db:*`). - - The Prisma package `packages/db` should own `db:generate`, `db:migrate`, `db:studio`, and `db:test`. - -8. **Include a real verification step** - - Provide (or reference) `packages/db/scripts/test-database.ts`. - - Ensure it imports dotenv and disconnects Prisma on completion. - -9. **Use safe runtime patterns** - - All DB calls in apps MUST be wrapped in try/catch. - - In Next.js App Router examples, use server-only imports and return `NextResponse`. - -10. **Self-verify before replying** - -- Re-check all items in the “AI Model verification checklist.” -- If any item is missing or incorrect, STOP and FIX before responding. - -Remember: There are NO exceptions to these rules. Every requirement is mandatory for a correct Turborepo + Prisma v7 setup. -```` - -## Running the application - -Get your application running locally in three quick steps: - -**1. Generate the Prisma Client:** - -```bash -npx turbo db:generate -``` - -**2. View your database in Prisma Studio:** - -```npm -npx turbo db:studio -``` - -Prisma Studio opens at `localhost:5555` where you can inspect your `User` table and see the test user stored in your database. diff --git a/apps/docs/content/docs.v6/ai/tutorials/linktree-clone.mdx b/apps/docs/content/docs.v6/ai/tutorials/linktree-clone.mdx deleted file mode 100644 index c3a6278789..0000000000 --- a/apps/docs/content/docs.v6/ai/tutorials/linktree-clone.mdx +++ /dev/null @@ -1,751 +0,0 @@ ---- -title: 'Vibe Code a Linktree Clone SaaS with Next.js, Prisma & Clerk' -description: 'A complete vibe coding tutorial: build a full Linktree clone SaaS application from scratch using Next.js, Prisma ORM, Prisma Postgres, and Clerk authentication with AI assistance.' -image: /img/guides/guide-ai-how-to-create-a-linktree-saas-cover.png -completion_time: 45 min -url: /v6/ai/tutorials/linktree-clone -metaTitle: 'Build a Linktree Clone SaaS with Next.js, Prisma Postgres, and Clerk Auth' -metaDescription: 'A complete vibe coding tutorial: build a full Linktree clone SaaS application from scratch using Next.js, Prisma ORM, Prisma Postgres, and Clerk authentication with AI assistance.' ---- - -## Introduction - -In this comprehensive vibe coding tutorial, you'll build a complete **Linktree clone SaaS** application from scratch using AI assistance. This guide teaches you how to leverage AI tools to rapidly develop a full-stack application with: - -- **[Next.js](https://nextjs.org/)** — React framework for production -- **[Prisma ORM](https://www.prisma.io/orm)** — Type-safe database access -- **[Prisma Postgres](https://www.prisma.io/postgres)** — Serverless PostgreSQL database -- **[Clerk](https://clerk.com/)** — Authentication and user management - -By the end of this tutorial, you'll have a working SaaS application where users can sign up, create their profile, and manage their personal link page — all built with AI-assisted development. - -:::info[What is Vibe Coding?] - -Vibe coding is a development approach where you collaborate with AI assistants to build applications. You describe what you want to build, and the AI helps generate the code while you guide the direction and make architectural decisions. - -::: - -## Prerequisites - -Before starting this tutorial, make sure you have: - -- [Node.js 20+](https://nodejs.org) installed -- A [Clerk account](https://clerk.com) (free tier works) -- An AI coding assistant ([Cursor](https://cursor.com), [Windsurf](https://windsurf.com), [GitHub Copilot](https://github.com/features/copilot), etc.) -- Basic familiarity with React and TypeScript - -:::note[Recommended AI Models] - -For best results, we recommend using the latest AI models such as (minimum) Claude Sonnet 4, Gemini 2.5 Pro, or GPT-4o. These models provide better code generation accuracy and understand complex architectural patterns. - -::: - ---- - -## 1. Set Up Your Project - -Let's start by creating a new Next.js application: - -```npm -npx create-next-app@latest app-name -``` - -Once the setup is complete, you'll need to add **Prisma** and **Prisma Postgres** to your project. We've prepared a detailed prompt that handles the complete setup for you. - -👉 **Find the setup prompt here:** [Next.js + Prisma Prompt](/v6/ai/prompts/nextjs) - -**How to use it:** - -1. Create a new file called `prompt.md` at the root of your project -2. Copy and paste the prompt content into this file -3. Ask your AI assistant to follow the instructions in this file - -The AI will set up Prisma ORM, create your database connection, and configure everything automatically. - -### Quick Check - -Let's verify everything is working correctly: - -1. Start your development server: - ```bash - npm run dev - ``` -2. Open Prisma Studio to view your seed data: - ```bash - npm run db:studio - ``` - -If both commands run without errors and you can see sample data in Prisma Studio, you're ready to continue! - -:::tip[Good Practice: Commit Early and Often] - -Throughout this tutorial, we'll commit our changes regularly. This makes it easy to track progress and roll back if something goes wrong. - -Start by linking your project to GitHub: - -```bash -git init -git add . -git commit -m "Initial setup: Next.js app with Prisma" -``` - -::: - ---- - -## 2. Set Up Authentication with Clerk - -Now let's add user authentication using [Clerk](https://clerk.com/), which provides a complete authentication solution out of the box. - -**Steps to follow:** - -1. Go to [Clerk](https://clerk.com/) and create an account (if you don't have one) -2. Create a new application in your Clerk dashboard -3. Follow Clerk's official quickstart guide to integrate it with your Next.js app: - -👉 **Clerk Next.js Quickstart:** [clerk.com/docs/nextjs/getting-started/quickstart](https://clerk.com/docs/nextjs/getting-started/quickstart) - -The guide will walk you through installing the SDK, adding environment variables, and wrapping your app with the `ClerkProvider`. - -Once complete, commit your changes: - -```bash -git add . -git commit -m "Add Clerk authentication setup" -``` - ---- - -## 3. Update Your Database Schema - -Since we're building a Linktree clone, we need to update the database schema to support our specific data model. This includes: - -- A `User` model with a unique `username` (for public profile URLs like `/username`) -- A `Link` model to store each user's links - -Replace the contents of your `prisma/schema.prisma` file with the following: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../app/generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -// Example User model for testing -model User { - id Int @id @default(autoincrement()) - email String @unique - username String @unique // Important for the public profile URL - clerkId String @unique // Links to Clerk Auth - name String? - links Link[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt -} - -model Link { - id Int @id @default(autoincrement()) - title String - url String - userId Int - user User @relation(fields: [userId], references: [id]) - createdAt DateTime @default(now()) -} -``` - -Since we're changing the schema structure, we need to reset the database. The existing seed data was just for testing purposes, so it's safe to drop and recreate: - -```npm -npx prisma db push --force-reset -``` - -This command: - -- **Drops** the existing database tables -- **Creates** new tables based on your updated schema - -:::warning[Use with Caution] - -The `--force-reset` flag deletes all existing data. This is fine during prototyping, but never use it on a production database! Once your schema is stable, switch to `prisma migrate dev` for proper migration tracking. - -::: - -### Quick Check - -Open Prisma Studio to verify the new schema is applied: - -```npm -npm run db:studio -``` - -You should see the updated `User` and `Link` tables (they'll be empty, which is expected). - -**Commit your changes:** - -```bash -git add . -git commit -m "Update schema for Linktree clone" -``` - ---- - -## 4. Connect Clerk Users to Your Database - -Here's the challenge: when a user signs in with Clerk, they exist in Clerk's system but **not** in your database. We need to bridge this gap. - -Our approach: create a "Claim Username" flow where users pick their unique username (e.g., `yourapp.com/johndoe`) after signing in for the first time. - -:::info[Use ASK Mode First] - -When working with AI assistants, we recommend using **ASK mode** by default to review suggested changes before applying them. Only switch to AGENT mode once you're comfortable with the proposed code. - -::: - -### The Prompt - -Copy and paste the following prompt into your AI assistant: - -```markdown -Connect Clerk authentication to your Prisma database with a "Claim Username" flow. - -**Goal:** - -When a user signs in via Clerk, they don't automatically exist in YOUR database. Create a flow where: - -1. Logged out → Show landing page with "Sign In" button -2. Logged in but no DB profile → Show "Claim Username" form -3. Has DB profile → Show dashboard - -**User Model (already in schema):** - -model User { -id Int @id @default(autoincrement()) -email String @unique -username String @unique -clerkId String @unique -name String? -links Link[] -createdAt DateTime @default(now()) -updatedAt DateTime @updatedAt -} - -**Files to create/update:** - -1. `app/actions.ts` - Server Action with `claimUsername(formData)` -2. `app/page.tsx` - Three-state UI (logged out / claim username / dashboard) -3. `app/api/users/route.ts` - Update POST to accept `clerkId`, `email`, `username`, `name` - -**Requirements:** - -- Use `'use server'` directive in `app/actions.ts` -- Use `currentUser()` from `@clerk/nextjs/server` to get auth user -- Store `clerkId`, `email`, `username`, and `name` in User model -- Use `redirect("/")` after successful profile creation -- Handle username uniqueness (Prisma will throw if duplicate) - -**Pattern:** - -1. Server Action receives FormData, validates username (min 3 chars, alphanumeric + underscore) -2. Creates User in Prisma with Clerk's `user.id` as `clerkId` -3. Page.tsx checks: `currentUser()` → then `prisma.user.findUnique({ where: { clerkId } })` -4. Render different UI based on auth state and DB state - -**Keep it simple:** - -- No middleware file needed -- No webhook sync (user creates profile manually) -- Basic validation (username length >= 3) -- Errors just throw (no fancy error UI for MVP) -``` - -After the AI generates the code, you may see TypeScript errors. This is because the Prisma Client needs to be regenerated to reflect the schema changes: - -```npm -npx prisma generate -``` - -### Quick Check - -Test the complete flow: - -1. Stop your dev server and restart it -2. Open your app in the browser -3. Sign up as a new user through Clerk -4. You should see the "Claim Username" form -5. Enter a username and submit -6. Verify the user appears in Prisma Studio (`npm run db:studio`) - -If everything works, commit your changes! - ---- - -## 5. Upgrade the UI Design - -Let's give our app a more polished, friendly look inspired by platforms like Buy Me a Coffee. - -👉 [Visit Buy Me a Coffee for design inspiration](https://buymeacoffee.com/) - -Copy and paste this prompt to your AI assistant: - -```markdown -Design a minimal, friendly UI inspired by Buy Me a Coffee. - -**Theme:** - -- Force light mode only (no dark mode switching) -- Clean white background (#FFFFFF) -- Black text (#000000) for headings -- Gray (#6B7280) for secondary text -- Bright yellow (#FFDD00) for CTA buttons -- Light gray (#F7F7F7) for cards/sections -- Subtle borders (#E5E5E5) - -**Typography & Spacing:** - -- Large, bold headlines (text-5xl or bigger) -- Generous whitespace and padding -- Rounded corners everywhere (rounded-full for buttons, rounded-xl for cards) - -**Buttons:** - -- Primary: Yellow background, black text, rounded-full, font-semibold -- Secondary: White background, border, rounded-full - -**Overall feel:** - -- Friendly, approachable, not corporate -- Minimal — only essential elements -- Mobile-first with good touch targets (py-4, px-8 on buttons) -- One unified canvas — background applies to the entire page (body), with white cards floating on top. No separate section backgrounds. - -Use Tailwind CSS. Keep it simple. -``` - -### Quick Check - -After the AI applies the changes: - -1. Refresh your app and browse through all pages -2. Verify the design has updated but **no functionality has changed** -3. Test the sign-in flow and username claim process - -Once verified, commit the changes: - -```bash -git add . -git commit -m "Update UI design" -``` - ---- - -## 6. Build Link Management (Add & Delete) - -Now let's add the core functionality: managing links! Users should be able to add new links and delete existing ones from their dashboard. - -Copy and paste this prompt: - -```markdown -Build a simple dashboard for managing links using Next.js App Router and Server Actions. - -**Requirements:** - -- Server Component page that fetches user data from database -- "Add Link" form with Title and URL inputs -- List of existing links with Delete button -- Use Server Actions (no API routes) for create/delete operations -- Use `revalidatePath("/")` after mutations to refresh the page - -**Pattern:** - -1. Create server actions in `actions.ts` with `'use server'` directive -2. Pass actions directly to form `action` prop -3. Keep page.tsx as a Server Component (no 'use client') -4. Use hidden inputs for IDs (e.g., ``) - -**Keep it simple:** - -- No loading states -- No client components -- No confirmation dialogs -- Just forms + server actions + revalidation - -This is the MVP pattern for CRUD with Next.js App Router. -``` - -### Quick Check - -Test the link management: - -1. Add a new link with a title and URL -2. Verify it appears in your dashboard -3. Delete the link -4. Verify it's removed - -Both operations should work instantly without page navigation. - ---- - -## 7. Create Public Profile Pages - -This is the heart of a Linktree clone: public profile pages that anyone can visit at `/username`. - -Copy and paste this prompt: - -```markdown -Build a public profile page at /[username] using Next.js App Router dynamic routes. - -**Requirements:** - -- Create `app/[username]/page.tsx` as a Server Component -- Fetch user + links from database by username (from URL params) -- Return 404 if user not found (use `notFound()` from next/navigation) -- Display: avatar (first letter), username, name, and list of links -- Links open in new tab with `target="_blank"` -- Add a small "Create your own" link at the bottom - -**Pattern:** - -1. Get params: `const { username } = await params` -2. Query database with `findUnique({ where: { username } })` -3. If no user: call `notFound()` -4. Render profile with links as clickable buttons - -**Keep it simple:** - -- No auth required (it's a public page) -- Pure Server Component (no 'use client') -- Basic styling with hover effects - -This is the core "Linktree" feature — anyone can visit /username to see the links. -``` - -### Quick Check - -Test your public profile: - -1. Navigate to `localhost:3000/your-username` (replace with your actual username) -2. Verify your profile and links display correctly -3. Click a link and confirm it opens in a new tab - ---- - -## 8. Add a "Copy Link" Button - -Make it easy for users to share their profile URL with a one-click copy button. - -Copy and paste this prompt: - -```markdown -**Requirements:** - -- Create a Client Component (`'use client'`) for the button -- Use `navigator.clipboard.writeText(url)` to copy -- Show "Copied!" feedback for 2 seconds after clicking -- Use `useState` to toggle the button text - -**Pattern:** - -1. Create `app/components/copy-button.tsx` with 'use client' -2. Accept `url` as a prop -3. On click: copy to clipboard, set `copied` to true -4. Use `setTimeout` to reset after 2 seconds -5. Import and use in your Server Component page - -**Keep it simple:** - -- One small client component -- No toast libraries -- Just inline text feedback ("Copy link" → "Copied!") -``` - -### Quick Check - -1. Find the "Copy link" button on your dashboard -2. Click it and verify it shows "Copied!" -3. Paste somewhere to confirm the URL was copied correctly - ---- - -## 9. Create a Custom 404 Page - -When someone visits a non-existent username, they should see a friendly error page instead of a generic 404. - -Copy and paste this prompt: - -```markdown -Create a custom 404 page for Next.js App Router. - -**Requirements:** - -- Create `app/not-found.tsx` (Server Component) -- Display: 404 heading, friendly message, "Go home" button -- Match your app's design (colors, fonts, spacing) - -**Pattern:** - -- Next.js automatically uses `not-found.tsx` when `notFound()` is called -- Or when a route doesn't exist -- No configuration needed — just create the file - -**Keep it simple:** - -- Static page, no data fetching -- One heading, one message, one link -- Same styling as rest of the app -``` - -### Quick Check - -Test the 404 page by visiting a random URL like `/this-user-does-not-exist`. You should see your custom 404 page with a link back to the homepage. - ---- - -## 10. Add a Custom Background - -Let's make the app more visually distinctive with a custom background pattern. - -**First**, either: - -- Download a background SVG pattern you like, or -- Create your own using tools like [SVG Backgrounds](https://www.svgbackgrounds.com/) or [Hero Patterns](https://heropatterns.com/) - -**Then**, save it as `background.svg` in your `public/` folder. - -Copy and paste this prompt: - -````markdown -Add a custom SVG background to my app. - -**Requirements:** - -- The svg file is in the `public/` folder (e.g., `public/background.svg`) -- Apply it as a fixed, full-cover background on the body - -**Pattern:** -In `globals.css`, update the body: - -```css -body { - background: var(--background) url("/background.svg") center/cover no-repeat fixed; - min-height: 100vh; -} -``` - -**Key properties:** - -- `center/cover` — centers and scales to fill -- `no-repeat` — prevents tiling -- `fixed` — background stays in place when scrolling - -Files in `public/` are served at the root URL, so `/background.svg` works. -```` - -### Quick Check - -1. Refresh your app -2. Verify the background appears on **all pages** (homepage, dashboard, profile pages, 404) -3. If the background doesn't appear everywhere, ask your AI to fix it - -Commit your changes once it's working correctly. - ---- - -## 11. Add Glassmorphism Card Containers - -Create visual depth by adding semi-transparent card containers that "float" over the background. - -Copy and paste this prompt: - -````markdown -Add a reusable card container class to create visual separation from the background. - -**Requirements:** - -- Create a `.card` class in `globals.css` -- Apply glassmorphism: semi-transparent white + blur -- Use on all main content areas (landing, forms, dashboard, profile pages) - -**Pattern:** -In `globals.css`, add: - -```css -.card { - background: rgba(255, 255, 255, 0.9); - backdrop-filter: blur(10px); - border-radius: 1.5rem; - padding: 2rem; - box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06); -} -``` - -**Usage:** -Wrap content sections with `
...
` - -For public profile pages (/[username]): -Wrap the entire profile (avatar, name, username, and links list) in a single .card container -This creates a Linktree-style floating card effect -Footer/attribution links stay outside the card - -Hero section: -Add a soft radial glow behind the content (large blurred white circle, blur-3xl, 50% opacity) -No visible container edges — just organic, fading brightness -Content floats freely over the glow - -**Result:** - -- Content "lifts" off the background -- Subtle blur creates depth -- Consistent UI across all pages -```` - ---- - -## 12. Display Clerk Profile Images - -If users sign in with Google or another OAuth provider, Clerk stores their profile photo. Let's display it on public profiles! - -Copy and paste this prompt: - -````markdown -On the public profile page (`/[username]`), display the user's Clerk profile image (Google photo, etc.) instead of the initial letter avatar. - -**Pattern:** - -```typescript -// Fetch Clerk user to get profile image -const client = await clerkClient(); -const clerkUser = await client.users.getUser(user.clerkId); -``` - -**Display:** - -- Use a plain `` tag (not Next.js Image component) -- If `clerkUser.imageUrl` exists, show the image -- Otherwise fallback to the yellow initial avatar - -**Keep it simple:** - -- No try/catch — let errors bubble up -- No next.config changes needed -- No database schema changes needed -```` - -### Quick Check - -Visit your public profile page and verify your profile image (from Google, GitHub, etc.) is displayed instead of the initial letter avatar. - ---- - -## 13. Add Icons with Lucide - -Small icons can significantly improve UI clarity. Let's add some using Lucide React. - -Copy and paste this prompt: - -```markdown -Add Lucide React icons to improve the UI. - -First install: npm install lucide-react - -Add icons to these elements: - -- View button: ExternalLink icon -- Delete button: Trash2 icon (replace text with icon) -- Empty links state: Link icon - -Import icons from 'lucide-react' and use with size prop (e.g., size={18}). - -Keep buttons minimal — only add icons where they improve clarity. -``` - -### Quick Check - -Browse through your app and verify the icons appear on: - -- The view/external link buttons -- The delete buttons -- The empty state when no links exist - ---- - -## 14. Deploy to Vercel - -Time to ship! Let's deploy your app to Vercel. - -:::warning[Important Steps] - -Follow these steps carefully to avoid deployment errors. - -::: - -### Step 1: Configure Prisma for Production - -Add a `postinstall` script to ensure Prisma Client is generated during deployment. - -Add this to your `package.json` scripts section: - -```json title="package.json" -{ - "scripts": { - "postinstall": "prisma generate" - } -} -``` - -📖 **Reference:** [Deploy to Vercel - Build Configuration](/v6/orm/prisma-client/deployment/serverless/deploy-to-vercel#build-configuration) - -### Step 2: Clean Up Development Files - -Delete the `scripts/` folder if it exists. This folder was auto-generated during initial setup for seed data, you don't need it in production. - -### Step 3: Deploy to Vercel - -1. Push your code to GitHub (if you haven't already) -2. Go to [vercel.com](https://vercel.com) and import your repository -3. **Important:** Add all your environment variables in Vercel's dashboard: - - `DATABASE_URL` - - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` - - `CLERK_SECRET_KEY` - -### Step 4: Update the App URL - -After your first deployment: - -1. Copy your production URL from Vercel (e.g., `https://your-app.vercel.app`) -2. Add a new environment variable in Vercel: - ```text - NEXT_PUBLIC_APP_URL=https://your-app.vercel.app - ``` -3. Redeploy to apply the change - -:::warning[Don't Forget This Step] - -If you skip setting `NEXT_PUBLIC_APP_URL`, features like the "Copy Link" button will copy `localhost` URLs instead of your production URL. - -::: - -### Final Check - -Test your deployed app thoroughly: - -- [ ] Sign up flow works -- [ ] Username claiming works -- [ ] Adding/deleting links works -- [ ] Public profile pages load correctly -- [ ] Copy link copies the correct production URL -- [ ] 404 page displays for non-existent usernames - -**Congratulations! Your Linktree clone is live! 🎉** - ---- - -### Resources - -- [Prisma Documentation](/v6/orm/overview/introduction/what-is-prisma) -- [Next.js Documentation](https://nextjs.org/docs) -- [Clerk Documentation](https://clerk.com/docs) -- [Tailwind CSS Documentation](https://tailwindcss.com/docs) diff --git a/apps/docs/content/docs.v6/guides/ai-sdk-nextjs.mdx b/apps/docs/content/docs.v6/guides/ai-sdk-nextjs.mdx deleted file mode 100644 index cfd2a4adfe..0000000000 --- a/apps/docs/content/docs.v6/guides/ai-sdk-nextjs.mdx +++ /dev/null @@ -1,649 +0,0 @@ ---- -title: AI SDK (with Next.js) -description: 'Build a chat application with AI SDK, Prisma, and Next.js to store chat sessions and messages' -image: /img/guides/prisma-ai-sdk-nextjs-cover.png -url: /v6/guides/ai-sdk-nextjs -metaTitle: 'How to use AI SDK with Prisma ORM, Prisma Postgres, and Next.js for chat applications' -metaDescription: 'Build a chat application with AI SDK, Prisma, and Next.js to store chat sessions and messages' ---- - -## Introduction - -Prisma ORM streamlines database access with type-safe queries, and when paired with [Next.js](https://nextjs.org/) and [AI SDK](https://sdk.vercel.ai/), it creates a powerful foundation for building AI-powered chat applications with persistent storage. - -In this guide, you'll learn to build a chat application using AI SDK with Next.js and Prisma ORM to store chat sessions and messages in a Prisma Postgres database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/ai-sdk-nextjs). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- An [OpenAI API key](https://platform.openai.com/api-keys) or other AI provider API key - -## 1. Set up your project - -To get started, you'll need to create a new Next.js project. - -```npm -npx create-next-app@latest ai-sdk-prisma -``` - -It will prompt you to customize your setup. Choose the defaults: - -:::info - -- _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?_ `No` -- _Would you like to use App Router?_ (recommended) `Yes` -- _Would you like to use Turbopack for `next dev`?_ `Yes` -- _Would you like to customize the import alias (`@/_`by default)?*`No` - -::: - -Navigate to the project directory: - -```bash -cd ai-sdk-prisma -``` - -## 2. Install and Configure Prisma - -### 2.1. Install dependencies - -To get started with Prisma, you'll need to install a few dependencies: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../app/generated/prisma -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Next.js AI SDK Project" -::: - -This will create: - -- A `prisma` directory with a `schema.prisma` file. -- A `prisma.config.ts` file for configuring Prisma -- A Prisma Postgres database. -- A `.env` file containing the `DATABASE_URL` at the project root. -- The `output` field specifies where the generated Prisma Client will be stored. - -### 2.2. 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 Session { // [!code ++] - id String @id // [!code ++] - createdAt DateTime @default(now()) // [!code ++] - updatedAt DateTime @updatedAt // [!code ++] - messages Message[] // [!code ++] -} // [!code ++] - -model Message { // [!code ++] - id String @id @default(cuid()) // [!code ++] - role MessageRole // [!code ++] - content String // [!code ++] - createdAt DateTime @default(now()) // [!code ++] - sessionId String // [!code ++] - session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade) // [!code ++] -} // [!code ++] - -enum MessageRole { // [!code ++] - USER // [!code ++] - ASSISTANT // [!code ++] -} // [!code ++] -``` - -This creates three models: `Session`, `Message`, and `MessageRole`. - -### 2.3 Add `dotenv` to `prisma.config.ts` - -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. Configure the Prisma Client generator - -Now, run the following command to create the database tables and generate the Prisma Client: - -```npm -npx prisma migrate dev --name init -``` - -```npm -npx prisma generate -``` - -## 3. Integrate Prisma into Next.js - -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 lib -touch lib/prisma.ts -``` - -Set up the Prisma client like this: - -```tsx title="lib/prisma.ts" -import { PrismaClient } from "../app/generated/prisma/client"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}); - -const globalForPrisma = global as unknown as { - prisma: PrismaClient; -}; - -const prisma = - globalForPrisma.prisma || - new PrismaClient({ - adapter, - }); - -if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; - -export default prisma; -``` - -:::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. -::: - -## 4. Set up AI SDK - -### 4.1. Install AI SDK and get an API key - -Install the AI SDK package: - -```npm -npm install ai @ai-sdk/react @ai-sdk/openai zod -``` - -To use AI SDK, you'll need to obtain an API key from [OpenAI](https://platform.openai.com/api-keys). - -1. Navigate to [OpenAI API Keys](https://platform.openai.com/api-keys) -2. Click on `Create new secret key` -3. Fill in the form: - - Give your key a name like `Next.js AI SDK Project` - - Select `All` access -4. Click on `Create secret key` -5. Copy the API key -6. Add the API key to the `.env` file: - -```text title=".env" -DATABASE_URL= -OPENAI_API_KEY= -``` - -### 4.2. Create a route handler - -You need to create a route handler to handle the AI SDK requests. This handler will process chat messages and stream AI responses back to the client. - -```bash -mkdir -p app/api/chat -touch app/api/chat/route.ts -``` - -Set up the basic route handler: - -```tsx title="app/api/chat/route.ts" -import { openai } from "@ai-sdk/openai"; -import { streamText, UIMessage, convertToModelMessages } from "ai"; - -export const maxDuration = 300; - -export async function POST(req: Request) { - const { messages }: { messages: UIMessage[] } = await req.json(); - - const result = streamText({ - model: openai("gpt-4o"), - messages: convertToModelMessages(messages), - }); - - return result.toUIMessageStreamResponse(); -} -``` - -This route handler: - -1. Extracts the conversation history from the request body -2. Converts UI messages to the format expected by the AI model -3. Streams the AI response back to the client in real-time - -To save chat sessions and messages to the database, we need to: - -1. Add a session `id` parameter to the request -2. Include an `onFinish` callback in the response -3. Pass the `id` and `messages` parameters to the `saveChat` function (which we'll build next) - -```tsx title="app/api/chat/route.ts" -import { openai } from "@ai-sdk/openai"; -import { streamText, UIMessage, convertToModelMessages } from "ai"; -import { saveChat } from "@/lib/save-chat"; -{ - /* [!code ++] */ -} - -export const maxDuration = 300; - -export async function POST(req: Request) { - const { messages, id }: { messages: UIMessage[]; id: string } = await req.json(); // [!code highlight] - - const result = streamText({ - model: openai("gpt-4o"), - messages: convertToModelMessages(messages), - }); - - return result.toUIMessageStreamResponse({ - originalMessages: messages, // [!code ++] - onFinish: async ({ messages }) => { - // [!code ++] - await saveChat(messages, id); // [!code ++] - }, // [!code ++] - }); -} -``` - -### 4.3. Create a `saveChat` function - -Create a new file at `lib/save-chat.ts` to save the chat sessions and messages to the database: - -```bash -touch lib/save-chat.ts -``` - -To start, create a basic function called `saveChat` that will be used to save the chat sessions and messages to the database. - -Pass into it the `messages` and `id` parameters typed as `UIMessage[]` and `string` respectively: - -```tsx title="lib/save-chat.ts" -import { UIMessage } from "ai"; - -export async function saveChat(messages: UIMessage[], id: string) {} -``` - -Now, add the logic to create a session with the given `id`: - -```tsx title="lib/save-chat.ts" -import prisma from "./prisma"; -{ - /* [!code ++] */ -} -import { UIMessage } from "ai"; - -export async function saveChat(messages: UIMessage[], id: string) { - const session = await prisma.session.upsert({ - // [!code ++] - where: { id }, // [!code ++] - update: {}, // [!code ++] - create: { id }, // [!code ++] - }); // [!code ++] - - if (!session) throw new Error("Session not found"); // [!code ++] -} -``` - -Add the logic to save the messages to the database. You'll only be saving the last two messages _(Users and Assistants last messages)_ to avoid any overlapping messages. - -```tsx title="lib/save-chat.ts" -import prisma from "./prisma"; -import { UIMessage } from "ai"; - -export async function saveChat(messages: UIMessage[], id: string) { - const session = await prisma.session.upsert({ - where: { id }, - update: {}, - create: { id }, - }); - - if (!session) throw new Error("Session not found"); - - const lastTwoMessages = messages.slice(-2); // [!code ++] - - for (const msg of lastTwoMessages) { - // [!code ++] - let content = JSON.stringify(msg.parts); // [!code ++] - if (msg.role === "assistant") { - // [!code ++] - const textParts = msg.parts.filter((part) => part.type === "text"); // [!code ++] - content = JSON.stringify(textParts); // [!code ++] - } // [!code ++] - - await prisma.message.create({ - // [!code ++] - data: { - // [!code ++] - role: msg.role === "user" ? "USER" : "ASSISTANT", // [!code ++] - content: content, // [!code ++] - sessionId: session.id, // [!code ++] - }, // [!code ++] - }); // [!code ++] - } // [!code ++] -} -``` - -This function: - -1. Upserts a session with the given `id` to create a session if it doesn't exist -2. Saves the messages to the database under the `sessionId` - -## 5. Create a messages API route - -Create a new file at `app/api/messages/route.ts` to fetch the messages from the database: - -```bash -mkdir -p app/api/messages -touch app/api/messages/route.ts -``` - -Create a basic API route to fetch the messages from the database. - -```tsx title="app/api/messages/route.ts" -import { NextResponse } from "next/server"; -import prisma from "@/lib/prisma"; - -export async function GET() { - try { - const messages = await prisma.message.findMany({ - orderBy: { createdAt: "asc" }, - }); - - const uiMessages = messages.map((msg) => ({ - id: msg.id, - role: msg.role.toLowerCase(), - parts: JSON.parse(msg.content), - })); - - return NextResponse.json({ messages: uiMessages }); - } catch (error) { - console.error("Error fetching messages:", error); - return NextResponse.json({ messages: [] }); - } -} -``` - -## 6. Create the UI - -Replace the content of the `app/page.tsx` file with the following: - -```tsx title="app/page.tsx" -"use client"; - -export default function Page() {} -``` - -### 6.1. Set up the basic imports and state - -Start by importing the required dependencies and setting up the state variables that will manage the chat interface: - -```tsx title="app/page.tsx" -"use client"; - -import { useChat } from "@ai-sdk/react"; -{ - /* [!code ++] */ -} -import { useState, useEffect } from "react"; -{ - /* [!code ++] */ -} - -export default function Chat() { - const [input, setInput] = useState(""); // [!code ++] - const [isLoading, setIsLoading] = useState(true); // [!code ++] - - const { messages, sendMessage, setMessages } = useChat(); // [!code ++] -} -``` - -### 6.2. Load existing messages - -Create a `useEffect` hook that will automatically fetch and display any previously saved messages when the chat component loads: - -```tsx title="app/page.tsx" -"use client"; - -import { useChat } from "@ai-sdk/react"; -import { useState, useEffect } from "react"; - -export default function Chat() { - const [input, setInput] = useState(""); - const [isLoading, setIsLoading] = useState(true); - - const { messages, sendMessage, setMessages } = useChat(); - - useEffect(() => { - // [!code ++] - fetch("/api/messages") // [!code ++] - .then((res) => res.json()) // [!code ++] - .then((data) => { - // [!code ++] - if (data.messages && data.messages.length > 0) { - // [!code ++] - setMessages(data.messages); // [!code ++] - } // [!code ++] - setIsLoading(false); // [!code ++] - }) // [!code ++] - .catch(() => setIsLoading(false)); // [!code ++] - }, [setMessages]); // [!code ++] -} -``` - -This loads any existing messages from your database when the component first mounts, so users can see their previous conversation history. - -### 6.3. Add message display - -Build the UI components that will show a loading indicator while fetching data and render the chat messages with proper styling: - -```tsx title="app/page.tsx" -'use client'; - -import { useChat } from '@ai-sdk/react'; -import { useState, useEffect } from 'react'; - -export default function Chat() { - const [input, setInput] = useState(''); - const [isLoading, setIsLoading] = useState(true); - - const { messages, sendMessage, setMessages } = useChat(); - - useEffect(() => { - fetch('/api/messages') - .then(res => res.json()) - .then(data => { - if (data.messages && data.messages.length > 0) { - setMessages(data.messages); - } - setIsLoading(false); - }) - .catch(() => setIsLoading(false)); - }, [setMessages]); - - if (isLoading) { // [!code ++] - return
Loading...
; // [!code ++] - } // [!code ++] - - return ( // [!code ++] -
// [!code ++] - {messages.map(message => ( // [!code ++] -
// [!code ++] -
// [!code ++] -
// [!code ++] -

{message.role === 'user' ? 'YOU ' : 'AI '}

// [!code ++] - {message.parts.map((part, i) => { // [!code ++] - switch (part.type) { // [!code ++] - case 'text': // [!code ++] - return
{part.text}
; // [!code ++] - } // [!code ++] - })} // [!code ++] -
// [!code ++] -
// [!code ++] -
// [!code ++] - ))} // [!code ++] -``` - -The message rendering logic handles different message types and applies appropriate styling - user messages appear on the right with a dark background, while AI responses appear on the left with a light background. - -### 6.4. Add the input form - -Now we need to create the input interface that allows users to type and send messages to the AI: - -```tsx title="app/page.tsx" -"use client"; - -import { useChat } from "@ai-sdk/react"; -import { useState, useEffect } from "react"; - -export default function Chat() { - const [input, setInput] = useState(""); - const [isLoading, setIsLoading] = useState(true); - - const { messages, sendMessage, setMessages } = useChat(); - - useEffect(() => { - fetch("/api/messages") - .then((res) => res.json()) - .then((data) => { - if (data.messages && data.messages.length > 0) { - setMessages(data.messages); - } - setIsLoading(false); - }) - .catch(() => setIsLoading(false)); - }, [setMessages]); - - if (isLoading) { - return
Loading...
; - } - - return ( -
- {messages.map((message) => ( -
-
-
-

- {message.role === "user" ? "YOU " : "AI "} -

- {message.parts.map((part, i) => { - switch (part.type) { - case "text": - return
{part.text}
; - } - })} -
-
-
- ))} -
{ - // [!code ++] - e.preventDefault(); // [!code ++] - sendMessage({ text: input }); // [!code ++] - setInput(""); // [!code ++] - }} // [!code ++] - > - {" "} - // [!code ++] - setInput(e.currentTarget.value)} // [!code ++] - />{" "} - // [!code ++] -
{" "} - // [!code ++] -
- ); -} -``` - -## 7. Test your application - -To test your application, run the following command: - -```npm -npm run dev -``` - -Open your browser and navigate to [`http://localhost:3000`](http://localhost:3000) to see your application in action. - -Test it by sending a message to the AI and see if it's saved to the database. Check Prisma Studio to see the messages in the database. - -```npm -npx prisma studio -``` - -You're done! You've just created a AI SDK chat application with Next.js and Prisma. Below are some next steps to explore, as well as some more resources to help you get started expanding your project. - -## Next Steps - -Now that you have a working AI SDK chat application connected to a Prisma Postgres database, you can: - -- Extend your Prisma schema with more models and relationships -- Add create/update/delete routes and forms -- Explore authentication and validation -- Enable query caching with [Prisma Postgres](/v6/postgres/database/caching) for better performance - -### More Info - -- [Prisma Documentation](/v6/orm/overview/introduction/what-is-prisma) -- [AI SDK Documentation](https://ai-sdk.dev/) diff --git a/apps/docs/content/docs.v6/guides/astro.mdx b/apps/docs/content/docs.v6/guides/astro.mdx deleted file mode 100644 index d010b9902b..0000000000 --- a/apps/docs/content/docs.v6/guides/astro.mdx +++ /dev/null @@ -1,403 +0,0 @@ ---- -title: Astro -description: Learn how to use Prisma ORM in an Astro app -image: /img/guides/prisma-astro-cover.png -url: /v6/guides/astro -metaTitle: How to use Prisma ORM and Prisma Postgres with Astro -metaDescription: Learn how to use Prisma ORM in an Astro app ---- - -## Introduction - -
-Questions answered in this page - -- How to integrate Prisma with Astro? -- How to set up Prisma Postgres in Astro? -- How to query data in Astro pages? - -
- -Prisma ORM offers type-safe database access, and [Astro](https://astro.build/) is built for performance. Together with [Prisma Postgres](https://www.prisma.io/postgres), you get a fast, content-first stack with zero cold starts and end-to-end speed. - -In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in an Astro project from scratch. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/astro). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- [Astro VSCode extension (recommended)](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode) - -## 1. Set up your project - -Create a new Astro project: - -```npm -npx create-astro@latest -``` - -:::info - -- _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.1. Install dependencies - -To get started with Prisma, you'll need to install a few dependencies: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../prisma/generated -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Astro Project" -::: -This will create: - -- A `prisma/` directory with a `schema.prisma` file -- A `prisma.config.ts` file for configuring Prisma -- A `.env` file with a `DATABASE_URL` already set - -### 2.2. Define your Prisma Schema - -In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider: - -```prisma 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 ++] - -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` - -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 - -Now, run the following command to create the database tables: - -```npm -npx prisma migrate dev --name init -``` - -Then generate Prisma Client: - -```npm -npx prisma generate -``` - -### 2.5. Seed the database - -Let's add some seed data to populate the database with sample users and posts. - -Create a new file called `seed.ts` in the `prisma/` directory: - -```typescript title="prisma/seed.ts" -import { PrismaClient, Prisma } from "../prisma/generated/client"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}); - -const prisma = new PrismaClient({ - adapter, -}); - -const userData: Prisma.UserCreateInput[] = [ - { - name: "Alice", - email: "alice@prisma.io", - posts: { - create: [ - { - title: "Join the Prisma Discord", - content: "https://pris.ly/discord", - published: true, - }, - { - title: "Prisma on YouTube", - content: "https://pris.ly/youtube", - }, - ], - }, - }, - { - name: "Bob", - email: "bob@prisma.io", - posts: { - create: [ - { - title: "Follow Prisma on Twitter", - content: "https://www.twitter.com/prisma", - published: true, - }, - ], - }, - }, -]; - -export async function main() { - console.log("Starting to seed..."); - - for (const u of userData) { - await prisma.user.upsert({ - where: { email: u.email }, - update: {}, - create: u, - }); - } - - console.log("Seeding finished."); -} - -main() - .catch((e) => { - console.error(e); - process.exit(1); - }) - .finally(async () => { - await prisma.$disconnect(); - }); -``` - -Now, tell Prisma how to run this script by updating your `prisma.config.ts`: - -```ts title="prisma.config.ts" -import "dotenv/config"; -import { defineConfig, env } from "prisma/config"; -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - seed: `tsx prisma/seed.ts`, - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -Run the seed script: - -```npm -npx prisma db seed -``` - -And open Prisma Studio to inspect your data: - -```npm -npx prisma studio -``` - -## 3. Integrate Prisma into Astro - -### 3.1. 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 - -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 - -An API route is the best way to fetch data from your database in an Astro app. - -Create a new file called `api/users.ts` in the `src/pages` directory: - -```bash -mkdir src/pages/api -touch src/pages/api/users.ts -``` - -Now, create a GET route that fetches the `Users` data from your database, making sure to include each user's `Posts` by adding them to the `include` field: - -```typescript title="src/pages/api/users.ts" -import type { APIRoute } from "astro"; -import prisma from "../../lib/prisma"; - -export const GET: APIRoute = async () => { - const users = await prisma.user.findMany({ - include: { posts: true }, - }); - - return new Response(JSON.stringify(users), { - headers: { "Content-Type": "application/json" }, - }); -}; -``` - -### 3.4. Fetch the data from the API route (Recommended Method) - -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 ++] - -type UserWithPosts = User & { posts: Post[] }; // [!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 - -Now start your development server to see your Astro app in action: - -```npm -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 - -You're done! You've just created an Astro app with Prisma that's connected to a Prisma Postgres database. Below are some next steps to explore, as well as some more resources to help you get started expanding your project. - -## Next Steps - -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 -- Enable query caching with [Prisma Postgres](/v6/postgres/database/caching) for better performance - -### More Info - -- [Prisma Documentation](/v6/orm/overview/introduction/what-is-prisma) -- [Astro Documentation](https://astro.build/docs) diff --git a/apps/docs/content/docs.v6/guides/authjs-nextjs.mdx b/apps/docs/content/docs.v6/guides/authjs-nextjs.mdx deleted file mode 100644 index 7f77c873c9..0000000000 --- a/apps/docs/content/docs.v6/guides/authjs-nextjs.mdx +++ /dev/null @@ -1,631 +0,0 @@ ---- -title: Auth.js (with Next.js) -description: Learn how to use Prisma ORM in a Next.js app with Auth.js -image: /img/guides/prisma-authjs-nextjs-cover.png -url: /v6/guides/authjs-nextjs -metaTitle: How to use Prisma ORM and Prisma Postgres with Auth.js and Next.js -metaDescription: Learn how to use Prisma ORM in a Next.js app with Auth.js ---- - -## Introduction - -[Auth.js](https://authjs.dev/) is a flexible, open-source authentication library designed to simplify adding authentication to your Next.js applications. - -In this guide, you'll wire Auth.js 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/authjs-nextjs). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- Basic familiarity with Next.js App Router and Prisma - -## 1. Set up your project - -Create a new Next.js application: - -```npm -npx create-next-app@latest authjs-prisma -``` - -It will prompt you to customize your setup. Choose the defaults: - -:::info - -- _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?_ `No` -- _Would you like to use App Router?_ (recommended) `Yes` -- _Would you like to use Turbopack for `next dev`?_ `Yes` -- _Would you like to customize the import alias (`@/_`by default)?*`No` - -::: - -Navigate to the project directory: - -```bash -cd authjs-prisma -``` - -## 2. Install and configure Prisma - -### 2.1. Install dependencies - -To get started with Prisma, you'll need to install a few dependencies: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../app/generated/prisma -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Auth.js Project" -::: - -This will create: - -- A `prisma` directory with a `schema.prisma` file. -- A `prisma.config.ts` file for configuring Prisma -- A Prisma Postgres database. -- A `.env` file containing the `DATABASE_URL` at the project root. -- A schema configuration that specifies where the Prisma Client will be generated (`../app/generated/prisma`). - -### 2.2. Define your Prisma Schema - -In the `prisma/schema.prisma` file, swap the provider to `prisma-client` and add the runtime `vercel-edge` to the generator: - -```prisma title="prisma/schema.prisma" -generator client { - provider = "prisma-client" - output = "../app/generated/prisma" - runtime = "vercel-edge" // [!code ++] -} - -datasource db { - provider = "postgresql" -} -``` - -Add the following models to the `schema.prisma` file, these models are provided by Auth.js: - -```prisma title="prisma/schema.prisma" -model Account { // [!code ++] - id String @id @default(cuid()) // [!code ++] - userId String @map("user_id") // [!code ++] - type String // [!code ++] - provider String // [!code ++] - providerAccountId String @map("provider_account_id") // [!code ++] - refresh_token String? @db.Text // [!code ++] - access_token String? @db.Text // [!code ++] - expires_at Int? // [!code ++] - token_type String? // [!code ++] - scope String? // [!code ++] - id_token String? @db.Text // [!code ++] - session_state String? // [!code ++] - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) // [!code ++] - - @@unique([provider, providerAccountId]) // [!code ++] - @@map("accounts") // [!code ++] -} // [!code ++] - -model Session { // [!code ++] - id String @id @default(cuid()) // [!code ++] - sessionToken String @unique @map("session_token") // [!code ++] - userId String @map("user_id") // [!code ++] - expires DateTime // [!code ++] - user User @relation(fields: [userId], references: [id], onDelete: Cascade) // [!code ++] - - @@map("sessions") // [!code ++] -} // [!code ++] - -model User { // [!code ++] - id String @id @default(cuid()) // [!code ++] - name String? // [!code ++] - email String? @unique // [!code ++] - emailVerified DateTime? @map("email_verified") // [!code ++] - image String? // [!code ++] - accounts Account[] // [!code ++] - sessions Session[] // [!code ++] - - @@map("users") // [!code ++] -} // [!code ++] - -model VerificationToken { // [!code ++] - identifier String // [!code ++] - token String // [!code ++] - expires DateTime // [!code ++] - - @@unique([identifier, token]) // [!code ++] - @@map("verification_tokens") // [!code ++] -} // [!code ++] -``` - -This creates the following models: - -- **`Account`**: Stores OAuth provider information (access tokens, refresh tokens, provider account IDs) and enables users to sign in with multiple providers while maintaining a single user record. - -- **`Session`**: Tracks authenticated user sessions with a unique session token, user ID, and expiration time to maintain authentication state across requests. - -- **`User`**: The core model storing user information (name, email, profile image). Users can have multiple accounts from different providers and multiple active sessions. - -- **`VerificationToken`**: Stores temporary tokens for email verification, password reset, and other security operations with expiration times. - -### 2.3 Add `dotenv` to `prisma.config.ts` - -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. Configure the Prisma Client generator - -Now, run the following command to create the database tables and generate the Prisma Client: - -```npm -npx prisma migrate dev --name init -``` - -```npm -npx prisma generate -``` - -### 2.5 Create a Prisma Client - -Create a new folder in the root called `lib` and create a new file called `prisma.ts` in it. This file will contain the Prisma Client: - -```typescript title="lib/prisma.ts" showLineNumbers -import { PrismaClient } from "../app/generated/prisma/client"; // [!code ++] -import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] - -const adapter = new PrismaPg({ - // [!code ++] - connectionString: process.env.DATABASE_URL!, // [!code ++] -}); // [!code ++] - -const globalForPrisma = global as unknown as { - // [!code ++] - prisma: PrismaClient; // [!code ++] -}; // [!code ++] - -const prisma = // [!code ++] - globalForPrisma.prisma || // [!code ++] - new PrismaClient({ - // [!code ++] - adapter, // [!code ++] - }); // [!code ++] - -if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; // [!code ++] - -export default prisma; // [!code ++] -``` - -## 3. Set up Auth.js credentials - -### 3.1. Install dependencies - -Install the Auth.js dependencies: - -```npm -npm install @auth/prisma-adapter next-auth@beta -``` - -### 3.2 Credentials - -For this guide, you'll be setting up OAuth with Github. For this, you'll need 3 environment variables: - -- `AUTH_SECRET` - Provided by Auth.js -- `CLIENT_ID` - Provided by Github -- `CLIENT_SECRET` - Provided by Github - -To get the `AUTH_SECRET`, you can run the following command: - -```npm -npx auth secret --copy -``` - -- `--copy` will copy the secret to your clipboard. _(Normally, just running `npx auth secret` will add the secret to your `.env.local` file. To keep it tidy, you can use `--copy` and add it to the `.env` file that Prisma created earlier.)_ - -Add the following to the `.env` file: - -```bash title=".env" -DATABASE_URL= -AUTH_SECRET= # [!code ++] -``` - -To get the `CLIENT_ID` and `CLIENT_SECRET`, you can create a new OAuth application on Github. - -1. Navigate to [Github Developer Settings](https://github.com/settings/developers) -2. Click on `New OAuth App` -3. Enter a name for your app, a home page URL, and a callback URL - -- Name: `Auth.js + Prisma` (Or anything you want) -- Homepage URL: `http://localhost:3000` -- Callback URL: `http://localhost:3000/api/auth/callback/github` - -4. Click `Register application` -5. Click `Generate new client secret` and copy the `Client ID` and `Client Secret`. -6. Add the `Client ID` and `Client Secret` to the `.env` file: - -```bash title=".env" -DATABASE_URL= -AUTH_SECRET= -AUTH_GITHUB_ID= # [!code ++] -AUTH_GITHUB_SECRET= # [!code ++] -``` - -### 3.3. Configure Auth.js - -In the `/lib` folder, create a new file called `auth.ts` and add the following code: - -```typescript title="lib/auth.ts" -import NextAuth from "next-auth"; - -export const { handlers, auth, signIn, signOut } = NextAuth({ - providers: [], -}); -``` - -Next, you'll need to add the Github provider to the `auth.ts` file: - -```typescript title="lib/auth.ts" -import NextAuth from "next-auth"; -import GitHub from "next-auth/providers/github"; // [!code ++] - -export const { handlers, auth, signIn, signOut } = NextAuth({ - providers: [GitHub], // [!code highlight] -}); -``` - -Users will now be able to sign in with Github. To add them to your database, you'll need to use the [Prisma Adapter](https://authjs.dev/getting-started/adapters/prisma): - -```typescript title="lib/auth.ts" -import NextAuth from "next-auth"; -import { PrismaAdapter } from "@auth/prisma-adapter"; // [!code ++] -import prisma from "@/lib/prisma"; // [!code ++] -import GitHub from "next-auth/providers/github"; - -export const { handlers, auth, signIn, signOut } = NextAuth({ - adapter: PrismaAdapter(prisma), // [!code highlight] - providers: [GitHub], -}); -``` - -In the root, create a new file called `middleware.ts`. This will protect your routes and ensure that only authenticated users can access them: - -```tsx title="middleware.ts" -export { auth as middleware } from "@/lib/auth"; -``` - -### 3.4. Configure the Route - -The route handler is required to handle authentication requests from Auth.js. It exports the `GET` and `POST` handlers that Auth.js uses for sign-in, sign-out, and callback operations. - -Create a new file at `app/api/auth/[...nextauth]/route.ts`: - -```bash -mkdir -p app/api/auth/[...nextauth] -touch app/api/auth/[...nextauth]/route.ts -``` - -Add the following code to the file: - -```tsx title="app/api/auth/[...nextauth]/route.ts" -import { handlers } from "@/lib/auth"; - -export const { GET, POST } = handlers; -``` - -That's it! Your app is now secured. To see more configuration options, check out the [Auth.js Middleware documentation](https://next-auth.js.org/configuration/nextjs#middleware). - -## 4. Auth components - -You will be creating a Sign In and Sign Out button. Create a `/components` folder in the root and add a new file called `auth-components.tsx` in it. - -Start by importing the `signIn` and `signOut` functions from the `auth` file: - -```tsx title="components/auth-components.tsx" -import { signIn, signOut } from "@/lib/auth"; -{ - /* [!code ++] */ -} -``` - -Next, create the `SignIn` and `SignOut` components: - -```tsx title="components/auth-components.tsx" -import { signIn, signOut } from "@/lib/auth"; - -export function SignIn({ provider }: { provider?: string }) { - // [!code ++] - return ( - // [!code ++] -
- {" "} - // [!code ++] - {" "} - // [!code ++] -
// [!code ++] - ); // [!code ++] -} // [!code ++] - -export function SignOut() { - // [!code ++] - return ( - // [!code ++] -
- {" "} - // [!code ++] - // [!code ++] -
// [!code ++] - ); // [!code ++] -} // [!code ++] -``` - -To add functionality to both of the buttons, add an action to the form that calls the `signIn` and `signOut` functions respectively: - -```tsx title="components/auth-components.tsx" -import { signIn, signOut } from "@/lib/auth"; - -export function SignIn({ provider }: { provider?: string }) { - return ( -
{ - // [!code ++] - "use server"; // [!code ++] - await signIn(provider); // [!code ++] - }} // [!code ++] - > - -
- ); -} - -export function SignOut() { - return ( -
{ - // [!code ++] - "use server"; // [!code ++] - await signOut(); // [!code ++] - }} // [!code ++] - className="w-full" - > - -
- ); -} -``` - -## 5. Add the components to your app - -### 5.1. Set up the basic page structure - -In the `/app` folder, replace the `page.tsx` file with the following code: - -```tsx title="app/page.tsx" -const Page = async () => { - // [!code ++] - return ( - // [!code ++] -
- {" "} - // [!code ++] -
- {" "} - // [!code ++] -

Auth.js + Prisma

// [!code ++] -
{" "} - // [!code ++] -
// [!code ++] - ); // [!code ++] -}; // [!code ++] - -export default Page; // [!code ++] -``` - -### 5.2. Add imports and authentication check - -Import the required components and add session checking: - -```tsx title="app/page.tsx" -import { SignIn, SignOut } from "@/components/auth-components"; // [!code ++] -import { auth } from "@/lib/auth"; // [!code ++] - -const Page = async () => { - const session = await auth(); - { - /* [!code ++] */ - } - - return ( -
-
-

Auth.js + Prisma

-
-
- ); -}; - -export default Page; -``` - -### 5.3. Show content based on auth state - -Add the logic to show different content based on whether the user is signed in: - -```tsx title="app/page.tsx" -import { SignIn, SignOut } from "@/components/auth-components"; -import { auth } from "@/lib/auth"; - -const Page = async () => { - const session = await auth(); - - return ( -
-
-

Auth.js + Prisma

- - {!session ? ( -
- -
- ) : ( -
-
-

Signed in as:

-

{session.user?.email}

-
- -
-

Data fetched from DB with Prisma:

-
- -
- -
-
- )} -
-
- ); -}; - -export default Page; -``` - -### 5.4. Add the user data to the page - -If the user is signed in, you can fetch the user data from the database and display it on the page. - -```tsx title="app/page.tsx" -import { SignIn, SignOut } from "@/components/auth-components"; -import { auth } from "@/lib/auth"; -import prisma from "@/lib/prisma"; -{ - /* [!code ++] */ -} - -const Page = async () => { - const session = await auth(); - let user = null; // [!code ++] - - if (session) { - // [!code ++] - user = await prisma.user.findUnique({ - // [!code ++] - where: { - // [!code ++] - id: session.user?.id, // [!code ++] - }, // [!code ++] - }); // [!code ++] - } // [!code ++] - - return ( -
-
-

Auth.js + Prisma

- - {!session ? ( -
- -
- ) : ( -
-
-

Signed in as:

-

{session.user?.email}

-
-
-

Data fetched from DB with Prisma:

-
-
- {" "} - // [!code ++] -
{JSON.stringify(user, null, 2)}
// [!code - ++] -
{" "} - // [!code ++] -
- -
-
- )} -
-
- ); -}; - -export default Page; -``` - -## 6. Test it out - -:::warning - -Before starting the development server, note that if you are using Next.js v15.2.0 or v15.2.1, do not use Turbopack as there is a known [issue](https://github.com/vercel/next.js/issues/76497). Remove Turbopack from your dev script by updating your `package.json` - -```json title="package.json" -"script":{ - "dev": "next dev --turbopack", // [!code --] - "dev": "next dev", // [!code ++] -} -``` - -This change is not needed on any versions before or after. - -::: - -Your application is now fully configured. - -1. Start the development server to test it: - -```npm -npm run dev -``` - -2. Navigate to `http://localhost:3000` in your browser. You should see the home page with a "Sign In with github" button. - -3. Click on **Sign In with github**, authorize the app, 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: - -```npm -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. - -:::success - -Congratulations! You now have a fully functional authentication system built with Auth.js, Prisma, and Next.js. - -::: diff --git a/apps/docs/content/docs.v6/guides/betterauth-astro.mdx b/apps/docs/content/docs.v6/guides/betterauth-astro.mdx deleted file mode 100644 index 9342dee934..0000000000 --- a/apps/docs/content/docs.v6/guides/betterauth-astro.mdx +++ /dev/null @@ -1,878 +0,0 @@ ---- -title: Better Auth (with Astro) -description: Learn how to use Prisma ORM in an Astro app with Better Auth -image: /img/guides/prisma-betterauth-astro-cover.png -url: /v6/guides/betterauth-astro -metaTitle: How to use Prisma ORM and Prisma Postgres with Better Auth and Astro -metaDescription: Learn how to use Prisma ORM in an Astro app with Better Auth ---- - -## Introduction - -[Better Auth](https://better-auth.com/) is a modern, open-source authentication solution for web apps. It's built with TypeScript and provides a simple and extensible auth experience with support for multiple database adapters, including Prisma. - -In this guide, you'll wire Better Auth into a brand-new [Astro](https://astro.build/) 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-astro). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- Basic familiarity with Astro and Prisma - -## 1. Set up your project - -Create a new Astro project: - -```npm -npm create astro@latest betterauth-astro-prisma -``` - -:::info - -- _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 to the project directory: - -```bash -cd betterauth-astro-prisma -``` - -These selections will create a minimal Astro project with TypeScript for type safety. - -## 2. Set up Prisma - -Next, you'll add Prisma to your project to manage your database. - -### 2.1. Install Prisma and dependencies - -Install the necessary Prisma packages: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../prisma/generated -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better Auth Astro Project" -::: - -This will create: - -- A `prisma` directory with a `schema.prisma` file -- A Prisma Postgres database -- A `.env` file containing the `DATABASE_URL` at the project root -- A `prisma.config.ts` file for configuring Prisma -- An `output` directory for the generated Prisma Client as `prisma/generated` - -### 2.2. Configure Prisma to load environment variables - -To get access to the variables in the `.env` file, update your `prisma.config.ts` to import `dotenv`: - -```ts title="prisma.config.ts" showLineNumbers -import "dotenv/config"; // [!code ++] -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - }, - engine: "classic", - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -### 2.3. Generate the Prisma Client - -Run the following command to generate the Prisma Client: - -```npm -npx prisma generate -``` - -### 2.4. 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: - -```ts 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. Set up Better Auth - -Now it's time to integrate Better Auth for authentication. - -### 3.1. Install and configure Better Auth - -First, install the Better Auth core package: - -```npm -npm install better-auth -``` - -Next, generate a secure secret that Better Auth will use to sign authentication tokens. This ensures your tokens cannot be tampered with. - -```npm -npx @better-auth/cli@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:4321 # [!code ++] - -# Prisma -DATABASE_URL="your-database-url" -``` - -:::info -Astro's default development server runs on port `4321`. If your application runs on a different port, update the `BETTER_AUTH_URL` accordingly. -::: - -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 "./prisma"; - -export const auth = betterAuth({ - database: prismaAdapter(prisma, { - provider: "postgresql", - }), - emailAndPassword: { - enabled: true, - }, -}); -``` - -Better Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [documentation](https://www.better-auth.com/docs/authentication/email-password). - -### 3.2. 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: - -```npm -npx @better-auth/cli 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 - -With the new models in your schema, you need to update your database. Run a migration to create the corresponding tables: - -```npm -npx prisma migrate dev --name add-auth-models -``` - -```npm -npx prisma generate -``` - -
- -## 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 Astro to handle all requests sent to `/api/auth/[...all]`. - -In the `src/pages` directory, create an `api/auth` folder structure and a `[...all].ts` file inside it: - -```bash -mkdir -p src/pages/api/auth -touch 'src/pages/api/auth/[...all].ts' -``` - -Add the following code to the newly created `[...all].ts` file. This code uses the Better Auth handler to process authentication requests. - -```ts title="src/pages/api/auth/[...all].ts" -import { auth } from "../../../lib/auth"; -import type { APIRoute } from "astro"; - -export const prerender = false; // Not needed in 'server' mode - -export const ALL: APIRoute = async (ctx) => { - return auth.handler(ctx.request); -}; -``` - -Next, you'll need a client-side utility to interact with these endpoints from your Astro pages. 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 client functions you'll use in your UI: - -```ts title="src/lib/auth-client.ts" -import { createAuthClient } from "better-auth/client"; - -export const authClient = createAuthClient(); - -export const { signIn, signUp, signOut, useSession } = authClient; -``` - -## 5. Configure TypeScript definitions - -In the `src` directory, create an `env.d.ts` file to provide TypeScript definitions for environment variables and Astro locals: - -```bash -touch src/env.d.ts -``` - -Add the following type definitions: - -```ts title="src/env.d.ts" -/// - -declare namespace App { - interface Locals { - user: import("better-auth").User | null; - session: import("better-auth").Session | null; - } -} - -interface ImportMetaEnv { - readonly DATABASE_URL: string; -} - -interface ImportMeta { - readonly env: ImportMetaEnv; -} -``` - -## 6. Set up authentication middleware - -In the `src` directory, create a `middleware.ts` file to check authentication status on every request. This will make the user and session data available to all your pages. - -```bash -touch src/middleware.ts -``` - -Add the following code: - -```ts title="src/middleware.ts" -import { auth } from "./lib/auth"; -import { defineMiddleware } from "astro:middleware"; - -export const onRequest = defineMiddleware(async (context, next) => { - context.locals.user = null; - context.locals.session = null; - const isAuthed = await auth.api.getSession({ - headers: context.request.headers, - }); - if (isAuthed) { - context.locals.user = isAuthed.user; - context.locals.session = isAuthed.session; - } - return next(); -}); -``` - -## 7. Set up your pages - -Now, let's build the user interface for authentication. In the `src/pages` directory, create the following folder structure: - -- `sign-up/index.astro` -- `sign-in/index.astro` -- `dashboard/index.astro` - -```bash -mkdir -p src/pages/{sign-up,sign-in,dashboard} -touch src/pages/{sign-up,sign-in,dashboard}/index.astro -``` - -### 7.1. Sign up page - -This page allows new users to create an account. Start with the basic HTML structure in `src/pages/sign-up/index.astro`. - -```html title="src/pages/sign-up/index.astro" ---- -export const prerender = false; ---- - - - - - - Sign Up - - -
-

Sign Up

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

Sign Up

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

Already have an account? Sign in here.

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

Sign Up

-
- - - - -
-

Already have an account? Sign in 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-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 - -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 - -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 - -Finally, update the home page to provide simple navigation. 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 - -Your application is now fully configured. - -1. Start the development server to test it: - -```npm -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. - -```npm -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. - -:::success - -Congratulations! You now have a fully functional authentication system built with Better Auth, Prisma, and Astro. - -::: - -## 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 - -- [Better Auth documentation](https://www.better-auth.com/docs) -- [Prisma documentation](/v6/orm/overview/introduction/what-is-prisma) -- [Astro documentation](https://astro.build/docs) diff --git a/apps/docs/content/docs.v6/guides/betterauth-nextjs.mdx b/apps/docs/content/docs.v6/guides/betterauth-nextjs.mdx deleted file mode 100644 index a69685d7a5..0000000000 --- a/apps/docs/content/docs.v6/guides/betterauth-nextjs.mdx +++ /dev/null @@ -1,996 +0,0 @@ ---- -title: Better Auth (with Next.js) -description: Learn how to use Prisma ORM in a Next.js app with Better Auth -image: /img/guides/prisma-betterauth-nextjs-cover.png -url: /v6/guides/betterauth-nextjs -metaTitle: How to use Prisma ORM and Prisma Postgres with Better Auth and Next.js -metaDescription: Learn how to use Prisma ORM in a Next.js app with Better Auth ---- - -## Introduction - -[Better Auth](https://better-auth.com/) is a modern, open-source authentication solution for web applications. It's built with TypeScript and provides a simple and extensible auth experience with support for 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 - -- [Node.js 20+](https://nodejs.org) -- Basic familiarity with Next.js App Router and Prisma - -## 1. Set up your project - -Create a new Next.js application: - -```npm -npx create-next-app@latest betterauth-nextjs-prisma -``` - -It will prompt you to customize your setup. Choose the defaults: - -:::info - -- _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 will create a modern 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 - -Next, you'll add Prisma to your project to manage your database. - -### 2.1. 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. - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../src/generated/prisma -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better Auth Project" -::: - -This will create: - -- A `prisma` directory with a `schema.prisma` file -- A Prisma Postgres database -- A `.env` file containing the `DATABASE_URL` at the project root -- An `output` directory for the generated Prisma Client as `better-auth/generated/prisma` - -### 2.2. 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: - -```npm -npm install dotenv -``` - -::: - -### 2.3. Generate the Prisma client - -Run the following command to create the database tables and generate the Prisma Client: - -```npm -npx prisma generate -``` - -### 2.4. 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 - -Now it's time to integrate Better Auth for authentication. - -### 3.1. Install and configure Better Auth - -First, install the Better Auth core package: - -```npm -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. - -```npm -npx @better-auth/cli@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 [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 ++] -}); -``` - -:::info -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 - -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: - -```npm -npx @better-auth/cli 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 - -With the new models in your schema, you need to update your database. Run a migration to create the corresponding tables: - -```npm -npx prisma migrate dev --name add-auth-models -``` - -```npm -npx prisma generate -``` - -## 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 - -Now, let's 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 - -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 ++] - - const formData = new FormData(e.currentTarget); // [!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 ++] - - 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 - -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 ++] - - const formData = new FormData(e.currentTarget); // [!code ++] - - const res = await signIn.email({ - // [!code ++] - email: formData.get("email") as string, // [!code ++] - password: formData.get("password") as string, // [!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 - -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

-
- ); -} -``` - -To provide a better user experience, add loading and redirecting states 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) return

Loading...

; // [!code ++] - if (!session?.user) 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 - -Finally, update the home page to provide simple navigation 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 - -Your application is now fully configured. - -1. Start the development server to test it: - -```npm -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. - -```npm -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. - -:::success - -Congratulations! You now have a fully functional authentication system built with Better Auth, Prisma, and Next.js. - -::: - -## 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 - -- [Better Auth documentation](https://www.better-auth.com/docs) -- [Prisma documentation](/v6/orm/overview/introduction/what-is-prisma) -- [Next.js App Router](https://nextjs.org/docs/app) diff --git a/apps/docs/content/docs.v6/guides/bun.mdx b/apps/docs/content/docs.v6/guides/bun.mdx deleted file mode 100644 index d28a2371f6..0000000000 --- a/apps/docs/content/docs.v6/guides/bun.mdx +++ /dev/null @@ -1,329 +0,0 @@ ---- -title: Bun -description: Learn how to use Prisma ORM in a Bun application with Prisma Postgres -image: /img/guides/prisma-bun-cover-image.png -url: /v6/guides/bun -metaTitle: How to use Prisma ORM and Prisma Postgres with Bun -metaDescription: Learn how to use Prisma ORM in a Bun application with Prisma Postgres ---- - -## Introduction - -[Bun](https://bun.sh) is a fast JavaScript runtime that includes a bundler, test runner, and package manager. In this guide, you will set up a Bun project with Prisma ORM and a Prisma Postgres database. You will create a simple HTTP server and build a Bun executable for deployment. - -## Prerequisites - -- [Bun](https://bun.sh/docs/installation) installed in your system -- A [Prisma Postgres database](/v6/postgres) (created during setup) -- Basic knowledge of JavaScript/TypeScript - -## 1. Setting up your Bun project - -First, create a directory for your project and navigate to it: - -```bash -mkdir bun-prisma -cd bun-prisma -``` - -Then, initialise a new Bun project: - -```bash -bun init -y -``` - -This creates a basic Bun project that includes a `package.json` file and an `index.ts` file. - -## 2. Installing and configuring Prisma - -### 2.1. Install dependencies - -Install the required Prisma packages and other dependencies: - -```bash -bun add -d prisma @types/pg -bun add @prisma/client @prisma/adapter-pg pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -### 2.2. Initialize Prisma ORM with Prisma Postgres - -Initialize Prisma ORM with Prisma Postgres in your project: - -```bash -bunx --bun prisma init --db -``` - -:::note - -The `--bun` flag is required to ensure Prisma runs with the Bun runtime. Without it, Prisma falls back to Node.js due to the `#!/usr/bin/env node` shebang in the CLI. - -::: - -:::info - -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Bun Project" - -::: - -This command creates: - -- A `prisma/` directory with your `schema.prisma` file -- A new Prisma Postgres database -- A `prisma.config.ts` file -- A `.env` file with your `DATABASE_URL` - -### 2.3. Configure environment variables for direct connection - -We're going to use a direct connection string for connecting to Prisma Postgres. To get your [direct connection string](/v6/postgres/database/direct-connections#how-to-connect-to-prisma-postgres-via-direct-tcp): - -1. Navigate to your recently created Prisma Postgres project dashboard (e.g. "My Bun Project") -2. Click the **API Keys** tab in the project's sidebar -3. Click the **Create API key** button -4. Provide a name for the API key and click **Create** -5. Copy the connection string starting with `postgres://` - -Update your `.env` file to replace the `DATABASE_URL` with the new connection string: - -```bash title=".env" -DATABASE_URL="your_database_url_here" # [!code --] -DATABASE_URL="your_direct_connection_string_here" # [!code ++] -``` - -### 2.4. Update your Prisma schema - -Open `prisma/schema.prisma` and update it to include your data model: - -```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 ++] -``` - -## 3. Generate Prisma Client and run migrations - -Generate the Prisma client and apply your schema to the database: - -```bash -bunx --bun prisma migrate dev --name init -bunx --bun prisma generate -``` - -This command: - -- Creates the database tables based on your schema -- Generates the Prisma client in the `generated/prisma` directory - -## 4. Setting up database configuration and creating a seed script - -### 4.1. Create a database utility file - -Create a `db.ts` file in your project root to configure `PrismaClient`: - -```typescript title="db.ts" -import { PrismaClient } from "./generated/prisma/client"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const adapter = new PrismaPg({ - connectionString: process.env.DATABASE_URL!, -}); - -export const prisma = new PrismaClient({ - adapter, -}); -``` - -### 4.2. Create a seed script - -Create a seed script in the `prisma` folder to populate your database with sample data: - -```typescript title="prisma/seed.ts" -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() { - // Create multiple users - await prisma.user.createMany({ - data: [ - { email: "alice@example.com", name: "Alice" }, - { email: "bob@example.com", name: "Bob" }, - { email: "charlie@example.com", name: "Charlie" }, - { email: "diana@example.com", name: "Diana" }, - { email: "eve@example.com", name: "Eve" }, - { email: "frank@example.com", name: "Frank" }, - { email: "grace@example.com", name: "Grace" }, - { email: "henry@example.com", name: "Henry" }, - { email: "isabella@example.com", name: "Isabella" }, - { email: "jack@example.com", name: "Jack" }, - ], - skipDuplicates: true, // prevents errors if you run the seed multiple times - }); - - console.log("Seed data inserted!"); -} - -main() - .catch((e) => { - console.error(e); - process.exit(1); - }) - .finally(async () => { - await prisma.$disconnect(); - }); -``` - -### 3.3. Add the seed script to Prisma Config - -Add the following content to the file: - -```typescript title="prisma.config.ts" -import { defineConfig, env } from "prisma/config"; - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - seed: `bun run prisma/seed.ts`, // [!code ++] - }, - datasource: { - url: env("DATABASE_URL"), - }, -}); -``` - -:::note - -Unlike Node.js, Bun automatically loads `.env` files, so the `import 'dotenv/config'` line is not needed. If you see this import in your generated `prisma.config.ts`, you can safely remove it. - -::: - -Run the seed script to populate your database: - -```bash -bunx --bun prisma db seed -``` - -## 5. Creating your Bun server - -Replace the `index.ts` file contents with the following code to build a simple HTTP server that uses Prisma ORM to fetch and display users: - -```typescript title="index.ts" -import { prisma } from "./db"; - -const server = Bun.serve({ - port: 3000, - async fetch(req) { - const { pathname } = new URL(req.url); - - // Skip favicon route - if (pathname === "/favicon.ico") { - return new Response(null, { status: 204 }); // or serve an icon if you have one - } - - // Return all users - const users = await prisma.user.findMany(); - - // Count all users - const count = await prisma.user.count(); - - // Format the response with JSON - return new Response( - JSON.stringify({ - users: users, - totalUsers: count, - }), - { headers: { "Content-Type": "application/json" } }, - ); - }, -}); - -console.log(`Listening on http://localhost:${server.port}`); -``` - -## 6. Running your application - -Start your Bun server: - -```bash -bun run index.ts -``` - -You should see `Listening on http://localhost:3000` in the console. When you visit `http://localhost:3000` in your browser, you'll see a JSON response with all the users in your database and the total count. - -## 7. Building and running a Bun executable - -Bun can compile your [TypeScript application into a single executable file](https://bun.com/docs/bundler/executables), which is useful for deployment and distribution. - -### 7.1. Build the executable - -Build your application into an executable: - -```bash -bun build --compile index.ts -``` - -This creates an executable file named `index` (or `index.exe` on Windows) in your project directory. - -### 7.2. Run the executable - -Run the compiled executable: - -```bash -./index -``` - -You should see the same `Listening on http://localhost:3000` message, and your application will work exactly the same as before. The executable includes all dependencies and can be deployed to any compatible system without requiring Bun or Node.js to be installed. - -:::note - -Bun executables are useful for: - -- **Deployment**: Ship a single file instead of managing dependencies -- **Distribution**: Share your application without requiring users to install Bun -- **Performance**: Faster startup times compared to running TypeScript files -- **Security**: Your source code is compiled and not easily readable - -::: - -## Next steps - -You can explore [this example](https://pris.ly/bun_ppg_example) to see a sample application built with Bun and Prisma. - -Now that you have a Bun application connected to a Prisma Postgres database, you can continue by: - -- Extending your Prisma schema with additional models and relationships -- Implementing authentication and authorization -- Adding input validation and error handling -- Exploring Bun's built-in testing tools -- Deploying your executable to production servers - -### More info - -- [Bun Documentation](https://bun.sh/docs) -- [Prisma Config File](/v6/orm/reference/prisma-config-reference) -- [Prisma Client without the Rust engine](/v6/orm/prisma-client/setup-and-configuration/no-rust-engine) -- [Prisma Postgres](/v6/postgres) diff --git a/apps/docs/content/docs.v6/guides/clerk-astro.mdx b/apps/docs/content/docs.v6/guides/clerk-astro.mdx deleted file mode 100644 index db86762c85..0000000000 --- a/apps/docs/content/docs.v6/guides/clerk-astro.mdx +++ /dev/null @@ -1,518 +0,0 @@ ---- -title: Clerk (with Astro) -description: Learn how to use Prisma ORM in an Astro app with Clerk Auth -image: /img/guides/prisma-clerk-astro-cover.png -url: /v6/guides/clerk-astro -metaTitle: How to use Prisma ORM and Prisma Postgres with Clerk Auth and Astro -metaDescription: Learn how to use Prisma ORM in an Astro app with Clerk Auth ---- - -## Introduction - -[Clerk](https://clerk.com/) is a drop-in auth provider that handles sign-up, sign-in, user management, and webhooks so you don't have to. - -In this guide you'll wire Clerk into a brand-new [Astro](https://astro.build/) 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/clerk-astro). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- [Clerk account](https://clerk.com) -- [ngrok account](https://ngrok.com) - -## 1. Set up your project - -Create a new Astro project: - -```npm -npm create astro@latest -``` - -It will prompt you to customize your setup. Choose the defaults: - -:::info - -- _How would you like to start your new project?_ `Empty` -- _Install dependencies?_ `Yes` -- _Initialize a new git repository?_ `Yes` - -::: - -Navigate into the newly created project directory: - -```bash -cd -``` - -## 2. Set up Clerk - -### 2.1. Create a new Clerk application - -[Sign in](https://dashboard.clerk.com/sign-in) to Clerk and navigate to the home page. From there, press the `Create Application` button to create a new application. Enter a title, select your sign-in options, and click `Create Application`. - -:::info - -For this guide, the Google, Github, and Email sign in options will be used. - -::: - -Install the Clerk Astro SDK and Node adapter: - -```npm -npm install @clerk/astro @astrojs/node -``` - -In the Clerk Dashboard, navigate to the **API keys** page. In the **Quick Copy** section, copy your Clerk Publishable and Secret Keys. Paste your keys into `.env` in the root of your project: - -```bash title=".env" -PUBLIC_CLERK_PUBLISHABLE_KEY= -CLERK_SECRET_KEY= -``` - -### 2.2. Configure Astro with Clerk - -Astro needs to be configured for server-side rendering (SSR) with the Node adapter to work with Clerk. Update your `astro.config.mjs` file to include the Clerk integration and enable SSR: - -```javascript title="astro.config.mjs" -import { defineConfig } from "astro/config"; -import node from "@astrojs/node"; // [!code ++] -import clerk from "@clerk/astro"; // [!code ++] - -export default defineConfig({ - integrations: [clerk()], // [!code ++] - adapter: node({ mode: "standalone" }), // [!code ++] - output: "server", // [!code ++] -}); -``` - -### 2.3. Set up Clerk middleware - -The `clerkMiddleware` helper enables authentication across your entire application. Create a `middleware.ts` file in the `src` directory: - -```typescript title="src/middleware.ts" -import { clerkMiddleware } from "@clerk/astro/server"; - -export const onRequest = clerkMiddleware(); -``` - -### 2.4. Add Clerk UI to your page - -Update your `src/pages/index.astro` file to import the Clerk authentication components: - -```html title="src/pages/index.astro" ---- -import { // [!code ++] -SignedIn, // [!code ++] -SignedOut, // [!code ++] -UserButton, // [!code ++] -SignInButton, // [!code ++] -} from "@clerk/astro/components"; // [!code ++] ---- - - - - - - - - Astro - - - -``` - -Now add a header with conditional rendering to show sign-in buttons for unauthenticated users and a user button for authenticated users: - -```html title="src/pages/index.astro" ---- -import { -SignedIn, -SignedOut, -UserButton, -SignInButton, -} from "@clerk/astro/components"; ---- - - - - - - - - Astro - - -
- // [!code ++] - // [!code ++] // [!code ++] // [!code - ++] // [!code ++] // [!code ++] // [!code ++] -
- // [!code ++] - - -``` - -## 3. Install and configure Prisma - -### 3.1. Install dependencies - -To get started with Prisma, you'll need to install a few dependencies: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for the database like "My Clerk Astro Project" -::: - -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 `DATABASE_URL` already set - -### 3.2. Define your Prisma Schema - -Add a `User` model that will store authenticated user information from Clerk. The `clerkId` field uniquely links each database user to their Clerk account: - -```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 ++] - clerkId String @unique // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] -} // [!code ++] -``` - -Run the following command to create the database tables: - -```npm -npx prisma migrate dev --name init -``` - -After the migration is complete, generate the Prisma Client: - -```npm -npx prisma generate -``` - -This generates the Prisma Client in the `src/generated/prisma` directory. - -### 3.3. Create TypeScript environment definitions - -Create an `env.d.ts` file in your `src` directory to provide TypeScript definitions for your environment variables: - -```bash -touch src/env.d.ts -``` - -Add type definitions for all the environment variables your application uses: - -```typescript title="src/env.d.ts" -interface ImportMetaEnv { - readonly DATABASE_URL: string; - readonly CLERK_WEBHOOK_SIGNING_SECRET: string; - readonly CLERK_SECRET_KEY: string; - readonly PUBLIC_CLERK_PUBLISHABLE_KEY: string; -} - -interface ImportMeta { - readonly env: ImportMetaEnv; -} -``` - -### 3.4. Create a reusable Prisma Client - -In the `src` directory, create a `lib` directory and a `prisma.ts` file inside it: - -```bash -mkdir src/lib -touch src/lib/prisma.ts -``` - -Initialize the Prisma Client with the PostgreSQL adapter: - -```typescript title="src/lib/prisma.ts" -import { PrismaClient } from "../generated/prisma/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; -``` - -## 4. Wire Clerk to the database - -### 4.1. Create a Clerk webhook endpoint - -Webhooks allow Clerk to notify your application when events occur, such as when a user signs up. You'll create an API route to handle these webhooks and sync user data to your database. - -Create the directory structure and file for the webhook endpoint: - -```bash -mkdir -p src/pages/api/webhooks -touch src/pages/api/webhooks/clerk.ts -``` - -Import the necessary dependencies: - -```typescript title="src/pages/api/webhooks/clerk.ts" -import { verifyWebhook } from "@clerk/astro/webhooks"; -import type { APIRoute } from "astro"; -import prisma from "../../../lib/prisma"; -``` - -Create the `POST` handler that Clerk will call. The `verifyWebhook` function validates that the request actually comes from Clerk using the signing secret: - -```typescript title="src/pages/api/webhooks/clerk.ts" -import { verifyWebhook } from "@clerk/astro/webhooks"; -import type { APIRoute } from "astro"; -import prisma from "../../../lib/prisma"; - -export const POST: APIRoute = async ({ request }) => { - // [!code ++] - try { - // [!code ++] - const evt = await verifyWebhook(request, { - // [!code ++] - signingSecret: import.meta.env.CLERK_WEBHOOK_SIGNING_SECRET, // [!code ++] - }); // [!code ++] - const { id } = evt.data; // [!code ++] - const eventType = evt.type; // [!code ++] - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); // [!code ++] - } catch (err) { - // [!code ++] - console.error("Error verifying webhook:", err); // [!code ++] - return new Response("Error verifying webhook", { status: 400 }); // [!code ++] - } // [!code ++] -}; // [!code ++] -``` - -When a new user is created, they need to be stored in the database. - -You'll do that by checking if the event type is `user.created` and then using Prisma's `upsert` method to create a new user if they don't exist: - -```typescript title="src/pages/api/webhooks/clerk.ts" -import { verifyWebhook } from "@clerk/astro/webhooks"; -import type { APIRoute } from "astro"; -import prisma from "../../../lib/prisma"; - -export const POST: APIRoute = async ({ request }) => { - try { - const evt = await verifyWebhook(request, { - signingSecret: import.meta.env.CLERK_WEBHOOK_SIGNING_SECRET, - }); - const { id } = evt.data; - const eventType = evt.type; - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); - - if (eventType === "user.created") { - // [!code ++] - const { id, email_addresses, first_name, last_name } = evt.data; // [!code ++] - await prisma.user.upsert({ - // [!code ++] - where: { clerkId: id }, // [!code ++] - update: {}, // [!code ++] - create: { - // [!code ++] - clerkId: id, // [!code ++] - email: email_addresses[0].email_address, // [!code ++] - name: `${first_name} ${last_name}`, // [!code ++] - }, // [!code ++] - }); // [!code ++] - } // [!code ++] - } catch (err) { - console.error("Error verifying webhook:", err); - return new Response("Error verifying webhook", { status: 400 }); - } -}; -``` - -Finally, return a response to Clerk to confirm the webhook was received: - -```typescript title="src/pages/api/webhooks/clerk.ts" -import { verifyWebhook } from "@clerk/astro/webhooks"; -import type { APIRoute } from "astro"; -import prisma from "../../../lib/prisma"; - -export const POST: APIRoute = async ({ request }) => { - try { - const evt = await verifyWebhook(request, { - signingSecret: import.meta.env.CLERK_WEBHOOK_SIGNING_SECRET, - }); - const { id } = evt.data; - const eventType = evt.type; - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); - - if (eventType === "user.created") { - const { id, email_addresses, first_name, last_name } = evt.data; - await prisma.user.upsert({ - where: { clerkId: id }, - update: {}, - create: { - clerkId: id, - email: email_addresses[0].email_address, - name: `${first_name} ${last_name}`, - }, - }); - } - - return new Response("Webhook received", { status: 200 }); // [!code ++] - } catch (err) { - console.error("Error verifying webhook:", err); - return new Response("Error verifying webhook", { status: 400 }); - } -}; -``` - -### 4.2. Expose your local app for webhooks - -You'll need to expose your local app for webhooks with [ngrok](https://ngrok.com/). This will allow Clerk to reach your `/api/webhooks/clerk` route to push events like `user.created`. - -Start your development server: - -```npm -npm run dev -``` - -In a separate terminal window, install ngrok globally and expose your local app: - -```npm -npm install --global ngrok -ngrok http 4321 -``` - -Copy the ngrok `Forwarding URL` (e.g., `https://a65a60261342.ngrok-free.app`). This will be used to configure the webhook URL in Clerk. - -### 4.3. Configure Astro to allow ngrok connections - -Astro needs to be configured to accept connections from the ngrok domain. Update your `astro.config.mjs` to include the ngrok host in the allowed hosts list: - -```javascript title="astro.config.mjs" -import { defineConfig } from "astro/config"; -import node from "@astrojs/node"; -import clerk from "@clerk/astro"; - -export default defineConfig({ - integrations: [clerk()], - adapter: node({ mode: "standalone" }), - output: "server", - server: { - // [!code ++] - allowedHosts: ["localhost", ".ngrok-free.app"], // [!code ++] - }, // [!code ++] -}); -``` - -:::note - -Replace `` with the subdomain from your ngrok URL. For example, if your ngrok URL is `https://a65a60261342.ngrok-free.app`, use `a65a60261342.ngrok-free.app`. - -::: - -### 4.4. Register the webhook in Clerk - -Navigate to the **_Webhooks_** section of your Clerk application located near the bottom of the **_Configure_** tab under **_Developers_**. - -Click **_Add Endpoint_** and paste the ngrok URL into the **_Endpoint URL_** field and add `/api/webhooks/clerk` to the end. It should look similar to this: - -```text -https://a65a60261342.ngrok-free.app/api/webhooks/clerk -``` - -Subscribe to the **user.created** event by checking the box next to it under **_Message Filtering_**. - -Click **_Create_** to save the webhook endpoint. - -Copy the **_Signing Secret_** and add it to your `.env` file: - -```bash title=".env" -# Prisma -DATABASE_URL= - -# Clerk -PUBLIC_CLERK_PUBLISHABLE_KEY= -CLERK_SECRET_KEY= -CLERK_WEBHOOK_SIGNING_SECRET= # [!code ++] -``` - -Restart your dev server to pick up the new environment variable: - -```npm -npm run dev -``` - -### 4.5. Test the integration - -Navigate to `http://localhost:4321` in your browser and sign in using any of the sign-up options you configured in Clerk. - -Open Prisma Studio to verify that the user was created in your database: - -```npm -npx prisma studio -``` - -You should see a new user record with the Clerk ID, email, and name from your sign-up. - -:::note - -If you don't see a user record, there are a few things to check: - -- Delete your user from the Users tab in Clerk and try signing up again. -- Check your ngrok URL and ensure it's correct _(it will change every time you restart ngrok)_. -- Verify your Clerk webhook is pointing to the correct ngrok URL. -- Make sure you've added `/api/webhooks/clerk` to the end of the webhook URL. -- Ensure you've subscribed to the **user.created** event in Clerk. -- Confirm you've added the ngrok host to `allowedHosts` in `astro.config.mjs` and removed `https://`. -- Check the terminal running `npm run dev` for any error messages. - -::: - -You've successfully built an Astro application with Clerk authentication and Prisma, creating a foundation for a secure and scalable full-stack application that handles user management and data persistence with ease. - -## Next steps - -Now that you have a working Astro app with Clerk authentication and Prisma connected to a Prisma Postgres database, you can: - -- Add user profile management and update functionality -- Build protected API routes that require authentication -- Extend your schema with additional models related to users -- Deploy to your preferred hosting platform and set your production webhook URL in Clerk -- Enable query caching with [Prisma Postgres](/v6/postgres/database/caching) for better performance - -### More info - -- [Prisma Documentation](/v6/orm/overview/introduction/what-is-prisma) -- [Astro Documentation](https://docs.astro.build) -- [Clerk Documentation](https://clerk.com/docs) diff --git a/apps/docs/content/docs.v6/guides/clerk-nextjs.mdx b/apps/docs/content/docs.v6/guides/clerk-nextjs.mdx deleted file mode 100644 index 2cf142ca10..0000000000 --- a/apps/docs/content/docs.v6/guides/clerk-nextjs.mdx +++ /dev/null @@ -1,834 +0,0 @@ ---- -title: Clerk (with Next.js) -description: Learn how to use Prisma ORM in a Next.js app with Clerk Auth -image: /img/guides/prisma-clerk-nextjs-cover.png -url: /v6/guides/clerk-nextjs -metaTitle: How to use Prisma ORM and Prisma Postgres with Clerk Auth and Next.js -metaDescription: Learn how to use Prisma ORM in a Next.js app with Clerk Auth ---- - -## Introduction - -[Clerk](https://clerk.com/) is a drop-in auth provider that handles sign-up, sign-in, user management, and webhooks so you don't have to. - -In this guide you'll wire Clerk into a brand-new [Next.js](https://nextjs.org/) app, persist users in a [Prisma Postgres](https://prisma.io/postgres) database, and expose a tiny posts API. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/clerk-nextjs). - -## Prerequisites - -- [Node.js 20+](https://nodejs.org) -- [Clerk account](https://clerk.com) -- [ngrok account](https://ngrok.com) - -## 1. Set up your project - -Create the app: - -```npm -npx create-next-app@latest clerk-nextjs-prisma -``` - -It will prompt you to customize your setup. Choose the defaults: - -:::info - -- _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?_ `No` -- _Would you like to use App Router?_ (recommended) `Yes` -- _Would you like to use Turbopack for `next dev`?_ `Yes` -- _Would you like to customize the import alias (`@/_`by default)?*`No` - -::: - -Navigate to the project directory: - -```bash -cd clerk-nextjs-prisma -``` - -## 2. Set up Clerk - -### 2.1. Create a new Clerk application - -[Sign in](https://dashboard.clerk.com/sign-in) to Clerk and navigate to the home page. From there, press the `Create Application` button to create a new application. Enter a title, select your sign-in options, and click `Create Application`. - -:::info - -For this guide, the Google, Github, and Email sign in options will be used. - -::: - -Install the Clerk Next.js SDK: - -```npm -npm install @clerk/nextjs -``` - -Copy your Clerk keys and paste them into **.env** in the root of your project: - -```bash title=".env" -# Clerk # [!code ++] -NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= # [!code ++] -CLERK_SECRET_KEY= # [!code ++] -``` - -### 2.2. Protect routes with Clerk middleware - -The `clerkMiddleware` helper enables authentication and is where you'll configure your protected routes. - -Create a `middleware.ts` file in the root directory of your project: - -```tsx title="middleware.ts" showLineNumbers -import { clerkMiddleware } from "@clerk/nextjs/server"; // [!code ++] - -export default clerkMiddleware(); // [!code ++] - -export const config = { - // [!code ++] - matcher: [ - // [!code ++] - "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)", // [!code ++] - "/(api|trpc)(.*)", // [!code ++] - ], // [!code ++] -}; // [!code ++] -``` - -### 2.3. Add Clerk UI to your layout - -Next, you'll need to wrap your app in the `ClerkProvider` component to make authentication globally available. - -In your `layout.tsx` file, add the `ClerkProvider` component: - -```tsx title="app/layout.tsx" showLineNumbers -import type { Metadata } from "next"; -import { Geist, Geist_Mono } from "next/font/google"; -import "./globals.css"; -import { ClerkProvider } from "@clerk/nextjs"; {/* [!code ++] */} - -const geistSans = Geist({ - variable: "--font-geist-sans", - subsets: ["latin"], -}); - -const geistMono = Geist_Mono({ - variable: "--font-geist-mono", - subsets: ["latin"], -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - {/* [!code ++] */} - - - {children} - - - {/* [!code ++] */} - ); -} -``` - -Create a `Navbar` component which will be used to display the Sign In and Sign Up buttons as well as the User Button once a user is signed in: - -```tsx title="app/layout.tsx" showLineNumbers -import type { Metadata } from "next"; -import { Geist, Geist_Mono } from "next/font/google"; -import "./globals.css"; -import { - ClerkProvider, - UserButton, // [!code ++] - SignInButton, // [!code ++] - SignUpButton, // [!code ++] - SignedOut, // [!code ++] - SignedIn, // [!code ++] -} from "@clerk/nextjs"; - -const geistSans = Geist({ - variable: "--font-geist-sans", - subsets: ["latin"], -}); - -const geistMono = Geist_Mono({ - variable: "--font-geist-mono", - subsets: ["latin"], -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - - {/* [!code ++] */} - {children} - - - - ); -} - -const Navbar = () => { - // [!code ++] - return ( - // [!code ++] -
- {" "} - // [!code ++] - - {" "} - // [!code ++] - // [!code ++] - // [!code ++] - {" "} - // [!code ++] - - {" "} - // [!code ++] - // [!code ++] - {" "} - // [!code ++] -
// [!code ++] - ); // [!code ++] -}; // [!code ++] -``` - -## 3. Install and configure Prisma - -### 3.1. Install dependencies - -To get started with Prisma, you'll need to install a few dependencies: - -```npm -npm install prisma tsx @types/pg --save-dev -``` - -```npm -npm install @prisma/client @prisma/adapter-pg dotenv pg -``` - -:::info - -If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/v6/orm/overview/databases/database-drivers). - -::: - -Once installed, initialize Prisma in your project: - -```npm -npx prisma init --db --output ../app/generated/prisma -``` - -:::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for the database like "My Clerk NextJS Project" -::: -This will create: - -- A `prisma/` directory with a `schema.prisma` file -- A `DATABASE_URL` in `.env` - -### 3.2. Define your Prisma Schema - -In the `prisma/schema.prisma` file, add the following models: - -```prisma title="prisma/schema.prisma" showLineNumbers -generator client { - provider = "prisma-client" - output = "../app/generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - clerkId String @unique // [!code ++] - email String @unique // [!code ++] - name String? // [!code ++] - posts Post[] // [!code ++] -} // [!code ++] - -model Post { // [!code ++] - id Int @id @default(autoincrement()) // [!code ++] - title String // [!code ++] - content String? // [!code ++] - published Boolean @default(false) // [!code ++] - authorId Int // [!code ++] - author User @relation(fields: [authorId], references: [id]) // [!code ++] - createdAt DateTime @default(now()) // [!code ++] -} // [!code ++] -``` - -This will create two models: `User` and `Post`, with a one-to-many relationship between them. - -Create a `prisma.config.ts` file to configure Prisma: - -```typescript title="prisma.config.ts" showLineNumbers -import "dotenv/config"; // [!code ++] -import { defineConfig, env } from "prisma/config"; // [!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: - -```npm -npm install dotenv -``` - -::: - -Now, run the following command to create the database tables and generate the Prisma Client: - -```npm -npx prisma migrate dev --name init -``` - -```npm -npx prisma generate -``` - -:::warning - -It is recommended that you add `/app/generated/prisma` to your `.gitignore` file. - -::: - -### 3.3. Create a reusable Prisma Client - -In the root directory, create a `lib` directory and a `prisma.ts` file inside it: - -```tsx title="lib/prisma.ts" showLineNumbers -import { PrismaClient } from "../app/generated/prisma/client"; // [!code ++] -import { PrismaPg } from "@prisma/adapter-pg"; // [!code ++] - -const adapter = new PrismaPg({ - // [!code ++] - connectionString: process.env.DATABASE_URL!, // [!code ++] -}); // [!code ++] - -const globalForPrisma = global as unknown as { - // [!code ++] - prisma: PrismaClient; // [!code ++] -}; // [!code ++] - -const prisma = // [!code ++] - globalForPrisma.prisma || // [!code ++] - new PrismaClient({ - // [!code ++] - adapter, // [!code ++] - }); // [!code ++] - -if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; // [!code ++] - -export default prisma; // [!code ++] -``` - -## 4. Wire Clerk to the database - -### 4.1. Create a Clerk webhook endpoint - -Create a new API route at `app/api/webhooks/clerk/route.ts`: - -Import the necessary dependencies: - -```tsx title="app/api/webhooks/clerk/route.ts" showLineNumbers -import { verifyWebhook } from "@clerk/nextjs/webhooks"; // [!code ++] -import { NextRequest } from "next/server"; // [!code ++] -import prisma from "@/lib/prisma"; // [!code ++] -``` - -Create the `POST` method that Clerk will call and verify the webhook: - -```tsx title="app/api/webhooks/clerk/route.ts" showLineNumbers -import { verifyWebhook } from "@clerk/nextjs/webhooks"; -import { NextRequest } from "next/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: NextRequest) { - // [!code ++] - try { - // [!code ++] - const evt = await verifyWebhook(req); // [!code ++] - const { id } = evt.data; // [!code ++] - const eventType = evt.type; // [!code ++] - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); // [!code ++] - } catch (err) { - // [!code ++] - console.error("Error verifying webhook:", err); // [!code ++] - return new Response("Error verifying webhook", { status: 400 }); // [!code ++] - } // [!code ++] -} // [!code ++] -``` - -When a new user is created, they need to be stored in the database. - -You'll do that by checking if the event type is `user.created` and then using Prisma's `upsert` method to create a new user if they don't exist: - -```tsx title="app/api/webhooks/clerk/route.ts" showLineNumbers -import { verifyWebhook } from "@clerk/nextjs/webhooks"; -import { NextRequest } from "next/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: NextRequest) { - try { - const evt = await verifyWebhook(req); - const { id } = evt.data; - const eventType = evt.type; - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); - - if (eventType === "user.created") { - // [!code ++] - const { id, email_addresses, first_name, last_name } = evt.data; // [!code ++] - await prisma.user.upsert({ - // [!code ++] - where: { clerkId: id }, // [!code ++] - update: {}, // [!code ++] - create: { - // [!code ++] - clerkId: id, // [!code ++] - email: email_addresses[0].email_address, // [!code ++] - name: `${first_name} ${last_name}`, // [!code ++] - }, // [!code ++] - }); // [!code ++] - } // [!code ++] - } catch (err) { - console.error("Error verifying webhook:", err); - return new Response("Error verifying webhook", { status: 400 }); - } -} -``` - -Finally, return a response to Clerk to confirm the webhook was received: - -```tsx title="app/api/webhooks/clerk/route.ts" showLineNumbers -import { verifyWebhook } from "@clerk/nextjs/webhooks"; -import { NextRequest } from "next/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: NextRequest) { - try { - const evt = await verifyWebhook(req); - const { id } = evt.data; - const eventType = evt.type; - console.log(`Received webhook with ID ${id} and event type of ${eventType}`); - - if (eventType === "user.created") { - const { id, email_addresses, first_name, last_name } = evt.data; - await prisma.user.upsert({ - where: { clerkId: id }, - update: {}, - create: { - clerkId: id, - email: email_addresses[0].email_address, - name: `${first_name} ${last_name}`, - }, - }); - } - - return new Response("Webhook received", { status: 200 }); - { - /* [!code ++] */ - } - } catch (err) { - console.error("Error verifying webhook:", err); - return new Response("Error verifying webhook", { status: 400 }); - } -} -``` - -### 4.2. Expose your local app for webhooks - -You'll need to expose your local app for webhooks with [ngrok](https://ngrok.com/). This will allow Clerk to reach your `/api/webhooks/clerk` route to push events like `user.created`. - -Install ngrok and expose your local app: - -```npm -npm install --global ngrok -ngrok http 3000 -``` - -Copy the ngrok `Forwarding URL`. This will be used to set the webhook URL in Clerk. - -Navigate to the **_Webhooks_** section of your Clerk application located near the bottom of the **_Configure_** tab under **_Developers_**. - -Click **_Add Endpoint_** and paste the ngrok URL into the **_Endpoint URL_** field and add `/api/webhooks/clerk` to the end of the URL. It should look similar to this: - -```text -https://a60b-99-42-62-240.ngrok-free.app/api/webhooks/clerk -``` - -Copy the **_Signing Secret_** and add it to your `.env` file: - -```bash title=".env" -# Prisma -DATABASE_URL= - -# Clerk -NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= -CLERK_SECRET_KEY= -CLERK_WEBHOOK_SIGNING_SECRET= # [!code ++] -``` - -On the home page, press Sign Up and create an account using any of the sign-up options - -Open Prisma Studio and you should see a user record. - -```npm -npx prisma studio -``` - -:::note - -If you don't see a user record, there are a few things to check: - -- Delete your user from the Users tab in Clerk and try again. -- Check your ngrok URL and ensure it's correct _(it will change everytime you restart ngrok)_. -- Check your Clerk webhook is pointing to the correct ngrok URL. -- Make sure you've added `/api/webhooks/clerk` to the end of the URL. - -::: - -## 5. Build a posts API - -To create posts under a user, you'll need to create a new API route at `app/api/posts/route.ts`: - -Start by importing the necessary dependencies: - -```tsx title="app/api/posts/route.ts" showLineNumbers -import { auth } from "@clerk/nextjs/server"; // [!code ++] -import prisma from "@/lib/prisma"; // [!code ++] -``` - -Get the `clerkId` of the authenticated user. If there's no user, return a `401` Unauthorized response: - -```tsx title="app/api/posts/route.ts" showLineNumbers -import { auth } from "@clerk/nextjs/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: Request) { - // [!code ++] - const { userId: clerkId } = await auth(); // [!code ++] - if (!clerkId) return new Response("Unauthorized", { status: 401 }); // [!code ++] -} // [!code ++] -``` - -Match the Clerk user to a user in the database. If none is found, return a `404` Not Found response: - -```tsx title="app/api/posts/route.ts" showLineNumbers -import { auth } from "@clerk/nextjs/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: Request) { - const { userId: clerkId } = await auth(); - if (!clerkId) return new Response("Unauthorized", { status: 401 }); - - const user = await prisma.user.findUnique({ - // [!code ++] - where: { clerkId }, // [!code ++] - }); // [!code ++] - - if (!user) return new Response("User not found", { status: 404 }); // [!code ++] -} -``` - -Destructure the title and content from the incoming request and create a post. Once done, return a `201` Created response: - -```tsx title="app/api/posts/route.ts" showLineNumbers -import { auth } from "@clerk/nextjs/server"; -import prisma from "@/lib/prisma"; - -export async function POST(req: Request) { - const { userId: clerkId } = await auth(); - if (!clerkId) return new Response("Unauthorized", { status: 401 }); - - const { title, content } = await req.json(); - { - /* [!code ++] */ - } - - const user = await prisma.user.findUnique({ - where: { clerkId }, - }); - - if (!user) return new Response("User not found", { status: 404 }); - - const post = await prisma.post.create({ - // [!code ++] - data: { - // [!code ++] - title, // [!code ++] - content, // [!code ++] - authorId: user.id, // [!code ++] - }, // [!code ++] - }); // [!code ++] - - return new Response(JSON.stringify(post), { status: 201 }); - { - /* [!code ++] */ - } -} -``` - -## 6. Add a Post creation UI - -In `/app`, create a `/components` directory and a `PostInputs.tsx` file inside it: - -```tsx title="app/components/PostInputs.tsx" showLineNumbers -"use client"; -{ - /* [!code ++] */ -} - -import { useState } from "react"; -{ - /* [!code ++] */ -} - -export default function PostInputs() { - // [!code ++] - const [title, setTitle] = useState(""); // [!code ++] - const [content, setContent] = useState(""); // [!code ++] -} // [!code ++] -``` - -This component uses `"use client"` to ensure the component is rendered on the client. The title and content are stored in their own `useState` hooks. - -Create a function that will be called when a form is submitted: - -```tsx title="app/components/PostInputs.tsx" showLineNumbers -"use client"; - -import { useState } from "react"; - -export default function PostInputs() { - const [title, setTitle] = useState(""); - const [content, setContent] = useState(""); - - async function createPost(e: React.FormEvent) { - // [!code ++] - e.preventDefault(); // [!code ++] - if (!title || !content) return; // [!code ++] - - await fetch("/api/posts", { - // [!code ++] - method: "POST", // [!code ++] - headers: { "Content-Type": "application/json" }, // [!code ++] - body: JSON.stringify({ title, content }), // [!code ++] - }); // [!code ++] - - setTitle(""); // [!code ++] - setContent(""); // [!code ++] - location.reload(); // [!code ++] - } // [!code ++] -} -``` - -You'll be using a form to create a post and call the `POST` route you created earlier: - -```tsx title="app/components/PostInputs.tsx" showLineNumbers -"use client"; - -import { useState } from "react"; - -export default function PostInputs() { - const [title, setTitle] = useState(""); - const [content, setContent] = useState(""); - - async function createPost(e: React.FormEvent) { - e.preventDefault(); - if (!title || !content) return; - - await fetch("/api/posts", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ title, content }), - }); - - setTitle(""); - setContent(""); - location.reload(); - } - - return ( - // [!code ++] -
- {" "} - // [!code ++] - setTitle(e.target.value)} // [!code ++] - className="w-full p-2 border border-zinc-800 rounded" // [!code ++] - />{" "} - // [!code ++] -