DEV Community

Mihir Bhadak
Mihir Bhadak

Posted on

Using Prisma ORM with Next.js 15, TypeScript, and PostgreSQL

Introduction

Prisma ORM is a powerful and type-safe database toolkit for Node.js and TypeScript. It simplifies database access and management, making it a great choice for Next.js applications. This guide will walk you through setting up Prisma with Next.js 15, TypeScript, and a PostgreSQL database.

Prerequisites

Ensure you have the following installed:

  • Node.js (v16+)
  • PostgreSQL
  • npm or yarn

Step 1: Setting Up Next.js 15 Project

First, create a new Next.js 15 project with TypeScript:

npx create-next-app@latest my-prisma-app --typescript
cd my-prisma-app
Enter fullscreen mode Exit fullscreen mode

Step 2: Installing Prisma and PostgreSQL Driver

Install Prisma and the PostgreSQL client library:

npm install @prisma/client
npm install --save-dev prisma
npm install pg
Enter fullscreen mode Exit fullscreen mode

Step 3: Initializing Prisma

Run the following command to initialize Prisma:

npx prisma init
Enter fullscreen mode Exit fullscreen mode

This command:

  • Creates a prisma directory with a schema.prisma file
  • Generates an .env file for database configuration

Step 4: Configuring PostgreSQL Connection

In the .env file, update the database URL:

DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/DATABASE_NAME"
Enter fullscreen mode Exit fullscreen mode

Replace USER, PASSWORD, and DATABASE_NAME with your PostgreSQL credentials.

Step 5: Defining the Prisma Schema

Edit prisma/schema.prisma to define a model:

model User {
  id    String @id @default(uuid())
  name  String
  email String @unique
  posts Post[]
}

model Post {
  id        String @id @default(uuid())
  title     String
  content   String?
  author    User   @relation(fields: [authorId], references: [id])
  authorId  String
  createdAt DateTime @default(now())
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Running Migrations

Generate and apply migrations:

npx prisma migrate dev --name init
Enter fullscreen mode Exit fullscreen mode

This will create the database tables.

Step 7: Generating Prisma Client

Run the following command to generate the Prisma Client:

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

This command creates TypeScript types for your database models.

Step 8: Using Prisma in Next.js API Route

Create an API route in pages/api/users.ts:

import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    const users = await prisma.user.findMany();
    return res.status(200).json(users);
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 9: Seeding the Database (Optional)

Add a prisma/seed.ts file:

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

const prisma = new PrismaClient();

async function main() {
  await prisma.user.create({
    data: {
      name: 'John Doe',
      email: 'johndoe@example.com',
    },
  });
}

main()
  .catch((e) => console.error(e))
  .finally(async () => await prisma.$disconnect());
Enter fullscreen mode Exit fullscreen mode

Run the seed command:

npx prisma db seed
Enter fullscreen mode Exit fullscreen mode

Step 10: Prisma Studio (GUI for DB Management)

Launch Prisma Studio:

npx prisma studio
Enter fullscreen mode Exit fullscreen mode

This opens a web interface to interact with your database.

List of Prisma Commands

Command Description
npx prisma init Initializes Prisma in the project.
npx prisma migrate dev --name init Creates and applies a new migration.
npx prisma generate Generates the Prisma client for TypeScript.
npx prisma studio Opens Prisma Studio for database management.
npx prisma db seed Runs the seed script to populate the database.
npx prisma migrate status Shows the current migration status.
npx prisma format Formats the Prisma schema file.
npx prisma validate Validates the Prisma schema file.

Conclusion

You have successfully set up Prisma ORM with Next.js 15, TypeScript, and PostgreSQL. This setup allows you to interact with your database using a fully typed API, making development more efficient and secure.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs