EthicsComputerCourses
Join training +91 90532 10052

Database with Prisma & PostgreSQL

Next.js Full Stack · Lesson 5 of 20 Intermediate 14 min read Updated

By the end of this lesson EventHub will read its meetups from a real PostgreSQL database. You will describe the tables in a Prisma schema, create them with a migration, fill them with a seed script, and replace the sample data in lib/events.ts with typed Prisma queries, without changing a single page. You will also see, in the SQL Prisma sends, why its queries are safe from SQL injection.

What you should know first: Server Components & Data Fetching, basic SQL tables and keys (Constraints & Keys) and how apps connect to PostgreSQL (Connect from Python, Node.js & PHP). For a local server, see Install PostgreSQL. Versions checked on 16 November 2026: Prisma ORM 7.10.1, @prisma/adapter-pg 7.10.1 and Next.js 16.4.6.

What Prisma adds

An ORM (Object-Relational Mapper) lets you work with database rows as objects in your language. Prisma has three parts:

  • The schema (prisma/schema.prisma): one readable file that describes your tables, columns and relations.
  • Migrate: turns schema changes into SQL migration files, which are numbered scripts that move the database from one version to the next. They go into Git, so every teammate and server gets the same tables.
  • Prisma Client: generated TypeScript code with methods such as db.event.findMany(). TypeScript knows every column, so a typo such as event.titel fails before you run anything.

Think of the reservation chart pasted on a train coach. The railway's rules decide what a chart may contain: coach, berth, name, age. Prisma's schema is those rules, the migration is printing a new chart format, and Prisma Client is the TTE who reads and updates the chart for you, always in the official format.

Step 1: Install the packages (and avoid a trap)

On 16 November 2026, npm's latest tag for the prisma command-line package pointed to 8.0.0-rc.33, a release candidate, while @prisma/client was at 7.10.1. A plain npm install prisma would mix versions. Pin all Prisma packages to the same stable version:

Terminal
npm install prisma@7.10.1 tsx --save-dev
npm install @prisma/client@7.10.1 @prisma/adapter-pg@7.10.1 dotenv

prisma is the command-line tool. tsx runs TypeScript files such as the seed script. @prisma/client is the runtime. @prisma/adapter-pg is a driver adapter: since Prisma 7, Prisma Client talks to PostgreSQL through the standard pg driver instead of its old Rust query engine. dotenv lets the Prisma tool read your .env file.

Step 2: Initialise Prisma

Terminal
npx prisma init --no-skills
Output
Initialized Prisma in your project

  prisma/
    schema.prisma
  prisma7.config.ts
  .env

warn You already have a .gitignore file. Don't forget to add .env in it to not commit any private information.

Next, choose how you want to set up your database:

CONNECT EXISTING DATABASE:
  1. Configure your DATABASE_URL in prisma7.config.ts
  2. Run prisma db pull to introspect your database.

CREATE NEW DATABASE:
  Local: npx prisma dev (runs Postgres locally in your terminal)
  Cloud: npx create-db (creates a free Prisma Postgres database)

Then, define your models in prisma/schema.prisma and run prisma migrate dev to apply your schema.

Learn more: https://pris.ly/getting-started

Without --no-skills, prisma init also copies instruction files for AI coding tools into .claude/, .agents/ and .windsurf/ folders. EventHub does not need them. The tool also added /lib/generated/prisma to .gitignore, because generated code is rebuilt, not committed. Your .env is already ignored from the setup lesson.

Notice the config file name: Prisma 7.10 writes prisma7.config.ts. Older Prisma 7 releases and most tutorials use prisma.config.ts; 7.10 still finds that name too. Open it and add the seed command:

TypeScript
import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
    seed: "tsx prisma/seed.ts",
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});

The connection string lives in the config file now, not in schema.prisma.

Step 3: Get a PostgreSQL database

Option A: PostgreSQL on your computer. Install PostgreSQL 18, then create a database and a login for the app in psql. Use your own strong password:

PostgreSQL
CREATE ROLE eventhub_app LOGIN PASSWORD 'use-a-long-random-password';
CREATE DATABASE eventhub OWNER eventhub_app;

Option B: Prisma's local development database. Run this in a second terminal and leave it running:

Terminal
npx prisma dev --name eventhub
Output
√  Your local Prisma Postgres server eventhub is now running

   DATABASE_URL="postgres://postgres:postgres@localhost:51218/template1?sslmode=disable&connection_limit=10&connect_timeout=0&max_idle_connection_lifetime=0&pool_timeout=0&socket_timeout=0"

That output is shortened to the important lines; the real one also prints a shadow database URL and a streams URL. --name keeps this project's data separate from other projects, and the port numbers depend on what is free on your computer. prisma dev runs PGlite, PostgreSQL compiled to WebAssembly, inside Node.js. Our copy reported PostgreSQL 17.5 from SELECT version(). It needs no installer, which makes it perfect for learning, but it is for development only.

This course's lessons were tested with Option B. The schema uses only standard PostgreSQL features, so it works unchanged on PostgreSQL 18 in production. Put the URL you got into .env:

Terminal
DATABASE_URL="postgres://postgres:postgres@localhost:51218/template1?sslmode=disable"

For Option A it would be postgresql://eventhub_app:your-password@localhost:5432/eventhub. The .env.example file from the setup lesson already shows that format.

Step 4: Describe the tables

Replace prisma/schema.prisma:

Text
generator client {
  provider = "prisma-client"
  output   = "../lib/generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model User {
  id        String   @id @default(cuid())
  name      String?
  email     String   @unique
  createdAt DateTime @default(now())
  organised Event[]
  rsvps     Rsvp[]
}

model Event {
  id           String   @id @default(cuid())
  slug         String   @unique
  title        String
  description  String
  city         String
  venue        String
  startsAt     DateTime
  capacity     Int
  priceInPaise Int      @default(0)
  organiserId  String
  organiser    User     @relation(fields: [organiserId], references: [id])
  rsvps        Rsvp[]
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@index([city, startsAt])
}

model Rsvp {
  id        String     @id @default(cuid())
  status    RsvpStatus @default(GOING)
  eventId   String
  event     Event      @relation(fields: [eventId], references: [id], onDelete: Cascade)
  userId    String
  user      User       @relation(fields: [userId], references: [id], onDelete: Cascade)
  createdAt DateTime   @default(now())

  @@unique([eventId, userId])
}

enum RsvpStatus {
  GOING
  WAITLIST
}

The design choices, each with a reason:

  • cuid() string ids are hard to guess, unlike 1, 2, 3, so nobody can walk through /rsvp/1, /rsvp/2 to count your members. Auth.js, used later in Authentication with Auth.js, also expects string user ids.
  • slug is @unique, so two meetups can never share a URL, and the lookup by slug uses an index.
  • @@unique([eventId, userId]) lets the database itself refuse a second RSVP from the same person. Rules in the database cannot be skipped by a buggy page.
  • @@index([city, startsAt]) speeds up the most common query: upcoming meetups in one city, by date.
  • onDelete: Cascade removes an event's RSVPs when the event is deleted. Deleting a user who organises events is blocked instead, because that relation has no cascade.
  • priceInPaise Int keeps money exact, and DateTime is stored in UTC.

Step 5: Migrate and generate

Terminal
npx prisma migrate dev --name init
Output
Loaded Prisma config from prisma7.config.ts.

Prisma schema loaded from prisma\schema.prisma.
Datasource "db": PostgreSQL database "template1", schema "public" at "localhost:51218"

Applying migration `20261116061320_init`

The following migration(s) have been created and applied from new schema changes:

prisma\migrations/
  └─ 20261116061320_init/
    └─ migration.sql

Your database is now in sync with your schema.

Open migration.sql and read it; it is ordinary SQL. A few of its lines:

SQL
CREATE TYPE "RsvpStatus" AS ENUM ('GOING', 'WAITLIST');
CREATE UNIQUE INDEX "Rsvp_eventId_userId_key" ON "Rsvp"("eventId", "userId");
ALTER TABLE "Rsvp" ADD CONSTRAINT "Rsvp_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;

In Prisma 7, migrate dev no longer generates the client for you. Run it yourself, now and after every schema change:

Terminal
npx prisma generate
Output
✔ Generated Prisma Client (7.10.1) to .\lib\generated\prisma in 290ms

Step 6: Seed some meetups

A seed script fills a fresh database with known data. Create prisma/seed.ts. It makes its own client, because a plain Node.js script cannot import lib/db.ts, which is marked server-only for Next.js:

TypeScript
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../lib/generated/prisma/client";

const db = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});

async function main() {
  const ananya = await db.user.upsert({
    where: { email: "ananya@example.com" },
    update: {},
    create: { name: "Ananya Sharma", email: "ananya@example.com" },
  });
  // also: a second user, Kabir; the three meetups from earlier lessons,
  // each created with db.event.upsert({ where: { slug }, ... organiserId: ananya.id });
  // and RSVPs from both users for the Rohtak meetup
  console.log(`Seeded ${await db.user.count()} users, ${await db.event.count()} events, ${await db.rsvp.count()} RSVPs`);
}

main()
  .catch((error) => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(() => db.$disconnect());
Terminal
npx prisma db seed
Output
Running seed command `tsx prisma/seed.ts` ...
Seeded 2 users, 3 events, 2 RSVPs

The seed command has been executed.

Upsert means "update if it exists, otherwise insert". Because every write is an upsert keyed on a unique field, you can run the seed twice and still get 2 users, not 4. We did, and the counts stayed the same.

Step 7: One shared client

Create lib/db.ts:

TypeScript
import "server-only";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/lib/generated/prisma/client";

function createClient() {
  const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
  return new PrismaClient({ adapter });
}

// Reuse one client during development, where hot reload re-runs this file.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

export const db = globalForPrisma.prisma ?? createClient();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db;

Each client keeps a connection pool, a few open connections that queries share. In development, Fast Refresh re-runs modules on every save. Without the globalThis trick, each save would open a new pool until PostgreSQL refuses more connections.

Step 8: Swap the data layer

Now the payoff. Replace lib/events.ts; the function names and return shapes stay the same:

TypeScript
import "server-only";
import { io } from "next/cache";
import { db } from "@/lib/db";
import type { Prisma } from "@/lib/generated/prisma/client";

// Only the columns pages need. Never send whole rows to the UI.
const summaryFields = {
  slug: true,
  title: true,
  city: true,
  venue: true,
  startsAt: true,
  capacity: true,
  priceInPaise: true,
} satisfies Prisma.EventSelect;

export type EventSummary = Prisma.EventGetPayload<{ select: typeof summaryFields }>;

type UpcomingOptions = { city?: string; limit?: number };

export async function getUpcomingEvents({ city, limit = 50 }: UpcomingOptions = {}): Promise<EventSummary[]> {
  await io(); // "upcoming" depends on the current time, so work it out per request
  return db.event.findMany({
    where: { startsAt: { gt: new Date() }, city },
    orderBy: { startsAt: "asc" },
    take: limit,
    select: summaryFields,
  });
}

export async function getCities(): Promise<string[]> {
  const rows = await db.event.findMany({
    distinct: ["city"],
    orderBy: { city: "asc" },
    select: { city: true },
  });
  return rows.map((row) => row.city);
}

export async function getEventBySlug(slug: string): Promise<EventSummary | null> {
  return db.event.findUnique({ where: { slug }, select: summaryFields });
}

export async function getGoingCount(slug: string): Promise<number> {
  return db.rsvp.count({ where: { event: { slug }, status: "GOING" } });
}

EventSummary is now derived from the query: change summaryFields and the type follows. In components/event-card.tsx, change the type import to @/lib/events, then delete lib/sample-events.ts. The organiserId, description and timestamps are never selected, so they cannot leak into a page by accident.

In where, a property set to undefined means "no filter", so city applies only when the URL had one. You can see that rule in plain JavaScript:

React JSXOpen in editor
import { createRoot } from "react-dom/client";

function whereFor(city) {
  return { startsAt: { gt: "now" }, city };
}

const cases = [["city=Pune", "Pune"], ["no city", undefined], ["empty city", ""]];
for (const [label, city] of cases) {
  console.log(label, "->", JSON.stringify(whereFor(city)));
}

const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log("14900 paise ->", rupees.format(14900 / 100));

createRoot(document.getElementById("root")).render(<p>Open the console output below.</p>);
Output
city=Pune -> {"startsAt":{"gt":"now"},"city":"Pune"}
no city -> {"startsAt":{"gt":"now"}}
empty city -> {"startsAt":{"gt":"now"},"city":""}
14900 paise -> ₹149.00

Like JSON.stringify, Prisma ignores undefined properties. But an empty string is a real value and would search for a city named "". The page from the last lesson already turns a missing or odd city into undefined.

Build and start the app. The route table is the same as in the last lesson, and in our run /events/rohtak-react-meetup showed "2 going · 58 seats left", counted from the two seeded RSVPs in PostgreSQL.

Safe queries and a safe database user

Prisma always sends values separately from the SQL text. We logged the query for an attacker's city value Pune' OR '1'='1 with a short script (log: [{ emit: "event", level: "query" }] on a test client):

Output
SQL: SELECT "public"."Event"."id", "public"."Event"."title" FROM "public"."Event" WHERE "public"."Event"."city" = $1 OFFSET $2 | params: ["Pune' OR '1'='1","0"]
Rows found: 0

The input became the parameter $1, never part of the SQL, so the trick found zero rows. If you ever need raw SQL, use the tagged template db.$queryRaw with ${value} placeholders, which are parameterised too. Never build SQL strings for $queryRawUnsafe from user input.

In production, give the running app a database user that can read and write rows but not change tables. Run migrations separately, as the owner. A sketch for PostgreSQL 18:

PostgreSQL
CREATE ROLE eventhub_app LOGIN PASSWORD 'from-your-secret-manager';
GRANT CONNECT ON DATABASE eventhub TO eventhub_app;
GRANT USAGE ON SCHEMA public TO eventhub_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO eventhub_app;

The details, including default privileges for future tables, are in Roles, Privileges & Row-Level Security. For a database on another machine, also require TLS in the URL (sslmode=require or stricter).

Common mistakes

  • Running npm install prisma without a version. On the day we checked, it installed a release candidate. Pin the same version for every Prisma package.
  • Forgetting npx prisma generate. Prisma 7's migrate dev does not regenerate the client, so new columns are missing from TypeScript.
  • Creating new PrismaClient() in many files. Use the one client in lib/db.ts.
  • Selecting whole rows for the UI. Use select and pass only what the page shows.
  • Editing an applied migration file. Change schema.prisma and create a new migration instead.
  • Connecting as the postgres superuser in production. Use a role with only the rights the app needs.

Interview questions

1. What is the difference between prisma migrate dev and prisma db push?

migrate dev writes a SQL migration file, applies it and keeps a history that every environment replays in order. db push changes the database to match the schema without a migration file, which is handy for quick prototypes but leaves no history to deploy. Teams use migrations, applied in production with prisma migrate deploy.

2. Why do Next.js apps keep a single Prisma Client instance?

Each client has its own connection pool. Creating clients repeatedly, especially during development hot reloads, opens new pools until the database runs out of connections. One client per server process, stored on globalThis in development, avoids that.

3. How does Prisma protect against SQL injection?

Its query methods send values as bound parameters ($1, $2) separate from the SQL text, so input is never parsed as SQL. The $queryRaw tagged template is also parameterised. Only the "Unsafe" raw methods with string-built SQL are dangerous.

4. Why did EventHub add a composite unique constraint on Rsvp?

@@unique([eventId, userId]) makes the database reject a second RSVP by the same user for the same event, even if two requests arrive at once or the application check has a bug. Constraints in the database are the last line of defence for data rules.

Key points

  • Prisma = schema + migrations + a generated, typed client. EventHub uses Prisma ORM 7.10.1 with @prisma/adapter-pg.
  • Pin Prisma package versions; npm's latest tag for the CLI pointed at a release candidate on 16 Nov 2026.
  • Configuration lives in prisma7.config.ts, the URL in .env as DATABASE_URL, and generated code in lib/generated/prisma (git-ignored).
  • npx prisma dev gives a PGlite-based local PostgreSQL; the same schema runs on PostgreSQL 18.
  • Run migrate dev, then generate; seed with idempotent upserts.
  • One client in lib/db.ts; all queries in lib/events.ts with explicit select.
  • Prisma parameterises values; production apps connect with a least-privilege role and TLS.

Exercise

Organisers want online meetups too. Add a boolean isOnline column to Event that defaults to false, and make venue optional for online events. Create a migration named online_events, update the seed so the Kochi workshop is online, include the new field in summaryFields, and show "Online" instead of the venue on the event page.

Show solution
Text
model Event {
  // ...other fields unchanged
  venue    String?
  isOnline Boolean @default(false)
}
Terminal
npx prisma migrate dev --name online_events
npx prisma generate
npx prisma db seed
React TSX
// lib/events.ts: add isOnline: true to summaryFields
// app/events/[slug]/page.tsx
<p>{event.isOnline ? "Online" : `${event.venue}, ${event.city}`}</p>

In the seed, set isOnline: true (and, if you like, venue: null) on the Kochi event. The migration drops the NOT NULL rule on venue and adds a column with a default, so existing rows stay valid. Because EventSummary is derived from summaryFields, TypeScript now knows event.isOnline everywhere, and that venue may be null.

Quick Quiz

1. Which command creates a SQL migration file and applies it to your development database?

2. What does @@unique([eventId, userId]) on Rsvp guarantee?

3. An attacker sends ?city=Pune' OR '1'='1. What does Prisma send to PostgreSQL?

4. Why does prisma/seed.ts create its own PrismaClient instead of importing lib/db.ts?

Learn Next.js Full Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call