0
0
NextJSframework~5 mins

Prisma ORM setup in NextJS

Choose your learning style9 modes available
Introduction

Prisma ORM helps you easily work with databases in your Next.js app. It turns database data into simple JavaScript objects you can use.

You want to save user data like names and emails in a database.
You need to read and show data from a database on your website.
You want to update or delete data safely without writing complex SQL.
You want to keep your database code clean and easy to understand.
Syntax
NextJS
npx prisma init

// Then edit prisma/schema.prisma to define your data models

// Generate Prisma client
npx prisma generate

// Use Prisma client in your Next.js code
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

npx prisma init creates the basic setup files.

You define your database tables as models in schema.prisma.

Examples
This defines a User table with id, name, and unique email.
NextJS
model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}
This fetches all users from the database.
NextJS
const users = await prisma.user.findMany()
This adds a new user to the database.
NextJS
const newUser = await prisma.user.create({
  data: { name: 'Anna', email: 'anna@example.com' }
})
Sample Program

This Next.js compatible code creates a user and then fetches all users from the database. It logs the results to the console.

NextJS
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // Create a new user
  const user = await prisma.user.create({
    data: {
      name: 'John Doe',
      email: 'john@example.com'
    }
  })

  // Fetch all users
  const allUsers = await prisma.user.findMany()

  console.log('Created user:', user)
  console.log('All users:', allUsers)
}

main()
  .catch(e => console.error(e))
  .finally(async () => {
    await prisma.$disconnect()
  })
OutputSuccess
Important Notes

Always run npx prisma generate after changing your schema.

Use environment variables to keep your database URL safe.

Disconnect Prisma client after use to avoid open connections.

Summary

Prisma ORM makes database work simple and safe in Next.js.

Define your data models in schema.prisma.

Use Prisma client to create, read, update, and delete data easily.