#nextjs #prisma #database #postgres

Day 23 β€” Database: Setting up Prisma

🧭 Day 23 β€” Database: Setting up Prisma

Zero to Hero β€” Hands-on Next.js Tutorial

We have Authentication. Now we need to save user data. We will use Prisma, the best ORM for TypeScript. It pairs perfectly with Next.js Server Components.


🟦 1. Basic Setup

npm install prisma --save-dev
npm install @prisma/client
npx prisma init

This creates a prisma/schema.prisma file.


🟩 2. Defining the Schema

Let’s model a basic Blog.

// prisma/schema.prisma

datasource db {
  provider = "sqlite" // Use postgres/mysql for production
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

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
}

Run the migration to create the DB file:

npx prisma migrate dev --name init

🟧 3. The Helper Client

To use Prisma in Next.js (especially in dev with hot reload), we need a singleton instance. Create lib/prisma.ts:

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

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma = globalForPrisma.prisma || new PrismaClient();

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

πŸŸ₯ 4. Using it in a Server Component

Now, fetching data is just a function call.

import { prisma } from '@/lib/prisma';

export default async function Page() {
  const users = await prisma.user.findMany({
    include: { posts: true }, // Join the posts table!
  });

  return <pre>{JSON.stringify(users, null, 2)}</pre>;
}

πŸ§ͺ Challenge: Day 23

  1. Set up Prisma with SQLite (easiest for local dev).
  2. Define a Todo model (id, title, done).
  3. Run the migration.
  4. Open Prisma Studio (npx prisma studio) to manually add a Todo item.
  5. Fetch and display it in page.tsx.

See you tomorrow for Full Stack CRUD! πŸ“