NestJS: Prisma Transaction with Repositories

Richang Sharma
4 min readJan 31, 2024

So we almost always stumble a situation in software development when we need to create a database transaction. Database transactions help us ensure that any database operation only gets committed when all the related operations are successful, otherwise, we roll back any changes in the database.

Such a situation arose when I was working with NestJS with Prisma as my ORM. I was following the standard architecture of keeping repositories, services, and controllers to execute requests. Now Prisma on its own does provide transaction support, but doing transactions inside a request where there are multiple service methods to be executed in conjunction as a transaction is not at all suitable in Prisma for some reason. While researching I found this can be solved by using AsyncLocalStorage, to somehow carry over the transaction context throughout the callback/function stack lifecycle. And the best way to do it was the NestJS-CLS.

Nest-CLS module supports a Prima transactional plugin that allows us to create a middleware that can carry a transaction context throughout an individual call stack lifecycle. This article will try to explain how to achieve it. TLDR;

We set up a NestJs app with Prisma installed using SQL-lite as our database.

Initial Setup

--

--