Prisma: Modern ORM for Node.js & TypeScript
You rename a column, the app compiles fine, and the first sign anything is wrong is a 500 in production because some query still selects user_name. Or you write const rows: User[] = await db.query(...) and the type is a promise you made to yourself, not something the compiler actually checked. Most Node.js database bugs I see come from that gap between what the code assumes and what the table really looks like.
Prisma closes that gap by starting from a schema file and generating a typed client from it, so your editor knows which fields and relations exist and what each query returns. This post covers setup, the schema language, CRUD queries, migrations, transactions, middleware, raw SQL, and how Prisma compares to Sequelize, TypeORM and Mongoose.
Because the client is generated from your schema, autocomplete only offers fields that actually exist, and a select changes the return type to match. If you drop a column and regenerate, every query that used it turns into a compile error instead of a runtime one.
The Pieces of Prisma
When people say "Prisma" they usually mean a handful of tools that ship together:
- Prisma Schema: A declarative, human-readable file (
schema.prisma) where you define your data models, relations, and database connection. It's the single source of truth for your data layer. - Prisma Client: An auto-generated, type-safe query builder that is tailored to your schema. Every model, field, and relation shows up in the TypeScript types, so you don't need to cast anything.
- Prisma Migrate: Turns schema changes into SQL migration files, tracks which ones have run, and applies the rest.
- Prisma Studio: A visual, web-based GUI to explore and edit your database data during development.
How Prisma's three components work together
Setting Up Prisma
Adding Prisma to a fresh TypeScript project takes a few minutes. These are the steps from an empty folder.
Initialize your project and install Prisma
Start with a Node.js project (TypeScript recommended) and install Prisma as a dev dependency along with the Prisma Client runtime package.
# Create project and install dependencies
mkdir my-prisma-app && cd my-prisma-app
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init
# Install Prisma
npm install prisma --save-dev
npm install @prisma/client
# Initialize Prisma (creates prisma/schema.prisma and .env)
npx prisma init
Configure your database connection
Prisma reads your database URL from the .env file. Update the DATABASE_URL to point to your database.
# PostgreSQL
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
# MySQL
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
# SQLite (great for development and prototyping)
DATABASE_URL="file:./dev.db"
Define your data models in schema.prisma
The Prisma schema file is where you describe your database structure using Prisma's declarative Schema Language (PSL).
Run migrations and generate the client
Run npx prisma migrate dev to apply your schema to the database and auto-generate the typed Prisma Client.
Prisma supports PostgreSQL, MySQL, MariaDB, SQLite, Microsoft SQL Server, CockroachDB, and MongoDB (Preview). For new projects I'd pick PostgreSQL. It has the widest feature coverage in Prisma (case-insensitive filters, native types, full migration support), and some query options shown below, like mode: 'insensitive', simply don't exist on other providers.
Defining Your Prisma Schema
Everything starts in schema.prisma. You describe models, fields and relations there, and both the client and the migrations are derived from it. Here's a small blog schema with users, profiles, posts and tags:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
role Role @default(USER)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
posts Post[]
profile Profile?
}
model Profile {
id Int @id @default(autoincrement())
bio String?
avatar String?
userId Int @unique
user User @relation(fields: [userId], references: [id])
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
createdAt DateTime @default(now())
authorId Int
author User @relation(fields: [authorId], references: [id])
tags Tag[]
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
enum Role {
USER
ADMIN
MODERATOR
}
Understanding Schema Syntax
The syntax is small. These are the parts you'll use constantly:
- Field types:
Int,String,Boolean,DateTime,Float,Json, and more. Append?to make a field optional, or[]to make it an array (for relations). - Attributes:
@idmarks the primary key,@uniqueenforces uniqueness,@default()sets a default value,@relationdefines foreign key relations. - Auto-generated values:
@default(autoincrement())for integer IDs,@default(uuid())for UUID IDs,@default(now())for timestamps,@updatedAtto auto-update timestamps. - Relations: One-to-one, one-to-many, and many-to-many relationships are declared directly in the schema. For implicit many-to-many (like
PostandTagabove), Prisma creates and manages the join table for you.
One gotcha: after editing the schema you need to regenerate the client. If you skip it, TypeScript keeps using the old types, and if the database has moved ahead you'll see errors like The column `Post.slug` does not exist in the current database at runtime. migrate dev regenerates for you; after a plain git pull, run npx prisma generate yourself.
Block-Level Attributes
model Post {
id Int @id @default(autoincrement())
title String
slug String
authorId Int
// Composite unique constraint (slug must be unique per author)
@@unique([authorId, slug])
// Composite index for fast querying
@@index([authorId, createdAt])
// Custom table name
@@map("blog_posts")
}
Querying with Prisma Client
Once the schema is migrated, you query through the generated client. Return types follow your include and select options, so you don't write type annotations for results.
Create one PrismaClient and reuse it. Each instance opens its own connection pool, and in Next.js dev mode hot reloading can create a new one on every change until Postgres starts refusing with too many connections. The usual fix is to stash the instance on globalThis in development.
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Find all published posts with author name
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: { select: { name: true, email: true } } },
orderBy: { createdAt: 'desc' },
take: 10, // LIMIT 10
skip: 0, // OFFSET 0
})
// Find a single user by unique field
const user = await prisma.user.findUnique({
where: { email: 'mayur@example.com' },
include: { posts: true, profile: true },
})
// Find first matching record
const admin = await prisma.user.findFirst({
where: { role: 'ADMIN' },
})
// Aggregations
const stats = await prisma.post.aggregate({
_count: { id: true },
_sum: { viewCount: true },
_avg: { viewCount: true },
where: { published: true },
})
// Create a single user
const user = await prisma.user.create({
data: {
email: 'jane@example.com',
name: 'Jane Smith',
role: 'USER',
// Create nested profile in one query
profile: {
create: { bio: 'Full stack developer' },
},
},
})
// Create multiple records at once
await prisma.post.createMany({
data: [
{ title: 'First Post', authorId: user.id, published: true },
{ title: 'Second Post', authorId: user.id, published: false },
],
skipDuplicates: true, // Ignore conflicts
})
// Upsert: create or update
const tag = await prisma.tag.upsert({
where: { name: 'TypeScript' },
update: {}, // Nothing to update if it exists
create: { name: 'TypeScript' },
})
// Update a record by unique field
const updatedUser = await prisma.user.update({
where: { id: 1 },
data: { name: 'Updated Name', role: 'ADMIN' },
})
// Update nested relations
await prisma.user.update({
where: { id: 1 },
data: {
profile: {
upsert: {
create: { bio: 'New bio' },
update: { bio: 'Updated bio' },
},
},
posts: {
// Connect existing tags to a post
update: {
where: { id: 5 },
data: { published: true, viewCount: { increment: 1 } },
},
},
},
})
// Update many records matching a condition
await prisma.post.updateMany({
where: { authorId: 1, published: false },
data: { published: true },
})
// Delete a single record
await prisma.user.delete({
where: { id: 1 },
})
// Delete many records
const { count } = await prisma.post.deleteMany({
where: {
published: false,
createdAt: { lt: new Date('2025-01-01') },
},
})
console.log(`Deleted ${count} old drafts`)
// Soft delete pattern (no native Prisma support, done manually)
await prisma.user.update({
where: { id: 1 },
data: { deletedAt: new Date() },
})
Advanced Filtering and Sorting
Each field type gets its own set of filter operators in where, and you can combine them with AND, OR and NOT. You can also filter on related records, like the author's role below.
const results = await prisma.post.findMany({
where: {
AND: [
{ published: true },
{
OR: [
{ title: { contains: 'TypeScript', mode: 'insensitive' } },
{ content: { startsWith: 'Learn' } },
],
},
{
author: {
role: { in: ['ADMIN', 'MODERATOR'] },
},
},
{
viewCount: { gte: 100 }, // Greater than or equal
createdAt: { gt: new Date('2025-01-01') }, // After date
},
],
NOT: { title: { contains: 'draft' } },
},
orderBy: [
{ viewCount: 'desc' },
{ createdAt: 'desc' },
],
select: {
id: true,
title: true,
viewCount: true,
author: { select: { name: true } },
},
})
Migrations with Prisma Migrate
Prisma Migrate compares your schema with the last migration and writes the difference as a plain SQL file. You commit those files, and every environment (dev, staging, production) applies the same ones in the same order.
# Development: create and apply a new migration
npx prisma migrate dev --name add_user_profile
# This command:
# 1. Detects changes in schema.prisma
# 2. Creates prisma/migrations/20260615_add_user_profile/migration.sql
# 3. Applies the migration to your dev database
# 4. Regenerates Prisma Client automatically
# Production: apply pending migrations without prompts
npx prisma migrate deploy
# Reset your dev database (drops all data)
npx prisma migrate reset
# Check migration status
npx prisma migrate status
# Generate client after pulling schema from existing DB
npx prisma db pull # Introspect existing DB → schema.prisma
npx prisma generate # Generate client from schema
Never run prisma migrate dev or prisma migrate reset in production. migrate dev can ask to reset the database when it detects drift, and reset drops everything. Use prisma migrate deploy instead: it only applies pending migration files and never prompts. Keep in mind that a migration you wrote yourself (like dropping a column) can still lose data, so run it against staging first.
What a Generated Migration Looks Like
-- CreateTable
CREATE TABLE "Profile" (
"id" SERIAL NOT NULL,
"bio" TEXT,
"avatar" TEXT,
"userId" INTEGER NOT NULL,
CONSTRAINT "Profile_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId");
-- AddForeignKey
ALTER TABLE "Profile"
ADD CONSTRAINT "Profile_userId_fkey"
FOREIGN KEY ("userId")
REFERENCES "User"("id")
ON DELETE RESTRICT ON UPDATE CASCADE;
Advanced Prisma Features
Transactions
There are two forms. You can pass an array of queries, which run in order inside one transaction, or pass a callback that gets a transaction client. Use the callback when you need to read something and decide what to do next. Keep it short, though: interactive transactions hold a connection and time out after 5 seconds by default, so don't call external APIs inside one.
// Transfer credits between users atomically
const [debit, credit] = await prisma.$transaction([
prisma.user.update({
where: { id: senderId },
data: { credits: { decrement: amount } },
}),
prisma.user.update({
where: { id: receiverId },
data: { credits: { increment: amount } },
}),
])
// Interactive transaction with conditional logic
const result = await prisma.$transaction(async (tx) => {
const sender = await tx.user.findUnique({ where: { id: senderId } })
if (!sender || sender.credits < amount) {
throw new Error('Insufficient credits')
}
await tx.user.update({
where: { id: senderId },
data: { credits: { decrement: amount } },
})
await tx.user.update({
where: { id: receiverId },
data: { credits: { increment: amount } },
})
return { success: true }
})
// If an error is thrown, the entire transaction is rolled back
Prisma Middleware
Middleware runs around every query, which makes it a good place for logging, soft-delete filtering or audit trails. Note that $use is deprecated and has been removed in recent Prisma versions; on a current release you'd write the same thing as a Client extension with $extends and its query component. The idea is the same.
const prisma = new PrismaClient()
// Log slow queries automatically
prisma.$use(async (params, next) => {
const before = Date.now()
const result = await next(params)
const after = Date.now()
const duration = after - before
if (duration > 500) {
console.warn(
`Slow query detected: ${params.model}.${params.action} took ${duration}ms`
)
}
return result
})
// Soft-delete middleware: filter deleted records transparently
prisma.$use(async (params, next) => {
if (params.model === 'User') {
if (params.action === 'findMany' || params.action === 'findFirst') {
params.args.where = {
...params.args?.where,
deletedAt: null, // Automatically exclude soft-deleted users
}
}
}
return next(params)
})
Prisma Studio
For a quick look at your data in the browser during development, run:
npx prisma studio
# Opens at http://localhost:5555
# Browse tables, filter records, create/update/delete rows
# No SQL required, handy for teammates who don't write queries
Prisma vs Other ORMs
Switching ORMs later is painful, so it's worth comparing up front. Here's how Prisma lines up against the other common Node.js options:
| Feature | Prisma | Sequelize | TypeORM | Mongoose |
|---|---|---|---|---|
| Type Safety | Auto-generated, fully typed | Manual / partial | Decorator-based | Partial (requires Typegoose) |
| Schema Definition | Declarative .prisma file | JavaScript models | TypeScript decorators | JavaScript schemas |
| Migrations | Built-in, tracked | Built-in (manual) | Built-in (auto-sync risky) | None (schemaless) |
| Query API | Fluent, type-safe | Method chaining | Query Builder / Repo | Mongoose query API |
| Relations | Nested queries (include) | Eager / lazy loading | Eager / lazy loading | populate() |
| Raw SQL | $queryRaw, $executeRaw | sequelize.query() | query() / getRepository() | N/A (MongoDB) |
| Learning Curve | Low (schema-first) | Medium | High (decorators) | Low (MongoDB-native) |
| Database Support | PG, MySQL, SQLite, MSSQL, MongoDB | PG, MySQL, SQLite, MSSQL, Oracle | PG, MySQL, SQLite, MSSQL, Oracle | MongoDB only |
When to Choose Prisma
- New TypeScript projects: Generated types catch typos in field names and wrong relation shapes at compile time.
- Teams with mixed skill levels: One readable schema file is easier to review than models spread across decorators or JS classes.
- Projects where schema changes are frequent: Tracked migration files make it harder for environments to drift apart.
- When editor support matters to you: Autocomplete on queries is one of the best I've used in any ORM.
Raw SQL with Prisma
For CTEs, window functions or database-specific features, the query API won't be enough. Prisma gives you two escape hatches:
// Type-safe raw query (returns typed results)
const users = await prisma.$queryRaw<User[]>`
SELECT u.*, COUNT(p.id) as post_count
FROM "User" u
LEFT JOIN "Post" p ON p."authorId" = u.id
WHERE u."createdAt" > ${new Date('2025-01-01')}
GROUP BY u.id
ORDER BY post_count DESC
`
// Execute without return value (DDL, UPDATE, DELETE)
const result = await prisma.$executeRaw`
UPDATE "Post"
SET "viewCount" = "viewCount" + 1
WHERE id = ${postId}
`
console.log(`${result} rows affected`)
Because these are tagged templates, interpolated values are sent as parameters, not pasted into the SQL. That protection goes away with $queryRawUnsafe, so never pass user input into it as a string. Also note the generic on $queryRaw is a type assertion; Prisma doesn't check it against the actual columns.
When I'd Use Prisma (and When I Wouldn't)
For a new TypeScript API with a fairly normal relational schema, Prisma is my default. The generated types, the migration files in the repo and nested writes cover most of what a CRUD backend needs, and $queryRaw handles the rest.
Where It Gets in the Way
- SQL-heavy workloads: If most of your queries are reporting with CTEs, window functions or complex joins, you'll live in
$queryRawand lose the type safety that was the point. A query builder like Kysely or Drizzle fits better there. - Existing databases with odd conventions:
db pullworks, but you'll spend time adding@mapand@@mapeverywhere, and features the schema language doesn't model (some triggers, check constraints, partial indexes on older versions) have to live in hand-edited migrations. - Serverless and edge: Lots of short-lived functions each opening a pool can exhaust database connections. Plan for a pooler (PgBouncer, Prisma Accelerate or your provider's pooler) before launch, not after.
- Overfetching by default:
includereturns every column of the related model. On wide tables, useselectfor the fields you actually render.
Before going to production, check three things: the deploy pipeline runs prisma migrate deploy (not migrate dev), prisma generate runs during the build so the client matches the schema, and your connection limit fits what the database allows across every running instance.