Prisma ORM

Learn how to setup Prisma ORM with NuxtHub.
This ORM is not fully compatible with NuxtHub yet.
Learn more about Prisma ORM.

Setup

To enhance your Developer Experience with the database, we can use the nuxt-prisma module with a few steps.

1. Install Prisma

Install the @prisma/nuxt and @prisma/adapter-d1 packages to your project:

pnpm add @prisma/nuxt @prisma/adapter-d1

2. Init Prisma

Add @prisma/nuxt to the modules section of nuxt.config.ts

export default defineNuxtConfig({
  modules: ["@prisma/nuxt"],
});

To generate needed directories and files, run this command:

```bash
npx prisma init --datasource-provider sqlite

Now you have .prisma/schema.prisma in your project, make it match this config:

schema.prisma
generator client {
  provider = "prisma-client-js"
  // preview feature enabling binding adapter
  previewFeatures = ["driverAdapters"]
}

datasource db {
  provider = "sqlite"
  // url is required but won't be used
  url = env("DATABASE_URL")
}
No need to define DATABASE_URL in your .env file, it won't be used.

Create Models

Your models are defined in the same file as the rest of Prisma config, schema.prisma. Let's add a model:

schema.prisma
model Todos {
  id         Int       @id @default(autoincrement())
  title      String
  completed  Boolean   @default(false)
  createdAt  DateTime  @default(now())
}
Prisma's documentation is a great resource to learn how to create the models you need.

4. Generate Prisma Client

Run this command to generate Prisma client:

npx prisma generate
Don't forget to run this command each time you update your schema.prisma file.

Example

The nuxt-prisma-nuxt-module example shows how @prisma/nuxt is used.

5. Migrations

Prisma Migrate does not fully support migrations with D1, but it is possible. See the link for a full guide.

Usage

Select

server/api/todos/index.get.ts
export default eventHandler(async () => {
  const todos = await usePrismaClient().todos.findMany()

  return todos
})

Insert

server/api/todos/index.post.ts
export default eventHandler(async (event) => {
  const { title } = await readBody(event)

  const todo = await usePrismaClient().todos.create({
    data: {
      title,
      createdAt: new Date()
    }
  })

  return todo
})

Update

server/api/todos/[id
export default eventHandler(async (event) => {
  const { id } = getRouterParams(event)
  const { completed } = await readBody(event)

  const todo = await usePrismaClient().todos.update({
    where: {
      id: Number(id)
    },
    data: {
      completed
    }
  })

  return todo
})

Delete

server/api/todos/[id
export default eventHandler(async (event) => {
  const { id } = getRouterParams(event)

  const deletedTodo = await usePrismaClient().todos.delete({
    where: {
      id: Number(id)
    }
  })

  if (!deletedTodo) {
    throw createError({
      statusCode: 404,
      message: 'Todo not found'
    })
  }
  return deletedTodo
})