You need to mass the query manager to the services, and use it to execute operations, instead of the injected repository. See https://orkhan.gitbook.io/typeorm/docs/transactions#using-queryrunner-to-create-and-control-state-of-single-database-connection for an example of using the manager. Answer from ccb621 on reddit.com
🌐
Medium
medium.com › @dev.muhammet.ozen › advanced-transaction-management-with-nestjs-typeorm-43a839363491
Advanced Transaction Management with NestJS & TypeORM | by Muhammet Özen | Medium
September 17, 2023 - As I stated above, this is a simple approach where we create a query runner, get a connection, start a transaction, and execute all queries over that query runner. Imagine we have two TypeORM entities as Order and Item .
🌐
Reddit
reddit.com › r/nestjs › how can i use transactions with typeorm across multiple services
r/nestjs on Reddit: How can I use transactions with typeorm across multiple services
January 21, 2024 -

This is my current code, it supposed to start a transaction in the update method that used other services.

  async update(authContext: AuthContext, id: string, updatePortfolioDto: UpdatePortfolioDto, isSaved = false): Promise<Portfolio> {

    const queryRunner = this.dataSource.createQueryRunner();

  await queryRunner.connect();
  await queryRunner.startTransaction();
  try{
    await this.sleeveService.deleteForPortfolio(authContext, id);
    const updatedPortfolio = this.portfoliosRepository.update(id, portfolio);
    await queryRunner.commitTransaction();
    return updatedPortfolio

  }catch(err){
    await queryRunner.rollbackTransaction();
  }finally{
    await queryRunner.release();
  }
  }

As you can see, I am calling a method from another sevice and repository.

For example deleteForPortfolio method in the sleeveservice is

export class TypeOrmSleeveRepository implements ISleevesRepository {
  private readonly logger = new Logger(TypeOrmSleeveRepository.name);

  constructor(@InjectRepository(Sleeve) private readonly sleeveRepository: Repository<Sleeve>) {}

  deleteForPortfolio(authContext: AuthContext, portfolioId: string) {
    this.sleeveRepository
      .createQueryBuilder('sleeve')
      .delete()
      .where('sleeve.portfolioId = :portfolioId', { portfolioId })
      .andWhere('sleeve.tenantId = :tenantId', { tenantId: authContext.tenantId })
      .execute();
  }
}

and the portfolio update method is

  async update(id: string, portfolio: Portfolio): Promise<Portfolio> {
    try {
      const updatedPortfolio = await this.portfolioRepository.preload({
        id,
        ...portfolio
      });

      if (!updatedPortfolio) {
        this.logger.warn(`Portfolio with ID ${id} not found`);
        throw new NotFoundException(`Portfolio with ID ${id} not found`);
      }
      const savedPortfolio = await this.portfolioRepository.save(updatedPortfolio);
      this.logger.log(`Updated Portfolio with ID ${id}`);
      return savedPortfolio;
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      this.logger.error(`Error updating portfolio with ID ${id}: ${error.message}`, error.stack);
      throw error;
    }
  }

Currently my code does not work. How can I fix this please ?

Discussions

how to use transaction across service in nestjs with typeorm - Stack Overflow
How can I have a transaction across different service in my project? I try my code as below but the transaction doesn't rollback while exception threw. The following code will rollback as expected... More on stackoverflow.com
🌐 stackoverflow.com
Support transaction per request with TypeORM
We would like to make all TypeORM database operations during a certain request/endpoint transactional. Based on typeorm/typeorm#404 (comment) we could create a transactional entity manager and pass it around to all our services, but that doesn't feel very nestjs like. More on github.com
🌐 github.com
12
April 12, 2018
Why I built typeorm-transactional-decorator
well, there’re reasons why it’s not included in official typeorm packages. i haven’t looked into your code, but i bet there will be shit tons of problems with edge cases. different propagation mechanisms also will lead to lots of problems. check this one out: https://github.com/Aliheym/typeorm-transactional it started with cls-hooked and then switched to AsynLocalStorage when it got introduced to Node. but it has never been adopted across community because of many underlying issues. in any case, good luck! More on reddit.com
🌐 r/nestjs
3
15
September 14, 2025
How can I use transactions with typeorm across multiple services
You need to mass the query manager to the services, and use it to execute operations, instead of the injected repository. See https://orkhan.gitbook.io/typeorm/docs/transactions#using-queryrunner-to-create-and-control-state-of-single-database-connection for an example of using the manager. More on reddit.com
🌐 r/nestjs
5
3
January 21, 2024
🌐
Better Programming
betterprogramming.pub › handling-transactions-in-typeorm-and-nest-js-with-ease-3a417e6ab5
Handling Transactions in TypeORM and Nest.js With Ease | by Dmitry Shamshurin | Better Programming
April 6, 2022 - Use decorators to control the transaction (@Transaction() and @TransactionManager()), which is not recommended by the Nest.js docs. Include some 3rd party library like typeorm-transactional-cls-hooked (which is based on this cool “Continuation Local Storage” concept) or nest_transact.
🌐
Aaron Boman
aaronboman.com › programming › 2020 › 05 › 15 › per-request-database-transactions-with-nestjs-and-typeorm
Per-Request Database Transactions with NestJS and TypeORM – Aaron Boman
July 12, 2024 - NestJS provides a very powerful dependency injection mechanism that allows us to create a new transaction, scoped by request and then allow for other services to create repositories using the current transaction EntityManager if set so that large blocks of business logic can be executed atomically. Thanks very much for posting this. I had been looking for a solution to transactions with Nest & TypeORM for ages.
🌐
DEV Community
dev.to › alphamikle › the-easiest-way-to-use-transactions-in-nest-js-41h0
The easiest way to use transactions in Nest.js - DEV Community
February 13, 2021 - Thus, we come to the conclusion that in order to be able to use transactions in Nest when using TypeORM, it is necessary to pass the connection class into the controller / service constructor, for now we just remember this.
Find elsewhere
🌐
Medium
medium.com › @neerajsonii › ninja-way-of-handling-database-transactions-with-typeorm-in-nestjs-be95241b24d9
Ninja way of handling Database Transactions with Typeorm in NestJs. | by Neeraj Soni | Medium
December 19, 2022 - A transaction class will create a transaction object and return. import { DataSource } from 'typeorm'; export class DbTransaction { private queryRunner = DataSource.createQueryRunner(); constructor() {} async start(): Promise<TransactionRunner> { return this.queryRunner.connect(); } async commitTransaction(): Promise<void> { return this.queryRunner.commitTransaction(); } async rollbackTransaction(): Promise<void> { return this.queryRunner.rollbackTransaction(); } async release(): Promise<void> { return this.queryRunner.release(); } }
🌐
GitHub
github.com › alphamikle › nest_transact
GitHub - alphamikle/nest_transact: Simplest transactions support for Nestjs with Typeorm · GitHub
Simplest transactions support for Nestjs with Typeorm - alphamikle/nest_transact
Starred by 119 users
Forked by 20 users
Languages   TypeScript 94.9% | Shell 3.1% | JavaScript 1.9% | Dockerfile 0.1%
🌐
Medium
medium.com › @testjokerqwerty › integrating-typeorm-transactional-in-your-nest-js-project-a-step-by-step-guide-26d2093ef1b5
Integrating TypeORM-Transactional in Your Nest.js Project: A Step-by-Step Guide | by Eugene Moskalenko | Medium
November 27, 2024 - 3. Configure TypeORM Using @nestjs/config: Create a configuration file (e.g., typeorm.config.ts) to register the TypeORM configuration with @nestjs/config:
🌐
HackerNoon
hackernoon.com › the-most-convenient-ways-of-writing-transactions-within-the-nestjs-typeorm-stack-3q3q33jd
The Most Convenient Ways of Writing Transactions Within the Nest.js + TypeORM Stack | HackerNoon
February 28, 2021 - // ... SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User"."defaultPurseId" AS "User_defaultPurseId" FROM "user" "User" WHERE "User"."id" IN ($1) START TRANSACTION UPDATE "purse" SET "balance" = $2 WHERE "id" IN ($1) COMMIT SELECT "Purse"."id" AS "Purse_id", "Purse"."balance" AS "Purse_balance", "Purse"."userId" AS "Purse_userId" FROM "purse" "Purse" WHERE "Purse"."id" IN ($1) START TRANSACTION UPDATE "purse" SET "balance" = $2 WHERE "id" IN ($1) COMMIT · By the way - I did not write this request by hand, but pulled it out of the ORM logs, but it reflects the essence. Everything is pretty simple and straightforward. To build the queries, TypeORM was used, which we will return to a little later.
🌐
Medium
medium.com › @alperenergul49 › understanding-typeorm-transactions-a-step-by-step-guide-with-nest-js-f682b63b514a
Understanding TypeORM Transactions: A Step-by-Step Guide with Nest.js | by Alperen Ergul | Oct, 2024 | Medium | Medium
March 21, 2025 - Using the response we received from the previous database transaction, save the other necessary information to the UserDetailEntity table with other information. First, we create a nest.js project. ... We import nestjs/config to be able to use the .env file.
🌐
Medium
medium.com › @jsankit99 › transaction-management-in-nestjs-typeorm-3-3-the-transactional-decorator-7fd60466b8a4
Transaction Management in NestJS + TypeORM (3/3): The @Transactional Decorator | by Ankit Pradhan | Medium
January 28, 2026 - @Injectable() export class OrderService { @Transactional() async createOrder(userId: string, items: OrderItem[]) { const order = await this.orderRepo.save({ userId, items }); await this.inventoryService.reserveItems(items); return order; } } Much cleaner! That’s what we’re building. import { SetMetadata } from '@nestjs/common'; import { IsolationLevel } from 'typeorm/driver/types/IsolationLevel'; // Metadata key used to identify transactional methods export const TRANSACTIONAL_KEY = Symbol('TRANSACTIONAL_METHOD'); /** * Marks a method as transactional.
🌐
Medium
medium.com › @jsankit99 › transaction-management-in-nestjs-typeorm-2-3-clean-repository-layer-e904b9146800
Transaction Management in NestJS + TypeORM (2/3): Clean Repository Layer | by Ankit Pradhan | Medium
January 28, 2026 - Full TypeORM API access - All methods work automatically · Transaction-aware by default - Respects active transactions seamlessly · Custom methods supported - Add business logic without friction · Type-safe - Full IDE autocomplete and type checking ... Combined with Part 1’s DbTransactionService and DbTransactionContext, you now have a complete, production-ready transaction management solution for NestJS + TypeORM.
🌐
NestJS
docs.nestjs.com › techniques › database
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-i-harnessed-transactions-in-nestjs-with-typeorm-without-a-headache-e901aee7aff7
How I Harnessed Transactions in NestJS with TypeORM Without a Headache | JavaScript in Plain English
March 24, 2024 - A big challenge came up when I looked into using NestJS's interceptor layer, which only works for the Controller layer. This meant that every time a request was made, a transaction would start. This wasn't efficient and added too many restrictions.
🌐
GitHub
github.com › nestjs › nest › issues › 560
Support transaction per request with TypeORM · Issue #560 · nestjs/nest
April 12, 2018 - Keeping in mind that custom repositories should not be singleton services and it is likely transaction decorators will be removed from TypeORM core. ... @Controller("/user") export class UserController { constructor( private userService: UserService, ) {} @Post("/") @Transaction() async createNewUser(@Body() body: UserDTO) { return await this.userService.createNewUser(body); } }
Author   nestjs
🌐
YouTube
youtube.com › watch
How to write TypeORM Transactions with Nest JS (Nest JS Advanced Course) #15 - YouTube
Hi Everyone, 🔥 This Video is a part of the Playlist "Nest JS Advanced Course 2023" and we are covering all advanced things from nestjs Playlist https://www....
Published   July 18, 2023
🌐
Reddit
reddit.com › r/nestjs › why i built typeorm-transactional-decorator
r/nestjs on Reddit: Why I built typeorm-transactional-decorator
September 14, 2025 -

I got tired of threading the EntityManager/QueryRunner through every layer of a modular NestJS backend—passing it as a parameter into every service and method. It was noisy, brittle, and honestly, a pain. I went hunting for a decorator-based solution for TypeORM transactions. I found a few, tried them, but they felt overconfigured and, crucially, the same transaction didn’t reliably propagate into deeply nested calls. Maybe I misused them—but the DX wasn’t there.

So I built typeorm-transactional-decorator: a small, focused layer that uses Node’s async hooks to carry a transactional context and patches TypeORM’s DataSource/EntityManager so repositories automatically bind to the current transaction if one exists. You get a dead-simple @Transactional decorator, @IgnoreTransaction to opt out where needed, reliable propagation into nested methods, automatic rollback on errors, and a TransactionResultManager to register side effects for onCommit/onRollback (think: delete an S3 file if the DB transaction fails). It’s based on typeorm-transactional, but simplified and tuned for a predictable, minimal workflow.

It slots neatly into NestJS via TypeOrmModule’s dataSourceFactory, or you can call addTransactionalDataSource(dataSource) in any Node app. The package grows as my needs evolve, but the north star is the same: minimal API, maximum ergonomics for real-world, layered architectures.

How are you handling TypeORM transactions?

NPM: https://www.npmjs.com/package/typeorm-transactional-decorator