Next.js Zero to Advanced #6: Prisma β Schema, Migration & Seed
In Part 5 we got PostgreSQL 16 running and stored DATABASE_URL in .env. The digistore database is still empty. In this Part 6 we will install Prisma, define DigiStore's data model (User, Product, Order), create tables with a migration, browse data with Prisma Studio, create a Next.js-ready lib/prisma.ts, and fill in initial data with a seed script.
By the end of this part, your database will contain 1 admin, 1 regular user and 6 products, ready to be loaded by DigiStore's pages in Part 7.
What is Prisma?
Prisma is an ORM (Object-Relational Mapper) for Node.js and TypeScript. Instead of writing raw SQL on every page, we describe the data structure once in a schema.prisma file, and Prisma helps in three ways:
- Prisma Schema: a single source of truth for the data model.
- Prisma Migrate: generates SQL migration files from schema changes and applies them to the database.
- Prisma Client: a type-safe query builder. If you mistype a column name, TypeScript reports an error before the app even runs.
Installing Prisma 6
From the digistore folder, run:
npm install prisma@6 --save-dev
npm install @prisma/client@6
npx prisma --version
Result:
prisma : 6.19.x
@prisma/client : 6.19.x
...
prisma is the CLI (only needed during development and builds), while @prisma/client is the library the app uses at runtime. Make sure both use the same major version.
Version note: this series pins Prisma 6 (
@6). Newer Prisma majors (Prisma 7 and later) change several things, such as how connections and the client generator are configured. If you use a newer version, some steps in this series may differ, so follow the official documentation for that version.
Initializing with prisma init
npx prisma init --datasource-provider postgresql
This command needs an internet connection because the CLI downloads the latest init helper. The result looks roughly like this:
digistore/
βββ prisma/
β βββ schema.prisma <- new: data model
βββ prisma.config.ts <- new: Prisma CLI configuration
βββ .env <- already exists (Part 5), DATABASE_URL is kept
βββ .gitignore <- Prisma may append a line for its generated client
A few things to notice in the output:
- Because
.envalready containsDATABASE_URLfrom Part 5, Prisma does not overwrite it and only prints a warning. Good. - Because
.gitignorealready exists, Prisma reminds you that.envshould be in it. We made sure of that in Part 5. - The generator in the
schema.prismacreated byinitmay differ depending on the helper version downloaded (for example a newer generator with anoutputfolder). That's fine, because we are about to replace the whole file.
Configuring prisma.config.ts
prisma.config.ts configures the Prisma CLI. There is one important behavior: when this config file exists, the Prisma CLI no longer loads .env automatically. That's why the generated file starts with import 'dotenv/config', and we need to install the package:
npm install --save-dev dotenv
Then tidy up prisma.config.ts as follows. We also add the seed command we will create at the end of this part:
// prisma.config.ts
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
engine: 'classic',
datasource: {
url: env('DATABASE_URL'),
},
})
env('DATABASE_URL') reads the value from the environment, so no secret is written in this file. Next.js itself does not read prisma.config.ts; the app still loads .env through Next.js's built-in mechanism.
Many older tutorials put the seed command in
package.json("prisma": { "seed": "..." }). In Prisma 6.19 that still works, but the CLI warns thatpackage.json#prismais deprecated and will be removed in Prisma 7. Since we already haveprisma.config.ts, we put it undermigrations.seed.
Writing the DigiStore schema
Replace the entire contents of prisma/schema.prisma with the following models:
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
enum Role {
USER
ADMIN
}
enum Category {
EBOOK
SOURCE_CODE
TEMPLATE
}
model User {
id String @id @default(cuid())
email String @unique
name String
passwordHash String
role Role @default(USER)
orders Order[]
createdAt DateTime @default(now())
}
model Product {
id String @id @default(cuid())
slug String @unique
title String
description String
price Int // in rupiah, no decimals
category Category
imageUrl String?
published Boolean @default(true)
orders Order[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Order {
id String @id @default(cuid())
user User @relation(fields: [userId], references: [id])
userId String
product Product @relation(fields: [productId], references: [id])
productId String
amount Int
createdAt DateTime @default(now())
@@index([userId])
@@index([productId])
}
Generator and datasource
generator clientwithprovider = "prisma-client-js": Prisma 6's classic generator, which outputs the client intonode_modules, so we can writeimport { PrismaClient } from '@prisma/client'.datasource db: a PostgreSQL database whose address is read fromenv("DATABASE_URL").
Enums
Role and Category become ENUM types in PostgreSQL. The database rejects any value that isn't listed, such as role = 'SUPERADMIN'. These values match the Category type we created in lib/products.ts in Part 4.
Field attributes
@id @default(cuid()): a primary key that is a hard-to-guess random string, such asclx3k9....@unique: no two users can share an email, and no two products can share a slug. It also creates an index, so looking up products by slug in Part 7 is fast.String?: the question mark means the column may beNULL, likeimageUrl.@default(now())and@updatedAt: Prisma fills in created and updated timestamps automatically.price Int: the price in Rupiah without decimals. Storing money as integers avoids decimal rounding problems.passwordHash: we never store the real password, only its bcrypt hash.
Relations
One User can have many Orders, and one Product can appear in many Orders. In the Order model, the line user User @relation(fields: [userId], references: [id]) means the userId column is a foreign key to User.id. The orders Order[] fields on User and Product are the other side of the relation; they do not become database columns. @@index([userId]) and @@index([productId]) create indexes so queries like "all orders of this user" (Part 10) stay fast. The amount field stores the price at the time of purchase, so order history doesn't change when a product's price is edited later.
Check and format the schema:
npx prisma format
npx prisma validate
The first migration
Now we turn the schema into real tables:
npx prisma migrate dev --name init
Result (roughly):
Loaded Prisma config from prisma.config.ts.
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "digistore", schema "public" at "localhost:5432"
Applying migration `20261031080000_init`
The following migration(s) have been created and applied from new schema changes:
prisma/migrations/
ββ 20261031080000_init/
ββ migration.sql
Your database is now in sync with your schema.
Generated Prisma Client (v6.19.x) to ./node_modules/@prisma/client
migrate dev does three things: it creates an SQL file in prisma/migrations/, runs it against the database, and runs prisma generate so Prisma Client matches the latest schema. Here is an excerpt of the generated SQL:
-- prisma/migrations/20261031080000_init/migration.sql (excerpt)
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN');
-- CreateTable
CREATE TABLE "Product" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT NOT NULL,
"price" INTEGER NOT NULL,
"category" "Category" NOT NULL,
"imageUrl" TEXT,
"published" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Product_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Product_slug_key" ON "Product"("slug");
-- AddForeignKey
ALTER TABLE "Order" ADD CONSTRAINT "Order_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
The prisma/migrations folder must be committed to Git. It is the history of your database structure, and in Part 12 we will run the same migrations against the production database. Don't edit migration files that have already been applied; when the schema changes, create a new migration with npx prisma migrate dev --name change-name.
Check the result in psql (docker exec -it digistore-db psql -U digistore -d digistore):
digistore=# \dt
List of relations
Schema | Name | Type | Owner
--------+--------------------+-------+-----------
public | Order | table | digistore
public | Product | table | digistore
public | User | table | digistore
public | _prisma_migrations | table | digistore
The _prisma_migrations table is used by Prisma to record which migrations have been applied. Also note that table names start with an uppercase letter, so in hand-written SQL you must wrap them in double quotes, for example SELECT * FROM "Product";.
Prisma Studio
Prisma Studio is a browser GUI for viewing and editing data:
npx prisma studio
Studio opens at http://localhost:5555. Right now all tables are empty. Studio is very handy during development, but remember that anyone who opens it can change data, so never run it connected to a production database.
The PrismaClient singleton: lib/prisma.ts
Every new PrismaClient() opens its own connection pool to the database. In development mode, Next.js reloads modules every time you save a file (hot reload). If we create a new client on every reload, connections pile up until PostgreSQL refuses with a "too many clients" error. The fix is to keep a single instance on globalThis:
// lib/prisma.ts
import { PrismaClient } from '@prisma/client'
// In development, Next.js hot reload re-runs modules. Without this,
// every reload would create a new PrismaClient and a new connection pool.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient }
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['warn', 'error'] : ['error'],
})
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
- In development, the instance is stored on
globalThisand reused after hot reloads. - In production, the module is loaded only once, so there is no need to store it globally.
- The
logoption prints Prisma warnings and errors to the terminal during development.
From Part 7 onward, every query in a Server Component will use import { prisma } from '@/lib/prisma'. Remember the rule from Part 3: this file must only be used in server code. Never import lib/prisma.ts from a file with "use client".
Seeding initial data
A seed script fills the database with initial data so every team member can try the app right away. We need bcryptjs to hash passwords and tsx to run TypeScript files:
npm install bcryptjs
npm install --save-dev tsx
bcryptjs version 3 ships its own TypeScript types, so no extra @types package is needed.
Seed passwords from environment variables
The seeded admin is a real account that can log in in Part 10. Therefore its password must not be written in code. Generate two random values:
openssl rand -hex 16 # run twice, one value per variable
Then add them to .env:
# .env (local only, never commit)
DATABASE_URL="postgresql://digistore:YOUR_LOCAL_PASSWORD@localhost:5432/digistore?schema=public"
# TODO: Securely load this value from an environment variable or secrets vault. Do not hardcode.
SEED_ADMIN_PASSWORD="paste-a-random-value-here"
SEED_USER_PASSWORD="paste-another-random-value-here"
Also update .env.example so the team knows about these new variables, without real values:
# .env.example
DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/digistore?schema=public"
SEED_ADMIN_PASSWORD=""
SEED_USER_PASSWORD=""
Writing prisma/seed.ts
// prisma/seed.ts
import 'dotenv/config'
import bcrypt from 'bcryptjs'
import { Category, Prisma, PrismaClient, Role } from '@prisma/client'
const prisma = new PrismaClient()
function requireSecret(name: string): string {
// TODO: Securely load this value from an environment variable or secrets vault. Do not hardcode.
const value = process.env[name]
if (!value || value.length < 12) {
throw new Error(`${name} is missing or shorter than 12 characters. Set it in .env`)
}
return value
}
const products: Prisma.ProductCreateInput[] = [
{
slug: 'ebook-belajar-nextjs',
title: 'E-book Belajar Next.js',
description: 'Panduan praktis membangun aplikasi web dengan Next.js.',
price: 99000,
category: Category.EBOOK,
imageUrl: '/products/ebook-belajar-nextjs.jpg',
},
{
slug: 'ebook-dasar-postgresql',
title: 'E-book Dasar PostgreSQL',
description: 'Belajar SQL dan desain tabel dari nol.',
price: 79000,
category: Category.EBOOK,
imageUrl: null,
},
{
slug: 'source-code-kasir-nextjs',
title: 'Source Code Aplikasi Kasir',
description: 'Aplikasi kasir sederhana dengan Next.js dan Prisma.',
price: 249000,
category: Category.SOURCE_CODE,
imageUrl: null,
},
{
slug: 'source-code-rest-api-starter',
title: 'REST API Starter',
description: 'Kerangka REST API dengan validasi dan autentikasi.',
price: 199000,
category: Category.SOURCE_CODE,
imageUrl: null,
},
{
slug: 'template-landing-page',
title: 'Template Landing Page',
description: 'Landing page responsif berbasis Tailwind CSS.',
price: 149000,
category: Category.TEMPLATE,
imageUrl: null,
},
{
slug: 'template-dashboard-admin',
title: 'Template Dashboard Admin',
description: 'Dashboard admin dengan tabel, grafik, dan form.',
price: 179000,
category: Category.TEMPLATE,
imageUrl: null,
published: false, // a draft: useful for testing filters later
},
]
async function main() {
const adminPasswordHash = await bcrypt.hash(requireSecret('SEED_ADMIN_PASSWORD'), 12)
const userPasswordHash = await bcrypt.hash(requireSecret('SEED_USER_PASSWORD'), 12)
await prisma.user.upsert({
where: { email: 'admin@digistore.test' },
update: {},
create: {
email: 'admin@digistore.test',
name: 'Admin DigiStore',
passwordHash: adminPasswordHash,
role: Role.ADMIN,
},
})
await prisma.user.upsert({
where: { email: 'user@digistore.test' },
update: {},
create: {
email: 'user@digistore.test',
name: 'Pembeli Contoh',
passwordHash: userPasswordHash,
},
})
for (const product of products) {
await prisma.product.upsert({
where: { slug: product.slug },
update: product,
create: product,
})
}
console.log(`Seeded 2 users and ${products.length} products`)
}
main()
.catch((error) => {
console.error(error)
process.exitCode = 1
})
.finally(async () => {
await prisma.$disconnect()
})
Explanation
requireSecret()stops the seed with a clear message if a password is missing or too short, instead of silently creating an admin with an empty password.bcrypt.hash(password, 12)produces a hash with a cost factor of 12. Only the hash is stored in thepasswordHashcolumn.- Emails use the
.testdomain, which is reserved for testing, so they can never belong to a real person. upsertmakes the seed idempotent: it's safe to run many times without creating duplicates. Products are matched byslug, users byemail. Because ofupdate: {}, existing users' passwords are not changed when the seed runs again.Prisma.ProductCreateInputis a type Prisma generates from the schema. If you mistype a category, such as'EBOOKS', TypeScript flags it immediately.- The last product is created with
published: falseas a draft. In Part 7 we will make sure drafts don't appear on public pages. - The seed also imports
dotenv/config, so it still works when run directly withnpx tsx prisma/seed.ts.
Running the seed
npx prisma db seed
Result:
Loaded Prisma config from prisma.config.ts.
Running seed command `tsx prisma/seed.ts` ...
Seeded 2 users and 6 products
The seed command has been executed.
Verify in psql:
SELECT email, role, left("passwordHash", 7) AS hash_prefix FROM "User";
SELECT slug, price, category, published FROM "Product" ORDER BY price;
Result of the first query:
email | role | hash_prefix
----------------------+-------+-------------
admin@digistore.test | ADMIN | $2b$12$
user@digistore.test | USER | $2b$12$
The password column only contains bcrypt hashes (starting with $2b$12$), not the real passwords. Open Prisma Studio as well to see all six products.
Common mistakes
- "Environment variable not found: DATABASE_URL" when running Prisma commands. Usually
prisma.config.tsdoesn't importdotenv/configor thedotenvpackage isn't installed. - Error P1001 "Can't reach database server". The PostgreSQL container isn't running (
docker start digistore-db) or the port inDATABASE_URLis wrong. - Different versions of
prismaand@prisma/client. Always install them with the same major version (@6). - Changing the schema without creating a migration. Every model change must be followed by
npx prisma migrate dev --name .... Don't alter tables by hand with SQL. - Creating
new PrismaClient()in many files. Always import fromlib/prisma.ts(except in the seed script, which runs separately). - Writing the admin password directly in
seed.ts. This file is committed to Git, so the password would leak. Use environment variables. - Running
npx prisma migrate resetcarelessly. It deletes all data. Fine locally, dangerous in production.
Exercises
- Add a seventh product to the
productsarray in the seed, runnpx prisma db seedtwice, then confirm in Prisma Studio that there are no duplicate products. - Add an optional field
downloadUrl String?to theProductmodel, create a migration namedadd-download-url, and read the generated SQL file. (You may keep it afterwards; the series doesn't use it.) - Run the seed without
SEED_ADMIN_PASSWORDin.envand observe the error message fromrequireSecret().
Summary
- Prisma consists of Schema, Migrate, Client and Studio. This series uses Prisma 6 (
prisma@6and@prisma/client@6). npx prisma initcreatesprisma/schema.prismaandprisma.config.ts. With a config file, the CLI doesn't load.envautomatically, so we useimport 'dotenv/config'.- The DigiStore schema contains the
RoleandCategoryenums and theUser,ProductandOrdermodels with relations and indexes. npx prisma migrate dev --name initcreates and applies a migration; theprisma/migrationsfolder is committed.lib/prisma.tskeeps a single PrismaClient onglobalThisso hot reloads don't open excess connections.prisma/seed.tsusesupsert, hashes passwords with bcryptjs and reads them from environment variables. Run it withnpx prisma db seed.
DigiStore's database now has data. In Part 7 we will replace the array in lib/products.ts with Prisma queries directly in Server Components, complete with search, category filters, pagination, and loading, empty and error states. See you there!
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #5: Arrays & Array Functions
Master PHP arrays: indexed and associative arrays, nested data, destructuring, and the essential functions array_map, array_filter, array_reduce, usort, and friends.
Ruby on Rails Zero to Advanced #5: Routing, Controllers & Views
Follow a request through Rails: define routes, use resources, read params in controllers, and render dynamic HTML with ERB views and partials.