Using the Nuxt Prisma Module
The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt applications.
Prisma ORM 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 PrismaClientfor 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
- 
Create a new Nuxt Project: npm create nuxt test-nuxt-app
- 
Navigate to project directory and install @prisma/nuxtusing the Nuxt CLI:cd test-nuxt-app
 npx nuxi@latest module add @prisma/nuxt
 warningIf you're using pnpm, make sure to hoist Prisma dependencies. Follow the Prisma studio steps for detailed instructions.
- 
Start the development server: npm run devStarting the development server will: - Automatically install the Prisma CLI
- Initialize a Prisma project with SQLite
- Create an UserandPostexample model in the Prisma Schema 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
 }
- Prompt you to run a migration to create database tables with Prisma Migrate
noteThe database migrates automatically the first time you start the module if there isn't a migrationsfolder. After that, you need to runnpx prisma migrate devmanually in the CLI to apply any schema changes. Running thenpx prisma migrate devcommand manually makes it easier and safer to manage migrations and also to troubleshoot any migration-related errors.
- Install and generate a Prisma Client which enables you to query your DB
- Automatically start Prisma Studio
 
- 
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 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. You can configure the getting started example to use a database of your choice. The steps would be different for a database without existing data and a database with pre-existing data.
Using a database without existing data
To configure the getting started example to use a PostgreSQL database without any existing data:
- Stop the Nuxt development server and Prisma Studio (if they are still running):
npx kill-port 3000 # Stops Nuxt dev server (default port)
 npx kill-port 5555 # Stops Prisma Studio (default port)
- Navigate to the schema.prismafile and update thedatasourceblock to specify thepostgresqlprovider: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
 }
- Update the DATABASE_URLenvironment variable in the.envfile with your PostgreSQL database URL:.env## This is a sample database URL, please use a valid URL
 DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample"
- Delete the SQLite database file and the migrations folder:
rm prisma/dev.db # Delete SQLite database file
 rm -r prisma/migrations # Delete the pre-existing migrations folder
- Run the development server:
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.npm run dev
- The @prisma/nuxtmodule is ready to use with your PostgreSQL database. See the usage section to learn how to use Prisma Client in your app.
Using a database with pre-existing data
To configure the getting started example to use a PostgreSQL database that already has data in it:
- Stop the dev server and Prisma Studio (if they are still running):
// 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
- Delete the Prisma folder:
rm -r prisma/
- Update the DATABASE_URLenvironment variable in the.envfile with your PostgreSQL database URL:.env## This is a sample database URL, please use a valid URL
 DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample"
- To generate a Prisma Schema and migrations folder from the existing database, you have to introspect the database. Complete step 1 to step 4 from the introspection guide and continue.
- 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.
- The @prisma/nuxtmodule is ready to be used with your PostgreSQL database. See the usage section 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, you can use the global instance of the Prisma Client in your .server.vue files:
<script setup>
  const prisma = usePrismaClient()
  const user = await prisma.user.findFirst()
</script>
<template>
  <p>{{ user.name }}</p>
</template>
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.
import { PrismaClient } from '@prisma/client'
const prismaClientSingleton = () => {
  return new PrismaClient()
}
declare const globalThis: {
  prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & 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:
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'
const prismaClientSingleton = () => {
  return new PrismaClient().$extends(withAccelerate())
}
declare const globalThis: {
  prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma
Use the prisma instance from the lib folder if you want to leverage a client using Prisma 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:
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, you can use the global instance of the Prisma Client .server.vue files:
<script setup>
  import prisma from '~/lib/prisma';
  const user = await prisma.user.findFirst()
</script>
<template>
  <p>{{ user.name }}</p>
</template>
Configuration
You can configure the @prisma/nuxt module by using the prisma key in nuxt.config.ts:
export default defineNuxtConfig({
  // ...
  prisma: {
    // Options
  }
})
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. | 
| installClient | boolean | true | Whether to install the Prisma Client library in the project. | 
| generateClient | boolean | true | Whether to generate the PrismaClientinstance. Executesnpx prisma generateon every run to update the client based on the schema changes. | 
| formatSchema | boolean | true | Whether to format the Prisma Schema file. | 
| installStudio | boolean | true | Whether to install and start Prisma 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. For example, if you have a Nuxt layer called database, theprismaRootwould be./databasein the base nuxt config. This refers to the folder where Prisma will be initialized or checked. | 
| prismaSchemaPath | string | undefined | Required when using Nuxt layers. For example, if you have a Nuxt layer called database, theprismaSchemaPathwould be./database/prisma/schema.prismain 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 pushcommand. 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.
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 or GitHub.
Troubleshooting
Prisma Studio not opening with pnpm
If you're encountering the following error when using pnpm and Prisma Studio isn't opening:
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:
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:
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.
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
generator client {
  provider = "prisma-client-js"
}
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.
Stay connected with Prisma
Continue your Prisma journey by connecting with  our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.