No prior database experience needed. This guide walks you through everything — what Prisma is, how it works, how to get a free cloud database in seconds, and how to write your first queries.
What Is Prisma?
If you've ever tried talking to a database from a Node.js app, you know how messy it can get. You write raw SQL strings, hope there are no typos, and get zero help from TypeScript. That's the old way.
Prisma is an ORM (Object-Relational Mapper). An ORM is basically a bridge between your JavaScript/TypeScript code and your database. Instead of writing SQL like:
SELECT * FROM users WHERE id = 1;
You write clean TypeScript like:
const user = await prisma.user.findUnique({ where: { id: 1 } });
And Prisma handles the SQL for you. It also gives you full TypeScript autocomplete — so your editor knows what fields exist on a user, what types they are, and warns you if you make a mistake.
Prisma has three main parts:
- Prisma ORM — The core library. Reads your schema and lets you query your database with TypeScript.
- Prisma Client — The auto-generated, type-safe code that you actually import in your app to run queries.
- Prisma Studio — A visual, browser-based UI where you can see and edit your database data without writing any code.
What Changed in Prisma 7?
Prisma 7 (released November 2025) introduced some important changes:
-
Driver adapters are now required. In older versions, Prisma connected to databases directly. Now, you pass a "driver adapter" (like
@prisma/adapter-pgfor PostgreSQL) toPrismaClient. This gives better performance and edge runtime support. -
A new
prisma.config.tsfile — Previously, all config lived insideschema.prisma. Now there's a separate TypeScript config file. - ESM first — Prisma 7 prefers ES Modules (the modern JavaScript module system).
-
Free cloud database with one command — You can now run
npx create-db(orpnpm dlx create-db) and get a real hosted PostgreSQL database in seconds, no account needed.
Don't worry — this guide covers all of this step by step.
Prerequisites
You need:
- Node.js 18+ installed — Download from nodejs.org
-
npm or pnpm — npm comes with Node.js. To install pnpm:
npm install -g pnpm - A code editor (VS Code recommended)
That's it. You don't need to install PostgreSQL locally. Prisma will give you a free cloud database.
Part 1: Option A — Get a Free Cloud Database (Recommended for Beginners)
This is the easiest path. Prisma offers a free hosted PostgreSQL database that you can spin up with a single command — no signup, no credit card.
How It Works
When you run npx create-db (or pnpm dlx create-db), Prisma:
- Provisions a real PostgreSQL database in the cloud
- Gives you a connection string you paste into your project
- Gives you a 24-hour window to use the database for free
- Shows you a claim URL — click it to keep the database permanently for free (requires a free Prisma account)
Think of it like a test drive. You get 24 hours free. If you want to keep it, you claim it — and it stays free on Prisma's generous free tier.
Step 1: Create a New Project
Open your terminal and run:
bash
mkdir hello-prisma
cd hello-prisma
Now initialize a Node.js TypeScript project:
npm:
bash
npm init -y
npm install typescript tsx @types/node --save-dev
npx tsc --init
pnpm:
bash
pnpm init
pnpm add typescript tsx @types/node --save-dev
pnpm dlx tsc --init
Step 2: Install Prisma and Its Dependencies
npm:
bash
npm install prisma @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg pg dotenv
pnpm:
bash
pnpm add prisma @types/pg --save-dev
pnpm add @prisma/client @prisma/adapter-pg pg dotenv
| Package | What it does |
|---|---|
prisma |
The Prisma CLI — runs commands like prisma init, prisma migrate, prisma studio
|
@prisma/client |
The library you import in your app to query the database |
@prisma/adapter-pg |
Connects Prisma to PostgreSQL (required in Prisma 7) |
pg |
The actual PostgreSQL driver for Node.js |
@types/pg |
TypeScript types for pg
|
dotenv |
Reads your .env file so Prisma can find your database URL |
Step 3: Configure ESM Support
Prisma 7 uses modern ES Modules. You need to tell your project about this.
Open tsconfig.json and replace its contents with:
json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}
Then open package.json and add "type": "module" inside it:
json
{
"name": "hello-prisma",
"type": "module",
...
}
What is ESM? ES Modules is the modern way JavaScript handles imports/exports (
import/exportinstead ofrequire). Prisma 7 fully embraces this.
Step 4: Initialize Prisma
npm:
bash
npx prisma init --output ../generated/prisma
pnpm:
bash
pnpm dlx prisma init --output ../generated/prisma
This command creates three things in your project:
-
prisma/schema.prisma— Where you define your data models (your database tables) -
.env— Where your database connection URL goes -
prisma.config.ts— The new Prisma 7 configuration file
Your prisma.config.ts will look like this:
typescript
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DATABASE_URL"),
},
});
What is
prisma.config.ts? This is new in Prisma 7. It tells Prisma where your schema is, where to store migration history, and how to connect to your database. Think of it as the "settings file" for Prisma.
Step 5: Get Your Free Cloud Database
Now run this single command to get a free hosted PostgreSQL database:
npm:
bash
npx create-db
pnpm:
bash
pnpm dlx create-db
You'll see output like this in your terminal:
┌ 🚀 Creating a Prisma Postgres database
│
│ Provisioning a temporary database in us-east-1...
│ It will be automatically deleted in 24 hours, but you can claim it.
│
◇ Database created successfully!
│
● Database Connection
│ Connection String:
│ postgresql://<username>:<password>@db.prisma.io:5432/postgres
│
◆ Claim your database →
│
│ Want to keep your database? Claim for free:
│ https://create-db.prisma.io?projectID=proj_...
│
│ Your database will be deleted on [date] if not claimed.
└
Copy that connection string and paste it into your .env file:
DATABASE_URL="postgresql://<username>:<password>@db.prisma.io:5432/postgres"
How to Claim Your Free Database (Keep It Forever)
- Copy the claim URL from the terminal output (it looks like
https://create-db.prisma.io?projectID=proj_...) - Open it in your browser
- Sign in with Google or GitHub (creates a free Prisma Data Platform account)
- Choose a workspace and click Claim
That's it — your database is now permanently yours on Prisma's free tier. No credit card needed.
Part 1: Option B — Use Your Own PostgreSQL Database
If you already have a PostgreSQL database running (locally or on a service like Supabase, Railway, Neon, etc.), use this path instead.
Step 1–4: Same as Option A
Follow Steps 1–4 above, but when initializing Prisma, add --datasource-provider postgresql:
npm:
bash
npx prisma init --datasource-provider postgresql --output ../generated/prisma
pnpm:
bash
pnpm dlx prisma init --datasource-provider postgresql --output ../generated/prisma
Step 5: Add Your Database URL
Skip npx create-db. Instead, open .env and paste your own connection string:
DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public"
Replace these parts with your actual details:
| Placeholder | What to replace it with |
|---|---|
username |
Your PostgreSQL username (often postgres) |
password |
Your PostgreSQL password |
localhost:5432 |
Your database host and port |
mydb |
The name of your database |
Using Supabase? Go to your Supabase project → Settings → Database → Connection String (URI mode). Copy and paste that.
Using Neon? Go to your Neon dashboard → Connection Details → paste the connection string.
Part 2: Define Your Data Model
Now let's tell Prisma what your database should look like. Open prisma/schema.prisma.
You'll see it already has some boilerplate. Add your models at the bottom:
prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
What Does This Mean?
Think of each model as a database table. Let's break down the User model:
-
id Int @id @default(autoincrement())— A number that auto-increases (1, 2, 3...). This is the primary key that uniquely identifies each user. -
email String @unique— A text field that must be unique across all users (no duplicates). -
name String?— The?means this field is optional (can be null). -
posts Post[]— This user can have many posts. This is a relation — it links User to Post.
In the Post model:
-
author User @relation(...)— Each post belongs to one User. -
authorId Int— This stores theidof the related user (the foreign key).
Part 3: What Is a Migration?
Before we run the migration command, let's understand what a migration actually is.
Migrations Explained Simply
Imagine your database as a building. When you first create it, you start with an empty plot of land. A migration is like a construction blueprint — it describes what changes to make to the building.
- First migration — "Build the foundation, add walls, add rooms" (creates your tables)
- Second migration — "Add a new room on the second floor" (adds a new column or table)
- Third migration — "Rename the living room to the lounge" (renames a field)
Every migration is saved as a file. This means:
- You can see the full history of every change ever made to your database
- You can share these files with your team, so everyone's database looks the same
- You can replay them in production to update the live database safely
Prisma stores migration files in prisma/migrations/. Each migration is a folder with a timestamp and a .sql file inside it.
Run Your First Migration
npm:
bash
npx prisma migrate dev --name init
pnpm:
bash
pnpm dlx prisma migrate dev --name init
The --name init just gives this migration a human-readable name. You can call it anything that describes what changed (e.g., --name add-user-table or --name add-email-field).
This command:
- Looks at your
schema.prisma - Compares it to the current state of your database
- Generates SQL to make the database match your schema
- Applies that SQL to your database
- Saves the migration file for your records
migrate devvsmigrate deploy—migrate devis for development (creates and applies migrations).migrate deployis for production (only applies already-existing migrations). Never runmigrate devin production.
Generate the Prisma Client
After migration, generate the Prisma Client so your TypeScript code is in sync with your schema:
npm:
bash
npx prisma generate
pnpm:
bash
pnpm dlx prisma generate
This creates auto-generated TypeScript code in the generated/prisma folder. You don't edit this folder — Prisma regenerates it every time you run prisma generate.
Part 4: Set Up Prisma Client in Your Code
In Prisma 7, you need to set up a driver adapter when creating the client. Create a new file at lib/prisma.ts:
typescript
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";
const connectionString =${process.env.DATABASE_URL};`
const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });
export { prisma };
What Is a Driver Adapter?
Think of the driver adapter as a translator. Prisma speaks its own query language internally. The adapter translates that into something PostgreSQL understands. In Prisma 7, this is now explicit instead of being hidden behind the scenes.
Important: Never create multiple instances of
PrismaClientin your app. Creating many instances can overload your database with too many connections. Always export one shared instance (like we did above) and import it wherever you need it.
Part 5: Write Your First Queries
Create a file called script.ts in the root of your project:
typescript
import { prisma } from "./lib/prisma";
async function main() {
// --- CREATE a user with a post ---
const user = await prisma.user.create({
data: {
name: "Alice",
email: "alice@example.com",
posts: {
create: {
title: "My First Post",
content: "Hello, Prisma!",
published: true,
},
},
},
include: {
posts: true, // also return the posts
},
});
console.log("Created user:", user);
// --- READ all users ---
const allUsers = await prisma.user.findMany({
include: { posts: true },
});
console.log("All users:", JSON.stringify(allUsers, null, 2));
// --- UPDATE a post ---
const updatedPost = await prisma.post.update({
where: { id: user.posts[0].id },
data: { title: "Updated Title" },
});
console.log("Updated post:", updatedPost);
// --- DELETE a user ---
// (Uncomment this if you want to test deletion)
// await prisma.user.delete({ where: { id: user.id } });
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Now run the script:
npm:
bash
npx tsx script.ts
pnpm:
bash
pnpm dlx tsx script.ts
You should see the newly created user and all users printed in your terminal. Congratulations — you just wrote to a real database with Prisma! 🎉
Quick Cheat Sheet: Common Prisma Queries
typescript
// Find one by unique field
const user = await prisma.user.findUnique({ where: { email: "alice@example.com" } });
// Find all
const users = await prisma.user.findMany();
// Find with filter
const publishedPosts = await prisma.post.findMany({
where: { published: true },
});
// Create
const newUser = await prisma.user.create({
data: { name: "Bob", email: "bob@example.com" },
});
// Update
const updated = await prisma.user.update({
where: { id: 1 },
data: { name: "Bobby" },
});
// Delete
await prisma.user.delete({ where: { id: 1 } });
// Count
const count = await prisma.user.count();
Part 6: Prisma Studio — See Your Data Visually
Prisma Studio is a free, browser-based database viewer that comes built into Prisma. You don't need to install anything extra.
Run this command:
npm or pnpm (same command):
bash
npx prisma studio
It will open a tab in your browser at http://localhost:5555. You'll see:
- All your tables listed on the left (User, Post, etc.)
- Click any table to see all its rows
- You can add, edit, and delete rows directly from the UI
- Changes are reflected in your real database instantly
This is super useful for:
- Quickly checking if your queries worked
- Adding test data without writing code
- Debugging unexpected data
Part 7: What Happens When You Update Your Schema?
Let's say you want to add a bio field to the User model. Here's the workflow:
Step 1: Open prisma/schema.prisma and add the field:
prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
bio String? // ← new field
posts Post[]
}
Step 2: Create a new migration:
npm:
bash
npx prisma migrate dev --name add-bio-to-user
pnpm:
bash
pnpm dlx prisma migrate dev --name add-bio-to-user
Step 3: Regenerate the client:
npm:
bash
npx prisma generate
pnpm:
bash
pnpm dlx prisma generate
Now your TypeScript code will have full autocomplete for the new bio field. That's the Prisma workflow — schema change → migrate → generate → done.
Folder Structure Overview
After following this guide, your project will look like this:
hello-prisma/
├── generated/
│ └── prisma/ ← Auto-generated Prisma Client (don't edit)
├── lib/
│ └── prisma.ts ← Your Prisma Client setup
├── prisma/
│ ├── migrations/ ← Migration history files
│ └── schema.prisma ← Your data models
├── .env ← Your DATABASE_URL (never commit this to git!)
├── prisma.config.ts ← Prisma configuration
├── script.ts ← Your test queries
├── package.json
└── tsconfig.json
⚠️ Important: Add
.envto your.gitignorefile. Your database URL contains a password and should never be pushed to GitHub.
Quick Reference: All Commands
| What you want to do | npm | pnpm |
|---|---|---|
| Initialize Prisma | npx prisma init |
pnpm dlx prisma init |
| Get free cloud database | npx create-db |
pnpm dlx create-db |
| Create & apply migration | npx prisma migrate dev --name <name> |
pnpm dlx prisma migrate dev --name <name> |
| Generate Prisma Client | npx prisma generate |
pnpm dlx prisma generate |
| Open Prisma Studio | npx prisma studio |
npx prisma studio |
| Run TypeScript file | npx tsx <file>.ts |
pnpm dlx tsx <file>.ts |
Summary — What Did We Learn?
- Prisma is an ORM that lets you talk to your database using TypeScript instead of raw SQL
-
Prisma 7 requires driver adapters and introduces a
prisma.config.tsfile -
npx create-dbgives you a free hosted PostgreSQL database in seconds — no signup needed, and you can claim it permanently for free - Prisma Schema is where you define your models (database tables)
-
Migrations are versioned snapshots of your database changes — run
prisma migrate devevery time your schema changes -
Prisma Client is the auto-generated code you use to query your database — regenerate it with
prisma generateafter each migration - Prisma Studio is a visual UI to browse and edit your database data right from the browser
What's Next?
Now that you have the basics down, here's where to go:
- Use Prisma with Next.js — Prisma works great in Next.js API routes and Server Actions
-
Explore filtering and pagination —
where,orderBy,take,skipin Prisma Client - Learn about relations — One-to-many, many-to-many, nested queries
-
Try Prisma Migrate in production — Use
prisma migrate deployin your CI/CD pipeline - Check out the Prisma docs — prisma.io/docs
Have questions? Drop them in the comments below. Happy building!
Top comments (0)