Back to blog
Mar 15, 2025
6 min read

How to Connect a Next.js App to a PostgreSQL Database Using Prisma

Learn how to integrate a PostgreSQL database with a Next.js application using Prisma ORM for efficient data management and API queries.

How to Connect a Next.js App to a PostgreSQL Database Using Prisma

Next.js is a powerful React framework for building web applications, and PostgreSQL is a reliable relational database for storing structured data. Prisma ORM simplifies database interactions by providing a type-safe and scalable way to query PostgreSQL.

This guide will walk you through: ✔ Setting up Prisma with PostgreSQLCreating and migrating database schemasPerforming database queries in Next.js API routesDeploying a Next.js app with PostgreSQL


1. Why Use Prisma with Next.js?

Prisma is a modern database toolkit that enhances database management in Next.js and Node.js applications.

Advantages of Using Prisma

Type Safety → Autogenerated TypeScript types ensure safe queries. ✔ Simplified Database Access → Provides an easy-to-use API for PostgreSQL. ✔ Automatic Migrations → Manage database schema changes effortlessly. ✔ Works with Next.js API Routes → Ideal for full-stack applications.

Prisma is an excellent alternative to SQL queries or traditional ORMs like Sequelize.


2. Installing PostgreSQL and Prisma

A. Setting Up PostgreSQL

If PostgreSQL is not installed, download it from postgresql.org.

To start a local PostgreSQL instance:

sudo service postgresql start# (Linux/macOS)

Check if PostgreSQL is running:

psql -U postgres -c "SELECT version();"

Create a new database:

psql -U postgres
CREATE DATABASE mynextjsapp;

B. Installing Prisma in Next.js

  1. Navigate to your Next.js project:
cd my-nextjs-app
  1. Install Prisma and PostgreSQL client:
npm install @prisma/client @prisma/cli pg
  1. Initialize Prisma:
npx prisma init

This creates a prisma/schema.prisma file.


3. Configuring Prisma for PostgreSQL

Open the .env file and add your PostgreSQL connection string:

DATABASE_URL="postgresql://postgres:password@localhost:5432/mynextjsapp"

Then, update the Prisma schema (prisma/schema.prisma):

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

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

model User {
idInt @id @default(autoincrement())
nameString
email String@unique
age Int
}

Run Prisma migration to create the database table:

npx prisma migrate dev --name init

Now, Prisma has generated the database schema.


4. Using Prisma in Next.js API Routes

A. Creating a User in the Database

Create an API route in pages/api/user.js:

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

const prisma = new PrismaClient();

export default async function handler(req, res) {
if (req.method === "POST") {
const { name, email, age } = req.body;

try {
const user = await prisma.user.create({
data: { name, email, age }
});
res.status(200).json(user);
} catch (error) {
res.status(400).json({ error: "User could not be created" });
}
}
}

B. Fetching All Users

Modify the API route:

export default async function handler(req, res) {
if (req.method === "GET") {
const users = await prisma.user.findMany();
res.status(200).json(users);
}
}

C. Updating a User

export default async function handler(req, res) {
if (req.method === "PUT") {
const { id, name, email, age } = req.body;
const updatedUser = await prisma.user.update({
where: { id },
data: { name, email, age }
});
res.status(200).json(updatedUser);
}
}

D. Deleting a User

export default async function handler(req, res) {
if (req.method === "DELETE") {
const { id } = req.body;
await prisma.user.delete({ where: { id } });
res.status(200).json({ message: "User deleted" });
}
}

Now, you can create, read, update, and delete users using Next.js API routes.


5. Running and Testing the API

Start your Next.js development server:

npm run dev

Test API routes using Postman, Curl, or Next.js fetch().

MethodRouteDescription
POST/api/userCreate a new user
GET/api/userGet all users
PUT/api/userUpdate a user
DELETE/api/userDelete a user

6. Deploying a Next.js App with PostgreSQL

A. Hosting the Database on Supabase

  1. Create a free PostgreSQL database on Supabase.
  2. Copy the connection string and update the .env file:
DATABASE_URL="postgresql://username:password@db.supabase.io:5432/database_name"

B. Deploying to Vercel

  1. Install Vercel CLI:
npm install -g vercel
  1. Deploy the project:
vercel deploy

Vercel will deploy your Next.js app with the database configuration.


7. Prisma vs. Other ORMs

FeaturePrismaSequelizeTypeORM
Type Safety✅ Yes❌ No✅ Yes
Ease of Use✅ Yes❌ Requires SQL knowledge✅ Yes
Auto Migrations✅ Yes❌ No✅ Yes
Performance✅ Fast⚠️ Moderate⚠️ Moderate

Prisma is faster and more developer-friendly than traditional ORMs.


8. Common Prisma Issues and Fixes

IssueSolution
Prisma not connectingCheck .env database URL
Migrations not applyingRun npx prisma migrate reset
API not updatingRestart server with npm run dev

Prisma’s developer-friendly error messages make debugging easier.


Conclusion

Prisma makes database management in Next.js apps simple and efficient. By integrating with PostgreSQL, developers can create scalable, type-safe applications with minimal effort.

Key Takeaways

Prisma simplifies database interactions with PostgreSQL.Next.js API routes allow seamless data handling.Prisma migrations ensure schema consistency.Deploying with Supabase and Vercel makes it production-ready.

Start building full-stack Next.js applications with PostgreSQL and Prisma today! 🚀


Disclaimer

Article written with the help of AI.

This blog post is for informational purposes only and is not affiliated with or endorsed by any mentioned company. References are for discussion, not promotion. Some information may be inaccurate, readers should verify independently before making decisions.