Prisma with Postgres in NEXT.JS

Prisma with Postgres in NEXT.JS

August 3, 2024

Next.JS can be used as fullstack application and it is obvious that a full-stack application must use database. In this blog we will see how we can set up postgresql with Prisma in Next.JS application.

Next.JS can be used as fullstack application and it is obvious that a full-stack application must use database. In this blog we will see how we can set up postgresql with Prisma in Next.JS application.

Set up Next.JS application and configure it by reading this blog

After you have setup your application. Let's follow the gien steps to set up our postgresql database with NEXT.JS

  1. Install prisma and prisma client
yarn add -D prisma
yarn add @prisma/client
  1. Init prisma in your project
npx prisma init --datasource-provider postgresql

Above command will auto generate a schema.prisma file under prisma directory and a .env file which looks like this

  • schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
  relationMode = "prisma" // Add this line if you want to use this mode 
}
  • .env
// Update the DATABASE_URL as per your need

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
  1. Create db.ts file inside lib directory and update the content given below
import { PrismaClient } from '@prisma/client';

declare global {
  var prisma: PrismaClient | undefined;
}

export const db = globalThis.prisma || new PrismaClient();

if (process.env.NODE_ENV !== 'production') globalThis.prisma = db;
  1. Define models inside your schema.prisma file
model User {
  id             String   @id @default(uuid())
  email          String   @unique
  username       String   @unique
  password       String
  firstName      String?
  lastName       String?
  profilePicture String
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt

  @@index([email])
  @@index([username])
  @@map("users")
}
  1. Generate schema by running given command
npx prisma generate
  1. Create tables in your database by running given command
npx prisma db push
  1. Use the given command to open prisma studio in browser
npx prisma studio
  1. This is how you can use db either in server actions or inside api route
const dbUser = await db.user.findUnique({
  where: {
    clerkId: user.id,
  },
});

Additional steps

If you want to deploy your project on vercel, some configurations need to be done else it will fail at build time. Simply update scripts inside package.json

"scripts": {
  // other scripts

  "postinstall": "prisma generate", // Add this script
  "build": "prisma generate && next build", // Update this script
  
  // other scripts
}

You are now good to go using prisma in your NEXT.JS application.

Leave a comment