DEV Community

Cover image for How to Build a Full-Stack Web App with Next.js, Prisma, and PostgreSQL
Raji moshood
Raji moshood

Posted on

How to Build a Full-Stack Web App with Next.js, Prisma, and PostgreSQL

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.

Nextjs
✔ Prisma – Simplifies database access with an intuitive TypeScript-based ORM.

Prisma orm
✔ PostgreSQL – A powerful, scalable, and reliable relational database.

postgressql

Setting Up the Project

Next prisma postgres

  1. Create a Next.js App

First, install Next.js with TypeScript:

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

Start the development server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 to see your Next.js app running.

Installing Prisma and PostgreSQL

  1. Install Prisma and PostgreSQL Client

Inside your project folder, install Prisma:

npm install @prisma/client @prisma/cli
Enter fullscreen mode Exit fullscreen mode

Install PostgreSQL if not already installed:

sudo apt update && sudo apt install postgresql postgresql-contrib
Enter fullscreen mode Exit fullscreen mode

Configuring PostgreSQL and Prisma

  1. Set Up PostgreSQL Database

Start PostgreSQL service:

sudo service postgresql start
Enter fullscreen mode Exit fullscreen mode

Access PostgreSQL CLI:

sudo -u postgres psql
Enter fullscreen mode Exit fullscreen mode

Create a database:

CREATE DATABASE myappdb;
Enter fullscreen mode Exit fullscreen mode
  1. Configure Prisma

Initialize Prisma in the Next.js project:

npx prisma init
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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())
}
Enter fullscreen mode Exit fullscreen mode
  1. Apply Database Migrations

Run the following to generate and apply the migration:

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

Implementing CRUD Operations in Next.js API Routes

  1. 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`);
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Deploying the App

  1. Preparing for Production

  2. Set environment variables (DATABASE_URL) in a .env.production file.

  3. Build the app:

npm run build
Enter fullscreen mode Exit fullscreen mode
  1. Start the app in production mode:
npm start
Enter fullscreen mode Exit fullscreen mode
  1. Deploying on Vercel

  2. Install Vercel CLI:

npm install -g vercel
Enter fullscreen mode Exit fullscreen mode
  1. Run deployment command:
vercel
Enter fullscreen mode Exit fullscreen mode

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.

Nextjs #Prisma #PostgreSQL #FullStack #WebDevelopment #Backend

Top comments (0)