Next.js

ORM Integration

Setting up Prisma ORM to interact with the database efficiently in Next.js.

Installation & Init: Install Prisma and initialize it.
📄terminal
BASH
npm install prisma --save-dev
npx prisma init

# After setting up schema:
# npx prisma migrate dev --name init
# npm install @prisma/client
Prisma Schema: Define models in the schema file.
📄prisma/schema.prisma
PRISMA
generator client {
  provider = "prisma-client-js"
}

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

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
Prisma Client Singleton: Instantiate Prisma Client safely for Next.js hot reloading.
📄lib/prisma.ts
TS
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
Using Prisma: Fetching records in a Server Component.
📄app/posts/page.tsx
TSX
import prisma from '@/lib/prisma'

export default async function PostsPage() {
  const posts = await prisma.post.findMany({
    where: { published: true },
    orderBy: { createdAt: 'desc' }
  })

  return (
    <div>
      <h1>Published Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  )
}