Prisma is a modern TypeScript ORM that makes database interactions type-safe and intuitive. NestJS is a powerful Node.js framework built for scalability and modularity. Together, they form a clean, type-safe backend stack.
🧠 Why Prisma + NestJS?
NestJS is a powerful, modular backend framework built with TypeScript. Prisma is a next-gen ORM that makes database access easy, type-safe, and scalable.
Together, they offer:
- ✅ Full TypeScript support
- ✅ Auto-generated types for DB models
- ✅ Fast and readable queries
- ✅ Modular, maintainable code structure
- ✅ Support for PostgreSQL, MySQL, SQLite & more
⚙️Installing and Setting Up Prisma in a NestJS Project
npm install prisma --save-dev
npm install @prisma/client
npx prisma init
- Creates prisma/schema.prisma
- Configure your database URL in .env
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
Basic Folder Structure
src/
├── app.module.ts
├── user/
│ ├── user.module.ts
│ ├── user.service.ts
│ ├── user.controller.ts
│ └── user.entity.ts
└── prisma/
├── prisma.module.ts
└── prisma.service.ts
Creating Your First Model
Inside prisma/schema.prisma
:
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}
npx prisma migrate dev --name init
Generating Prisma Client & Using It
Create a PrismaService to inject Prisma client throughout the app.
// prisma.service.ts
import { Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient {
constructor() {
super();
}
}
Creating a User Service with CRUD
// user.service.ts
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
create(data: CreateUserDto) {
return this.prisma.user.create({ data });
}
findAll() {
return this.prisma.user.findMany();
}
findOne(id: number) {
return this.prisma.user.findUnique({ where: { id } });
}
update(id: number, data: UpdateUserDto) {
return this.prisma.user.update({ where: { id }, data });
}
delete(id: number) {
return this.prisma.user.delete({ where: { id } });
}
}
Using DTOs for Type Safety
// create-user.dto.ts
export class CreateUserDto {
name: string;
email: string;
}
Bonus Tips from Real Projects
- ✅ Always validate inputs with class-validator
- ✅ Use guards for role-based access (RBAC)
- ✅ Write custom Prisma middleware (e.g., for soft deletes)
- ✅ Use select & include for fine-grained queries
- ✅ Combine with Swagger for clean API documentation
Wrap-Up
Prisma and NestJS together make backend development clean, fast, and scalable. Once you get the structure right, it’s a smooth ride 🚀