-
Notifications
You must be signed in to change notification settings - Fork 876
Update nuxt guides #7275
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Update nuxt guides #7275
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,7 @@ | ||
| --- | ||
| 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 with the Prisma Nuxt module and deploying to Vercel.' | ||
| description: 'A step-by-step guide to setting up and using Prisma ORM and Prisma Postgres in a Nuxt app and deploying to Vercel.' | ||
| sidebar_label: 'Nuxt' | ||
| completion_time: '10 min' | ||
| image: '/img/guides/prisma-postgres-and-prisma-nuxt-guide.png' | ||
|
|
@@ -12,12 +12,12 @@ tags: | |
| community_section: true | ||
| --- | ||
|
|
||
| This guide explains how to set up a Nuxt application, configure [Prisma Postgres](https://prisma.io/postgres) using the [Prisma Nuxt module](/orm/more/help-and-troubleshooting/prisma-nuxt-module), and deploy the project to [Vercel](https://vercel.com/) for production. | ||
| 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. | ||
|
|
||
| Here's what you'll learn: | ||
|
|
||
| - How to set up a Nuxt project with the Prisma Nuxt module. | ||
| - How to configure and use Prisma Postgres with the Prisma Nuxt module in your Nuxt app. | ||
| - 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. | ||
|
|
||
| ## Prerequisites | ||
|
|
@@ -30,36 +30,20 @@ To follow this guide, ensure you have the following: | |
| - [Vercel](https://vercel.com) | ||
| - Basic knowledge of Git and Vercel deployment (helpful but not required). | ||
|
|
||
| ## 1. Create a New Nuxt Project and set up the Prisma Nuxt module | ||
| ## 1. Create a New Nuxt Project and install Prisma dependencies | ||
|
|
||
| 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 | ||
| ``` | ||
| :::note | ||
| We recommend using `npm` as it is the most stable option with the `@prisma/nuxt` module. | ||
| ::: | ||
|
|
||
| 2. Navigate into the project directory and install the `@prisma/nuxt` module: | ||
| 2. Navigate into the project directory and install Prisma ORM dependencies along with the PostgreSQL driver adapter: | ||
| ```terminal | ||
| cd hello-world | ||
| npm i @prisma/nuxt | ||
| npm install prisma @prisma/client @prisma/adapter-pg pg dotenv tsx | ||
|
||
| ``` | ||
| 3. Install the [Prisma Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) as it's required to use Prisma Postgres: | ||
| 3. Initialize Prisma with PostgreSQL by running: | ||
| ```terminal | ||
| npm i @prisma/extension-accelerate | ||
| ``` | ||
| 4. Add the `@prisma/nuxt` module with the following configuration to your `nuxt.config.ts` file: | ||
| ```typescript | ||
| // https://nuxt.com/docs/api/configuration/nuxt-config | ||
| export default defineNuxtConfig({ | ||
| compatibilityDate: "2024-11-01", | ||
| modules: ["@prisma/nuxt"], | ||
| experimental: { | ||
| componentIslands: true, | ||
| }, | ||
| devtools: { enabled: true }, | ||
| }); | ||
| npx prisma init --datasource-provider postgresql | ||
|
||
| ``` | ||
|
|
||
| ## 2. Configure Prisma | ||
|
|
@@ -68,62 +52,36 @@ Before running the development server, create a `prisma.config.ts` file in the r | |
|
|
||
| ```typescript file=prisma.config.ts | ||
| import 'dotenv/config' | ||
| import { defineConfig, env } from 'prisma/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'), | ||
| }, | ||
| }); | ||
| }) | ||
| ``` | ||
|
|
||
| :::note | ||
|
|
||
| You'll need to install the `dotenv` package to load environment variables: | ||
|
|
||
| ```bash | ||
| npm install dotenv | ||
| ``` | ||
|
|
||
| ::: | ||
|
|
||
| ## 3. Setup Prisma ORM by running the development server locally | ||
| ## 3. Set up Prisma ORM | ||
|
|
||
| After configuring your Nuxt project with the Prisma module, the next step is to set up Prisma ORM. This process begins by starting the development server, which automatically configures Prisma with a [SQLite database](/orm/overview/databases/sqlite). | ||
| With Prisma initialized, define your data model and run a migration to create the PostgreSQL database. | ||
|
|
||
| Run the following command to start the development server: | ||
|
|
||
| ```terminal | ||
| npm run dev | ||
| ``` | ||
|
|
||
| After running this command, you will be prompted to run a database migration with [Prisma Migrate](/orm/prisma-migrate/understanding-prisma-migrate/overview): | ||
|
|
||
| ```terminal | ||
| ? Do you want to migrate database changes to your database? › (Y/n) | ||
| ``` | ||
|
|
||
| Confirm that you want to migrate your database and create your initial tables by hitting <kbd>Y</kbd> on your keyboard. | ||
|
|
||
| Once the setup flow has terminated, it: | ||
|
|
||
| 1. Installed the [Prisma CLI](/orm/reference/prisma-cli-reference). | ||
| 2. Initialized a Prisma project with a SQLite database. | ||
| 3. Created sample `User` and `Post` models in the `schema.prisma` file: | ||
| 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 = "sqlite" | ||
| provider = "postgresql" | ||
| } | ||
|
|
||
| model User { | ||
|
|
@@ -142,39 +100,52 @@ Once the setup flow has terminated, it: | |
| authorId Int | ||
| } | ||
| ``` | ||
| 4. Created the database tables for the `User` and `Post` models from the previous steps. | ||
| :::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. Installed and generated [Prisma Client](https://da-2255.docs-51g.pages.dev/orm/reference/prisma-client-reference) which enables you to query your DB. | ||
| 6. Installed [Prisma Studio](/orm/tools/prisma-studio). | ||
|
|
||
| When the Prisma setup is complete, the development server should start on `https://localhost:3000`. | ||
|
|
||
| Next, stop the server, as we need to make some code changes. | ||
| 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 `components`. | ||
| 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 }) | ||
| } | ||
|
|
||
| 2. Inside the `components` folder, create a file named `User.server.vue`. This server component will fetch and display the name of the first user from the database: | ||
| type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton> | ||
|
|
||
| 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 | ||
| <script setup> | ||
| import { withAccelerate } from "@prisma/extension-accelerate"; | ||
| const prisma = usePrismaClient().$extends(withAccelerate()); | ||
| const user = await prisma.user.findFirst(); | ||
| import prisma from '~/lib/prisma' | ||
| const user = await prisma.user.findFirst() | ||
| </script> | ||
|
|
||
| <template> | ||
| <p>{{ user?.name ?? "No user has been added yet." }}</p> | ||
| </template> | ||
| ``` | ||
|
|
||
| :::note | ||
| We're extending the `usePrismaClient()` composable with the `withAccelerate()` extension method to ensure [compatibility with Prisma Postgres](/postgres/introduction/overview#using-the-client-extension-for-prisma-accelerate-required). This extension will also allow you to [cache your queries](/postgres/database/caching). | ||
| ::: | ||
|
|
||
| 3. Modify the `app.vue` file in the root directory to include the new server component using Nuxt Islands: | ||
| ```html file=app.vue | ||
|
|
@@ -198,7 +169,93 @@ With Prisma configured, the next step is to update your application code to fetc | |
|
|
||
| By completing these steps, your application is now capable of fetching data from your Prisma database and rendering it on the frontend. | ||
|
|
||
| ## 5. Create a Prisma Postgres instance | ||
| ## 5. Seed your database (optional) | ||
|
|
||
| If you want sample data, create a `prisma/seed.ts` file. The following script uses the PostgreSQL adapter: | ||
|
|
||
| ```ts file=prisma/seed.ts | ||
| import 'dotenv/config' | ||
| import { PrismaClient } from './generated/client' | ||
| 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.`) | ||
| } | ||
|
|
||
| main() | ||
| .then(async () => { | ||
| await prisma.$disconnect() | ||
| }) | ||
| .catch(async (e) => { | ||
| console.error(e) | ||
| await prisma.$disconnect() | ||
| process.exit(1) | ||
| }) | ||
| ``` | ||
|
|
||
| Run the seed command whenever you need demo data: | ||
|
|
||
| ```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. | ||
|
|
||
|
|
@@ -223,7 +280,7 @@ DATABASE_URL=<your-database-url> | |
|
|
||
| The `DATABASE_URL` environment variable will be required in the next steps. | ||
|
|
||
| ## 6. Set up Prisma Postgres in your Nuxt app | ||
| ## 7. Set up Prisma Postgres in your Nuxt app | ||
|
|
||
| Now that the Prisma Postgres instance is ready, update your Nuxt application to use this database: | ||
|
|
||
|
|
@@ -233,28 +290,23 @@ Now that the Prisma Postgres instance is ready, update your Nuxt application to | |
| DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=PRISMA_POSTGRES_API_KEY" | ||
| ``` | ||
|
|
||
| 2. Modify the `schema.prisma` file by changing the database provider in the `datasource` block of the `schema.prisma` file located in the `prisma` folder: | ||
| ```prisma file=prisma/schema.prisma | ||
| datasource db { | ||
| // edit-next-line | ||
| provider = "postgresql" | ||
| } | ||
| ``` | ||
| 3. Delete the SQLite database files (`dev.db` and `dev.db-journal`) along with the `migrations` folder, all located in the `prisma` directory. This cleans up the existing SQLite setup and prepares your project to migrate to PostgreSQL. | ||
| 4. Manually create a new migration for the Postgres database by running the `prisma migrate` command: | ||
| 2. Manually run a migration to sync your schema to Prisma Postgres: | ||
| ```terminal | ||
| npx prisma migrate dev --name init | ||
| ``` | ||
| 5. Start the development server again: | ||
| 3. (Optional) Seed your database with sample data: | ||
| ```terminal | ||
| npx prisma db seed | ||
| ``` | ||
| 4. Start the development server again: | ||
| ```terminal | ||
| npm run dev | ||
| ``` | ||
| 6. Open the Nuxt DevTools (by hitting <kbd>Shift</kbd>+<kbd>Option</kbd>+ <kbd>D</kbd>) and click the Prisma logo in the left sidenav to open Prisma Studio. Then add a new `User` record by specifying values for the `name` and `email` fields. | ||
| 7. Verify the data in the application by refreshing your application at `https://localhost:3000`. The page should display the name of the user you added in Prisma Studio. For example, if you added a user named `Jon`, the application will display `Jon` in the browser. | ||
| 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! | ||
|
|
||
| ## 7. Deploy to Vercel | ||
| ## 8. Deploy to Vercel | ||
|
|
||
| Deploy your Nuxt application with Prisma Postgres integration to Vercel by following these steps: | ||
|
|
||
|
|
@@ -295,4 +347,4 @@ Congratulations! Your Nuxt application with Prisma Postgres integration is now l | |
|
|
||
| ## Considerations | ||
|
|
||
| This guide helps you get started with Prisma Postgres using the Nuxt module. Because the Nuxt module is actively evolving, it does not cover all of Prisma's features or support every edge case. For more advanced functionality or edge deployments, consider using Prisma directly. | ||
| 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. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.