From 28e619072c4e9c26c4fcf366cb1e5728fa683fb3 Mon Sep 17 00:00:00 2001 From: Aman Varshney Date: Sun, 14 Dec 2025 00:56:16 +0530 Subject: [PATCH] docs: update nuxt guide --- .../900-prisma-nuxt-module.mdx | 370 +------------- content/800-guides/100-nuxt.mdx | 475 ++++++++---------- 2 files changed, 205 insertions(+), 640 deletions(-) diff --git a/content/200-orm/800-more/600-help-and-troubleshooting/900-prisma-nuxt-module.mdx b/content/200-orm/800-more/600-help-and-troubleshooting/900-prisma-nuxt-module.mdx index 790bbc5f2e..877c2ae405 100644 --- a/content/200-orm/800-more/600-help-and-troubleshooting/900-prisma-nuxt-module.mdx +++ b/content/200-orm/800-more/600-help-and-troubleshooting/900-prisma-nuxt-module.mdx @@ -5,374 +5,6 @@ metaDescription: 'Learn how to easily add Prisma ORM to your Nuxt apps, use its community_section: true --- -The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt applications. - -[Prisma ORM](/orm/overview/introduction/what-is-prisma) is a database library that lets you model your database schema, provides auto-generated migrations and lets you query the database in an intuitive and type-safe way. - -This module provides several features to streamline the setup and usage of Prisma ORM in a Nuxt application, making it easier to interact with your database. - :::warning -The `@prisma/nuxt` module is currently not supported with Prisma ORM 7 or when using a custom `generator client { output = ... }`. For Prisma 7 projects, follow the general Nuxt guide instead. +The `@prisma/nuxt` module is deprecated and no longer recommended. Please follow our [Nuxt guide](/guides/nuxt) for the recommended approach to integrating Prisma ORM with your Nuxt application. ::: - -## Features - -- **Project initialization**: Automatically sets up a Prisma ORM project with a SQLite database within your Nuxt project. -- **Composable**: Provides an auto-imported `usePrismaClient()` composable for use in your Vue files. -- **API route integration**: Automatically imports an instance of `PrismaClient` for use in API routes to query your DB. -- **Prisma Studio access**: Enables access to Prisma Studio through Nuxt Devtools for viewing and manually editing data. - -## Getting started - -1. Create a [new Nuxt Project](https://nuxt.com/docs/getting-started/installation#new-project): - ```terminal - npm create nuxt test-nuxt-app - ``` - -2. Navigate to project directory and install `@prisma/nuxt` using the Nuxt CLI: - ```terminal - cd test-nuxt-app - npx nuxi@latest module add @prisma/nuxt - ``` -
- :::warning - - If you're using `pnpm`, make sure to hoist Prisma dependencies. Follow the [Prisma studio steps](#prisma-studio-not-opening-with-pnpm) for detailed instructions. - - ::: - -3. Start the development server: - ```terminal - npm run dev - ``` - - Starting the development server will: - 1. Automatically install the [Prisma CLI](/orm/reference/prisma-cli-reference) - 2. Initialize a Prisma project with SQLite - 3. Create an `User` and `Post` example model in the Prisma Schema file: - ```prisma file=prisma/schema.prisma - // This is your Prisma schema file, - // learn more about it in the docs: https://pris.ly/d/prisma-schema - - generator client { - provider = "prisma-client" - output = "./generated" - } - - datasource db { - provider = "sqlite" - } - - 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 - } - ``` - 4. Prompt you to run a migration to create database tables with [Prisma Migrate](/orm/prisma-migrate/understanding-prisma-migrate/overview) - :::note - The database migrates automatically the first time you start the module if there isn't a `migrations` folder. After that, you need to run `npx prisma migrate dev` manually in the CLI to apply any schema changes. Running the `npx prisma migrate dev` command manually makes it easier and safer to manage migrations and also to [troubleshoot](/orm/prisma-migrate/workflows/troubleshooting) any migration-related errors. - ::: - 5. Install and generate a [Prisma Client](/orm/reference/prisma-client-reference) which enables you to query your DB - 6. Automatically start [Prisma Studio](/orm/tools/prisma-studio) - -4. You can now use Prisma ORM in your project. If you accepted the prompt to add Prisma Studio, you can access Prisma Studio through the Nuxt Devtools. See the [usage section](#usage) to learn how to use Prisma Client in your app. - -## Using a different database provider - -The `@prisma/nuxt` module works with any [database provider that Prisma ORM supports](/orm/reference/supported-databases). You can configure the [getting started example](#getting-started) to use a database of your choice. The steps would be different for a [database without existing data](#using-a-database-without-existing-data) and a [database with pre-existing data](#using-a-database-with-pre-existing-data). - -### Using a database without existing data - -To configure [the getting started example](#getting-started) to use a PostgreSQL database without any existing data: - -1. Stop the Nuxt development server and Prisma Studio (if they are still running): - ```terminal - npx kill-port 3000 # Stops Nuxt dev server (default port) - npx kill-port 5555 # Stops Prisma Studio (default port) - ``` -2. Navigate to the `schema.prisma` file and update the `datasource` block to specify the `postgresql` provider: - ```prisma file=prisma/schema.prisma - // This is your Prisma schema file, - // learn more about it in the docs: https://pris.ly/d/prisma-schema - - generator client { - provider = "prisma-client" - output = "./generated" - } - - 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 - } - ``` -2. Update the `DATABASE_URL` environment variable in the `.env` file with your PostgreSQL database URL: - ```.env file=.env - ## This is a sample database URL, please use a valid URL - DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample" - ``` -3. Delete the SQLite database file and the migrations folder: - ```terminal - rm prisma/dev.db # Delete SQLite database file - rm -r prisma/migrations # Delete the pre-existing migrations folder - ``` -4. Run the development server: - ```terminal - npm run dev - ``` - Starting the development server will prompt you to migrate the schema changes to the database, to which you should agree. Then agree to the prompt to install and access Prisma Studio from the Nuxt Devtools. -5. The `@prisma/nuxt` module is ready to use with your PostgreSQL database. See the [usage section](#usage) to learn how to use Prisma Client in your app. - -### Using a database with pre-existing data - -To configure [the getting started example](#getting-started) to use a PostgreSQL database that already has data in it: - -1. Stop the dev server and Prisma Studio (if they are still running): - ```terminal - // stops Nuxt dev server from running incase it's still running - npx kill-port 3000 - // stops Prisma Studio instance incase it's still running - npx kill-port 5555 - ``` -2. Delete the Prisma folder: - ```terminal - rm -r prisma/ - ``` -3. Update the `DATABASE_URL` environment variable in the `.env` file with your PostgreSQL database URL: - ```.env file=.env - ## This is a sample database URL, please use a valid URL - DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample" - ``` -4. To generate a Prisma Schema and migrations folder from the existing database, you have to [introspect](/orm/prisma-schema/introspection) the database. Complete **step 1** to **step 4** from the [introspection guide](/orm/prisma-migrate/getting-started#adding-prisma-migrate-to-an-existing-project) and continue. -5. Starting the development server will skip the prompt to migrate the schema changes to the database, as the migrations folder already exists. Agree to the prompt to install and access Prisma Studio from the Nuxt Devtools. -6. The `@prisma/nuxt` module is ready to be used with your PostgreSQL database. See the [usage section](#usage) to learn how to use Prisma Client in your app. - -## Usage - -### Option A: `usePrismaClient` composable - -#### Using the composable in your Nuxt server component - -If you're using [Nuxt server components](https://nuxt.com/docs/guide/directory-structure/components#server-components), you can use the global instance of the Prisma Client in your `.server.vue` files: -```html - - - -``` - -### Option B: `lib/prisma.ts` - -After running through the initial setup prompts, this module creates the `lib/prisma.ts` file which contains a global instance of Prisma Client. -```typescript file=lib/prisma.ts -import { PrismaClient } from '../prisma/generated/client' - -const prismaClientSingleton = () => { - return new PrismaClient() -} - -declare const globalThis: { - prismaGlobal: ReturnType; -} & typeof global; - -const prisma = globalThis.prismaGlobal ?? prismaClientSingleton() - -export default prisma - -if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma -``` - -You can customize Prisma Client's capabilities by using client extensions in your `lib/prisma.ts` file. Here is an example using the [Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate): - -```typescript file=lib/prisma.ts -import { PrismaClient } from '../prisma/generated/client' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prismaClientSingleton = () => { - return new PrismaClient().$extends(withAccelerate()) -} - -declare const globalThis: { - prismaGlobal: ReturnType; -} & typeof global; - -const prisma = globalThis.prismaGlobal ?? prismaClientSingleton() - -export default prisma - -if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma -``` -
-:::info - -Use the `prisma` instance from the `lib` folder if you want to leverage a client using [Prisma Client extensions](/orm/prisma-client/client-extensions). - -::: - -#### Using the global Prisma Client instance in your API route - -You can use the global instance of the Prisma Client in your Nuxt API route as follows: -```typescript -import prisma from "~/lib/prisma"; - -export default defineEventHandler(async (event) => { - return { - user: await prisma.user.findFirst(), - }; -}); -``` - -#### Using the global Prisma Client instance in your Nuxt server component - -If you're using [Nuxt server components](https://nuxt.com/docs/guide/directory-structure/components#server-components), you can use the global instance of the Prisma Client `.server.vue` files: -```html - - - -``` - -## Configuration - -You can configure the `@prisma/nuxt` module by using the `prisma` key in `nuxt.config.ts`: - -```ts file=nuxt.config.ts -export default defineNuxtConfig({ - // ... - prisma: { - // Options - } -}) -``` -
-:::note - The `prisma` key is available in `nuxt.config.ts` after successfully setting up the module by running `npm run dev` -::: - -| Option | Type | Default | Description | -|---------------------|-----------|---------|-------------| -| **installCLI** | `boolean` | true | Whether to install the [Prisma CLI](/orm/tools/prisma-cli). | -| **installClient** | `boolean` | true | Whether to install the [Prisma Client](/orm/prisma-client) library in the project. | -| **generateClient** | `boolean` | true | Whether to [generate](/orm/prisma-client/setup-and-configuration/generating-prisma-client) the `PrismaClient` instance. Executes `npx prisma generate` on every run to update the client based on the schema changes. | -| **formatSchema** | `boolean` | true | Whether to [format](/orm/reference/prisma-cli-reference#format) the [Prisma Schema](/orm/prisma-schema) file. | -| **installStudio** | `boolean` | true | Whether to install and start [Prisma Studio](https://www.prisma.io/studio) in the Nuxt Devtools. | -| **autoSetupPrisma** | `boolean` | false | Whether to skip all prompts during setup. This option is useful for automating Prisma setup in scripts or CI/CD pipelines. | -| **skipPrompts** | `false` | false | Skips all prompts | -| **prismaRoot** | `string` | false | Required when using [Nuxt layers](https://nuxt.com/docs/getting-started/layers). For example, if you have a Nuxt layer called `database`, the `prismaRoot` would be `./database` in the base nuxt config. This refers to the folder where Prisma will be initialized or checked. | -| **prismaSchemaPath** | `string` | `undefined` | Required when using [Nuxt layers](https://nuxt.com/docs/getting-started/layers). For example, if you have a Nuxt layer called `database`, the `prismaSchemaPath` would be `./database/prisma/schema.prisma` in the base nuxt config. | -| **runMigration** | `boolean` | true | Whether to run a Prisma Migration automatically. If you are using MongoDB or PlanetScale, use the [`npx prisma db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema#choosing-db-push-or-prisma-migrate). Migrations aren’t supported for these databases, so this command will ensure your schema is updated appropriately. | - -## Limitations - -### `PrismaClient` constructor options are not configurable in the `usePrismaClient` composable - -The `usePrismaClient` module does not currently allow for configuration of `PrismaClient` [constructor options](/orm/reference/prisma-client-reference#prismaclient). - -### The `usePrismaClient` composable is not supported in edge runtimes - -The `usePrismaClient` composable currently relies on a `PrismaClient` instance that does not work in edge runtimes. If you require edge support for the composable, please let us know on [Discord](https://pris.ly/discord?utm_source=docs&utm_medium=inline_text) or [GitHub](https://github.com/prisma/nuxt-prisma). - -## Troubleshooting - -### Prisma Studio not opening with `pnpm` - -If you're encountering the following error when using `pnpm` and Prisma Studio isn't opening: - -```terminal -Uncaught SyntaxError: The requested module '/_nuxt/node_modules/.pnpm/*@*/node_modules/@prisma/client/index-browser.js?v=' does not provide an export named 'PrismaClient' (at plugin.mjs?v=*) -``` - -To resolve this issue, create a `.npmrc` file in your project root and add the following configuration to hoist Prisma dependencies: - -```.npmrc file=.npmrc -hoist-pattern[]=*prisma* -``` - -This will ensure that Prisma dependencies are properly resolved by `pnpm`. - -### Resolving `TypeError: Failed to resolve module specifier ".prisma/client/index-browser"` - -If you encounter the following error message in the browser console after building and previewing your application: - -``` -TypeError: Failed to resolve module specifier ".prisma/client/index-browser" -``` -To resolve this issue, add the following configuration to your nuxt.config.ts file: - -```ts file=nuxt.config.ts -import { defineNuxtConfig } from 'nuxt' - -export default defineNuxtConfig({ - modules: [ - '@prisma/nuxt', - ], - // additional config - vite: { - resolve: { - alias: { - '.prisma/client/index-browser': './node_modules/.prisma/client/index-browser.js', - }, - }, - }, -}) -``` - -This configuration ensures that the module specifier is correctly mapped to the appropriate file. - -### Limitations in package manager support - -The module is designed to work with popular package managers, including npm, Yarn, and pnpm. However, as of `v0.2`, it is not fully compatible with Bun due to an issue causing an indefinite installation loop. - -Additionally, this package has not been tested with Deno and is therefore not officially **supported.** - -### Resolving `Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.` - -If you encounter the following message even if you have generated the client. - -```terminal -Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again. -``` - -Please try delete `output = ../generated/prisma` in schema.prisma, like - -```prisma file=prisma/schema.prisma -generator client { - provider = "prisma-client" - output = "./generated" -} -``` - -When you specify a custom output directory for the Prisma Client, it means that the generated client code will not be located in the default `node_modules/@prisma/client directory`. Instead, it will be generated in your project's root directory under `generated/prisma/`. However, the `@prisma/nuxt` module in Nuxt expects to find `PrismaClient` in the default `@prisma/client` location. diff --git a/content/800-guides/100-nuxt.mdx b/content/800-guides/100-nuxt.mdx index 88137059b7..18e275ca5a 100644 --- a/content/800-guides/100-nuxt.mdx +++ b/content/800-guides/100-nuxt.mdx @@ -1,59 +1,76 @@ --- title: 'How to use Prisma ORM with Nuxt' metaTitle: 'Build a Nuxt app with Prisma ORM and Prisma Postgres' -description: 'A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app and deploying to Vercel.' +description: 'A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app.' sidebar_label: 'Nuxt' completion_time: '10 min' image: '/img/guides/prisma-postgres-and-prisma-nuxt-guide.png' tags: - Nuxt - Prisma Postgres - - Vercel community_section: true --- -This guide explains how to set up a Nuxt application, configure [Prisma Postgres](https://prisma.io/postgres) with Prisma ORM, and deploy the project to [Vercel](https://vercel.com/) for production. +This guide shows you how to set up Prisma ORM in a Nuxt application with [Prisma Postgres](https://prisma.io/postgres). -Here's what you'll learn: +## Prerequisites -- How to set up a Nuxt project that uses Prisma ORM directly. -- How to configure and use Prisma Postgres with Prisma ORM in your Nuxt app. -- How to deploy the project to Vercel. +- Node.js 18+ +- A [Prisma Postgres](https://console.prisma.io/) database (or any PostgreSQL database) -## Prerequisites +## 1. Create a Nuxt project + +Create a new Nuxt project and install dependencies: + +```terminal +npx nuxi@latest init hello-prisma +cd hello-prisma +npm install @prisma/client @prisma/adapter-pg pg +npm install -D prisma @types/pg dotenv tsx +``` -To follow this guide, ensure you have the following: +## 2. Initialize Prisma -- Node.js version: A [compatible Node.js version](/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-6#minimum-supported-nodejs-versions) required for Prisma 6. -- Accounts: - - [GitHub](https://github.com) - - [Vercel](https://vercel.com) -- Basic knowledge of Git and Vercel deployment (helpful but not required). +Initialize Prisma in your project: -## 1. Create a New Nuxt Project and install Prisma ORM dependencies +```terminal +npx prisma init +``` -1. Initialize [a new Nuxt project](https://nuxt.com/docs/getting-started/installation#new-project), select `npm` as the package manager and initialize git: - ```terminal - npm create nuxt hello-world - ``` -2. Navigate into the project directory and install Prisma ORM dependencies along with the PostgreSQL driver adapter: - ```terminal - cd hello-world - npm install @prisma/client @prisma/adapter-pg pg dotenv tsx - npm install -D prisma @types/pg - ``` -3. Initialize Prisma with PostgreSQL by running: - ```terminal - npx prisma init --db - ``` +Update your `prisma/schema.prisma`: -## 2. Configure Prisma +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "./generated" +} -Before running the development server, create a `prisma.config.ts` file in the root of your project to manage environment variables and configuration: +datasource db { + provider = "postgresql" +} -```typescript file=prisma.config.ts -import 'dotenv/config' +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? +} +``` + +Create a `prisma.config.ts` file in the root of your project: + +```ts file=prisma.config.ts import { defineConfig, env } from 'prisma/config' +import 'dotenv/config' export default defineConfig({ schema: 'prisma/schema.prisma', @@ -67,112 +84,107 @@ export default defineConfig({ }) ``` -## 3. Set up Prisma ORM - -With Prisma initialized, define your data model and run a migration to create the PostgreSQL database. - -1. Update the `prisma/schema.prisma` file with the following configuration: - ```prisma file=prisma/schema.prisma - // This is your Prisma schema file, - // learn more about it in the docs: https://pris.ly/d/prisma-schema - - generator client { - provider = "prisma-client" - output = "./generated" - } - - 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 - } - ``` -2. Create the initial migration and database tables: - ```terminal - npx prisma migrate dev --name init - ``` -3. Once the command succeeds, start the Nuxt development server: - ```terminal - npm run dev - ``` -4. When the server is running at `http://localhost:3000`, stop it for now—we’ll update some files before continuing. - -## 4. Update the application code - -With Prisma configured, the next step is to update your application code to fetch and display data from your database. - -1. In the root directory of your project, create a folder named `lib` and add a `prisma.ts` file to share a single Prisma Client instance that connects through the PostgreSQL adapter: - ```ts file=lib/prisma.ts - import { PrismaPg } from '@prisma/adapter-pg' - import { PrismaClient } from '../prisma/generated/client' - - const prismaClientSingleton = () => { - const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }) - return new PrismaClient({ adapter }) - } - - type PrismaClientSingleton = ReturnType - - const globalForPrisma = globalThis as unknown as { - prisma: PrismaClientSingleton | undefined - } - - export const prisma = globalForPrisma.prisma ?? prismaClientSingleton() - - if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma - ``` - -2. Create a folder named `components` (if it doesn’t exist yet) and inside it add `User.server.vue`. This server component fetches and displays the name of the first user from the database: - ```html file=components/User.server.vue - - - - ``` +Update your `.env` file with your database connection string: -3. Modify the `app.vue` file in the root directory to include the new server component using Nuxt Islands: - ```html file=app.vue - - ``` +```bash file=.env +DATABASE_URL="postgresql://user:password@localhost:5432/mydb" +``` -4. Run the following command to start the development server again: - ```terminal - npm run dev - ``` -5. Verify the application code is working by opening your application in a browser at `https://localhost:3000`. - As there are no users in the database yet, the application will display: - ```no-copy - No user has been added yet. - ``` - This message will dynamically update when users are added to your database. +Run the migration to create your database tables: + +```terminal +npx prisma migrate dev --name init +``` + +## 3. Set up Prisma Client + +Create `server/utils/db.ts`. Nuxt auto-imports exports from `server/utils`, making `prisma` available in all API routes: -By completing these steps, your application is now capable of fetching data from your Prisma database and rendering it on the frontend. +```ts file=server/utils/db.ts +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../../prisma/generated/client' + +const prismaClientSingleton = () => { + const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! }) + return new PrismaClient({ adapter: pool }) +} -## 5. Seed your database (optional) +type PrismaClientSingleton = ReturnType -If you want sample data, create a `prisma/seed.ts` file. The following script uses the PostgreSQL adapter: +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClientSingleton | undefined +} + +export const prisma = globalForPrisma.prisma ?? prismaClientSingleton() + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma +``` + +## 4. Create API routes + +Create an API route to fetch users. The `prisma` instance is auto-imported: + +```ts file=server/api/users.get.ts +export default defineEventHandler(async () => { + const users = await prisma.user.findMany({ + include: { posts: true } + }) + return users +}) +``` + +Create an API route to create a user: + +```ts file=server/api/users.post.ts +export default defineEventHandler(async (event) => { + const body = await readBody<{ name: string; email: string }>(event) + + const user = await prisma.user.create({ + data: { + name: body.name, + email: body.email, + }, + }) + + return user +}) +``` + +## 5. Create a page + +Update `app.vue` to display users: + +```html file=app.vue + + + +``` + +## 6. Run the app + +Start the development server: + +```terminal +npm run dev +``` + +Open `http://localhost:3000` to see your app. + +## 7. Seed your database (optional) + +Create a seed file to populate your database with sample data: ```ts file=prisma/seed.ts import 'dotenv/config' @@ -182,67 +194,21 @@ import { PrismaPg } from '@prisma/adapter-pg' const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }) const prisma = new PrismaClient({ adapter }) -const userData = [ - { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: [ - { - title: 'Join the Prisma Discord', - content: 'https://pris.ly/discord', - published: true, - }, - ], - }, - }, - { - name: 'Nilu', - email: 'nilu@prisma.io', - posts: { - create: [ - { - title: 'Follow Prisma on Twitter', - content: 'https://www.twitter.com/prisma', - published: true, - }, - ], - }, - }, - { - name: 'Mahmoud', - email: 'mahmoud@prisma.io', - posts: { - create: [ - { - title: 'Ask a question about Prisma on GitHub', - content: 'https://www.github.com/prisma/prisma/discussions', - published: true, - }, - { - title: 'Prisma on YouTube', - content: 'https://pris.ly/youtube', - }, - ], - }, - }, -] - async function main() { - console.log(`Start seeding ...`) - for (const u of userData) { - const user = await prisma.user.create({ - data: u, - }) - console.log(`Created user with id: ${user.id}`) - } - console.log(`Seeding finished.`) + const alice = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World', published: true }, + }, + }, + }) + console.log(`Created user: ${alice.name}`) } main() - .then(async () => { - await prisma.$disconnect() - }) + .then(() => prisma.$disconnect()) .catch(async (e) => { console.error(e) await prisma.$disconnect() @@ -250,102 +216,69 @@ main() }) ``` -Run the seed command whenever you need demo data: +Run the seed: ```terminal npx prisma db seed ``` -## 6. Create a Prisma Postgres instance - -To store your app's data, you'll create a Prisma Postgres database instance using the Prisma Data Platform. - -Follow these steps to create your Prisma Postgres database: - -1. Log in to [Prisma Data Platform](https://console.prisma.io/) and open the Console. -1. In a [workspace](/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. +## 8. Deploy to Vercel -At this point, you'll be redirected to the **Database** page where you will need to wait for a few seconds while the status of your database changes from **`PROVISIONING`** to **`CONNECTED`**. +You can deploy your Nuxt application to Vercel using one of two methods: -Once the green **`CONNECTED`** label appears, your database is ready to use! +### Option A: Deploy using Vercel CLI -Then, find your database credentials in the **Set up database access** section, copy the `DATABASE_URL` environment variable`. +1. Install the Vercel CLI (if not already installed): + ```terminal + npm install -g vercel + ``` -```bash no-copy -DATABASE_URL= -``` +2. Deploy your project: + ```terminal + npx vercel + ``` -The `DATABASE_URL` environment variable will be required in the next steps. +3. Set the `DATABASE_URL` environment variable: + - Go to your [Vercel Dashboard](https://vercel.com/dashboard) + - Select your project + - Navigate to **Settings** → **Environment Variables** + - Add `DATABASE_URL` with your database connection string -## 7. Set up Prisma Postgres in your Nuxt app +4. Redeploy your application to apply the environment variable: + ```terminal + npx vercel --prod + ``` -Now that the Prisma Postgres instance is ready, update your Nuxt application to use this database: +### Option B: Deploy using Git integration -1. Update the `.env` file by replacing the existing `DATABASE_URL` value with the one you previously copied. It will look similar to this: - ```terminal file=.env - // edit-next-line - DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=PRISMA_POSTGRES_API_KEY" - ``` +1. Push your code to a Git repository (GitHub, GitLab, or Bitbucket). -2. Manually run a migration to sync your schema to Prisma Postgres: - ```terminal - npx prisma migrate dev --name init +2. Add `prisma generate` to your `postinstall` script in `package.json` to ensure Prisma Client is generated during deployment: + ```json file=package.json + { + "scripts": { + "postinstall": "prisma generate", + "build": "nuxt build", + "dev": "nuxt dev" + } + } ``` -3. (Optional) Seed your database with sample data: - ```terminal - npx prisma db seed - ``` -4. Start the development server again: - ```terminal - npm run dev - ``` -5. Verify the data in the application by opening `https://localhost:3000`. If you seeded the database, you should see the first user's name displayed. -Congratulations, your Nuxt app is now fully integrated with Prisma Postgres! +3. Import your project in Vercel: + - Go to [Vercel Dashboard](https://vercel.com/dashboard) + - Click **Add New** → **Project** + - Import your Git repository + - Vercel will automatically detect it as a Nuxt project -## 8. Deploy to Vercel +4. Configure environment variables: + - Before deploying, go to **Environment Variables** + - Add `DATABASE_URL` with your database connection string + - Click **Deploy** -Deploy your Nuxt application with Prisma Postgres integration to Vercel by following these steps: +Vercel will automatically build and deploy your Nuxt application. The deployment process is the same as any other Node.js application, and Prisma Client will be generated during the build process thanks to the `postinstall` script. -1. Ensure your project is version-controlled and pushed to a GitHub repository. If you don't have a repository yet, [create one on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository). Once the repository is ready, run the following commands: - ```terminal - git add . - git commit -m "Initial commit with Prisma Postgres integration" - git branch -M main - git remote add origin https://github.com//.git - git push -u origin main - ``` - :::note - Replace `` and `` with your GitHub username and the name of your repository. - ::: -2. Log in to [Vercel](https://vercel.com/) and navigate to your [Dashboard](https://vercel.com/docs/dashboard-features). -3. Create a new project. Follow Vercel's [Import an existing project](https://vercel.com/docs/getting-started-with-vercel/import) guide, but stop at [step 3](https://vercel.com/docs/getting-started-with-vercel/import#optionally-configure-any-settings) where you will configure environment variables _before_ clicking **Deploy**. -4. Configure the `DATABASE_URL` environment variable: - 1. Expand the **Environment variables** section. - 2. Add the `DATABASE_URL` environment variable: - - **Key**: `DATABASE_URL` - - **Value**: Paste your Prisma Postgres connection URL, e.g. by copying it from the `.env` file in your Nuxt project. - :::warning - Do not deploy without setting the `DATABASE_URL` variable. Your deployment will fail if the application cannot connect to the database. - ::: -5. Click the **Deploy** button. Vercel will build your project and deploy it to a live URL. -6. Open the live URL provided by Vercel and verify that your application is working: - - If you've added a user in Prisma Studio, their name should appear on the live site. - - If no users exist, the application will display: - ``` - No user has been added yet. - ``` -7. To add or manage data: - 1. Open Prisma Studio via [the Prisma Data Platform](https://prisma.io/blog/studio-for-prisma-postgres-view-and-edit-your-data-online) or local instance. - 2. Add or update user data in the database. - 3. Refresh your live site to confirm the changes. - -Congratulations! Your Nuxt application with Prisma Postgres integration is now live and fully operational on Vercel. - -## Considerations - -This guide helps you get started with Prisma Postgres in a Nuxt application. For more advanced functionality or edge deployments, explore Prisma’s broader guides and tailor the setup to your project’s needs. \ No newline at end of file +## Next steps + +- Explore the [full Nuxt + Prisma example](https://github.com/prisma/prisma-examples/tree/latest/orm/nuxt) for a complete blog application +- Learn about [Prisma Client API](/orm/prisma-client) +- Set up [Prisma Postgres](/postgres) for a managed database