Introduction
Building a full-stack web application requires an efficient framework, a powerful database, and an ORM (Object-Relational Mapper) to connect them. Next.js, Prisma, and PostgreSQL form a modern tech stack that enables fast, scalable, and maintainable applications.
This guide walks through setting up a Next.js app, integrating it with PostgreSQL using Prisma, and implementing CRUD operations.
Why Use Next.js, Prisma, and PostgreSQL?
✔ Next.js – Provides server-side rendering (SSR), static site generation (SSG), API routes, and seamless front-end integration.
✔ Prisma – Simplifies database access with an intuitive TypeScript-based ORM.
✔ PostgreSQL – A powerful, scalable, and reliable relational database.
Setting Up the Project
- Create a Next.js App
First, install Next.js with TypeScript:
npx create-next-app@latest myapp --typescript
cd myapp
Start the development server:
npm run dev
Visit http://localhost:3000 to see your Next.js app running.
Installing Prisma and PostgreSQL
- Install Prisma and PostgreSQL Client
Inside your project folder, install Prisma:
npm install @prisma/client @prisma/cli
Install PostgreSQL if not already installed:
sudo apt update && sudo apt install postgresql postgresql-contrib
Configuring PostgreSQL and Prisma
- Set Up PostgreSQL Database
Start PostgreSQL service:
sudo service postgresql start
Access PostgreSQL CLI:
sudo -u postgres psql
Create a database:
CREATE DATABASE myappdb;
- Configure Prisma
Initialize Prisma in the Next.js project:
npx prisma init
This creates a .env file and a prisma/schema.prisma file.
Update .env with your PostgreSQL database URL:
DATABASE_URL="postgresql://postgres:password@localhost:5432/myappdb"
Update prisma/schema.prisma to define a User model:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}
- Apply Database Migrations
Run the following to generate and apply the migration:
npx prisma migrate dev --name init
Implementing CRUD Operations in Next.js API Routes
- Create a User API
Inside the pages/api folder, create a new file users.ts:
import { PrismaClient } from '@prisma/client';
import { NextApiRequest, NextApiResponse } from 'next';
const prisma = new PrismaClient();
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
const users = await prisma.user.findMany();
res.status(200).json(users);
}
else if (req.method === 'POST') {
const { name, email } = req.body;
const user = await prisma.user.create({
data: { name, email },
});
res.status(201).json(user);
}
else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
- Create a React Frontend for Displaying Users
Modify pages/index.tsx to fetch and display users:
import { useEffect, useState } from 'react';
interface User {
id: number;
name: string;
email: string;
}
export default function Home() {
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
fetch('/api/users')
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
return (
<div>
<h1>User List</h1>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
</div>
);
}
Deploying the App
Preparing for Production
Set environment variables (DATABASE_URL) in a .env.production file.
Build the app:
npm run build
- Start the app in production mode:
npm start
Deploying on Vercel
Install Vercel CLI:
npm install -g vercel
- Run deployment command:
vercel
Conclusion
By following this guide, you've built a full-stack web application using Next.js, Prisma, and PostgreSQL.
✔ Next.js provides frontend and API support.
✔ Prisma simplifies database interactions.
✔ PostgreSQL ensures robust data management.
This setup is scalable, efficient, and ready for production.
I am open to collaboration on projects and work. Let's transform ideas into digital reality.
Top comments (0)