Skip to content
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

enhance: add clarity and configuration options (#DA-359) #6107

Merged
merged 12 commits into from
Jun 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,28 @@ metaDescription: 'Learn how to easily add Prisma ORM to your Nuxt apps, use its

---

The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt applications. This module provides several features to streamline the setup and usage of Prisma, making it easier to manage your database interactions.
The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt applications.

### Features
[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.

## 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 `prisma` for use in your API routes.
- **Prisma Studio access**: Enables access to Prisma Studio through Nuxt Devtools for database management.
- **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
## Getting started

1. Create a [new Nuxt Project](https://nuxt.com/docs/getting-started/installation#new-project):
```sh
```terminal
npx nuxi@latest init test-nuxt-app
```

2. Navigate to project directory and install `@prisma/nuxt`:
```sh
```terminal
cd test-nuxt-app
npm install @prisma/nuxt
```
Expand All @@ -37,21 +41,136 @@ The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt a
```

4. Start the development server:
```sh
```terminal
npm run dev
```

Starting the development server will:

- Automatically install the [Prisma CLI](/orm/reference/prisma-cli-reference)
- Initialize a Prisma project with SQLite
- Create an `User` and `Post` example model in the Prisma Schema
- Prompt you to run a migration to create database tables with [Prisma Migrate](/orm/prisma-migrate/understanding-prisma-migrate/overview)
- Install and generate a [Prisma Client](/orm/reference/prisma-client-reference)
- Prompt you to start the [Prisma Studio](/orm/tools/prisma-studio)
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-js"
}

datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}

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)
<Admonition type="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.
</Admonition>
ankur-arch marked this conversation as resolved.
Show resolved Hide resolved
5. Install and generate a [Prisma Client](/orm/reference/prisma-client-reference) which enables you to query your DB
6. Prompt you to start the [Prisma Studio](/orm/tools/prisma-studio)

5. 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-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

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
Expand Down Expand Up @@ -84,7 +203,7 @@ export default defineEventHandler(async (event) => {
### 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
```typescript file=lib/prisma.ts
import { PrismaClient } from '@prisma/client'

const prismaClientSingleton = () => {
Expand All @@ -103,7 +222,7 @@ 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 [Pulse client extension](https://www.npmjs.com/package/@prisma/extension-pulse):
```typescript
```typescript file=lib/prisma.ts
import { PrismaClient } from '@prisma/client'
import { withPulse } from '@prisma/extension-pulse'

Expand Down Expand Up @@ -149,4 +268,40 @@ If you're using [Nuxt server components](https://nuxt.com/docs/guide/directory-s
<template>
<p>{{ user.name }}</p>
</template>
```
```

## 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
}
})
```
<br />
<Admonition type="note">
The `prisma` key is available in `nuxt.config.ts` after successfully setting up the module by running `npm run dev`
</Admonition>

| 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. |

## 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) or [GitHub](https://github.com/prisma/nuxt-prisma).
Loading