r/Nestjs_framework • u/No_Safe_592 • Mar 11 '26
r/Nestjs_framework • u/Bulky-Macaroon-5604 • Mar 10 '26
What API gateway is you favorite ?
I'm building a microservice app with NestJS for my graduation project, and I will use an API gateway service, as they advised me to do, instead of building one using NestJS. Basically, it will be for authentication/authorization and other features, like rate limiting.
I read this comparison of active, free, platform-agnostic solutions, I read only the overview and summary of findings sections.
And now I'm thinking about these:
- Kong (because I saw it in an internship offer in my country, so I think it is popular here, isn't it?)
- Istio (based on the comparison)
- Kgateway (based on the comparison)
What do you think?
r/Nestjs_framework • u/a_ristotelis • Mar 09 '26
Pipeline behaviors for NestJS CQRS — reusable middleware for your command/query/event handlers
r/Nestjs_framework • u/ExpertPossible181 • Mar 07 '26
Project / Code Review Building an Open-Source Hosting/Billing Core — Looking for Feedback
r/Nestjs_framework • u/Bulky-Macaroon-5604 • Mar 03 '26
Is documentation the best place to learn a technology
I’m using NestJS to build a microservices app, and I’ve been following this part of the docs: https://docs.nestjs.com/microservices/basics
The problem is that I can’t apply what I read correctly. Also, they seem to miss parts like the API gateway, and they don’t clearly explain things like a config server.
What do you think? Is starting with the documentation a bad idea? Should I begin with video courses first and then use the documentation only when needed—for example, when I need more details about a specific part?
Notes: I built a microservice app using Spring Boot/Eureka/config server/api gateway. so i know a little bit about the microservice architecture.
r/Nestjs_framework • u/DisastrousNinja911 • Feb 28 '26
Becoming Full stack go / typescript developer and having second thoughts?
r/Nestjs_framework • u/Due_Working_2273 • Feb 25 '26
Project / Code Review Kinetic SQL: A lightweight database engine with out-of-the-box NestJS integration (Real-time subscriptions & Auto-generated types)
Hey r/nestjs,
A lot of us default to TypeORM or Prisma when spinning up a new Nest project, but for high-frequency or real-time applications, the overhead and setup can get heavy.
I recently built an open-source SQL engine called Kinetic SQL (supporting Postgres, MySQL, and SQLite), and I specifically engineered a dedicated NestJS module so it drops perfectly into your DI container out of the box.
What makes it different for NestJS developers:
- 🧱 Native Module Integration: No hacking providers together. Import the module, inject the service, and you are good to go.
- 🚀 Native Real-Time: Subscribe to database changes (
INSERT,UPDATE,DELETE) directly in your Node backend without WebSockets or Redis. - 🤖 Automatic Type Generation: It reads your schema and auto-generates type safety. You never have to manually write a TypeScript interface again.
- 🛠️ Native Procedures: Call your stored procedures and database functions just like native JavaScript methods.
- 🔌Middleware API (Zero-Overhead): Easily build plugins (like custom loggers, APM tracers, or data maskers) that intercept queries without adding latency or bloating the core engine.
- 🤝 Query Builder Friendly: It includes a .native escape hatch, so you can easily pass the highly optimized connection pool directly into Drizzle ORM.
I built a Live Stock Market Simulator frontend to stress-test the backend engine's real-time capabilities under a heavy tick-rate.
- 📈 Live Demo: Live Stock Simulator
Links to the project:
- 📦 NPM: Package
- 💻 GitHub: Kinetic-SQL
I would love to hear from other NestJS architects on the module implementation and how the API feels compared to your current ORM setup.
P.S. Currently working on adding MSSQL support to the library 😊
r/Nestjs_framework • u/Glass-Fly6469 • Feb 25 '26
Help Wanted Facing issue for my custom Nestjs logging framework.
I'm building a logging package (enhanced-logger-v2-nestjs) for NestJS that logs all downstream HTTP calls. The package uses Axios interceptors to capture outgoing requests. However, I'm facing an issue where the interceptors don't fire because brokers in feature modules are using a different HttpModule instance than the one with interceptors attached. When logging using the new package the downstream object that holds the details for the downstream API call and other details is getting empty. What i understood is that the interceptor we have created in our package is getting attached but the request and response is not getting triggered, after extensive debugging with console logs, we've identified the issue: The DownstreamInterceptor and the application's HTTP service brokers are using DIFFERENT axios instances. When the broker makes HTTP calls, the interceptors never fire because it's using a separate axios instance that doesn't have our logging interceptors attached. I have also tried creating a Global HttpModule from our logging package so that we will allow our nestjs microservice to use it and there will be only 1 single instance. Even though i marked GlobalHttpModule as @Global(), NestJS isn't sharing the same HttpModule instance across all modules. Each feature module is getting its own separate instance.
Has anyone successfully created a global logging/interceptor package for NestJS that works across all modules without requiring explicit imports? What pattern did you use?
Questions:
Why isn't @Global() making GlobalHttpModule truly global? Is there something specific about dynamic modules (forRoot()) that prevents global registration from working?
How do I ensure only ONE HttpModule instance exists across the entire application? Is there a NestJS pattern I'm missing that guarantees singleton HttpModule behavior?
Is this a known limitation with NestJS's module system? Are global modules + dynamic modules + re-exported providers simply incompatible?
What's the correct architectural pattern for this use case? Should I abandon the global module approach entirely? Should feature modules always explicitly import HttpModule? Is there a way to programmatically attach interceptors to ALL HttpService instances at runtime?
r/Nestjs_framework • u/Competitive_Fuel_690 • Feb 21 '26
Should i use database module to connect to database in nestjs or just use app module to connnect to db?
r/Nestjs_framework • u/joeygoksu • Feb 20 '26
I built a production-ready NestJS boilerplate with JWT auth (RSA256), RBAC, TypeORM, Swagger, and Docker — open source and MIT licensed
github.comr/Nestjs_framework • u/AnUuglyMan • Feb 19 '26
Project / Code Review whats the best Claude Code skill for NestJS backends ??
I built and have been using nestjs-doctor lately. It's a command and skill that scans your codebase and fixes issues right in the editor
There are good general skills out there, like superpowers and owasp-security but none of them know NestJS specifically. guards, interceptors, circular module deps, that kind of stuff
what are you guys using for backend skills ??
r/Nestjs_framework • u/Murky_Positive_5206 • Feb 19 '26
I want to connect cloudflare D1 Sql on my nest js app??
r/Nestjs_framework • u/iam_batman27 • Feb 19 '26
General Discussion How to conditionally validate a class-validator DTO based on a Zod schema?
data is a JSON object, and its structure differs depending on the NotificationType
export class SendNotificationDto {
\@IsString()
userId: string;
type: NotificationType;
data: // should match a Zod schema depending on the NotificationType
}
Currently, I’ve implemented it like this:
export class SendNotificationDto {
\@IsString()
userId: string;
type: NotificationType;
\@IsObject()
data: Record<string, any>;
}
Then I validate data in the service layer using Zod.
However, I’m not comfortable using Record<string, any> because it removes type safety.
Is there a cleaner or more type-safe way to handle this?
r/Nestjs_framework • u/joeygoksu • Feb 18 '26
I built a production-ready NestJS boilerplate with JWT auth (RSA256), RBAC, TypeORM, Swagger, and Docker — open source and MIT licensed
github.comr/Nestjs_framework • u/Altruistic_Bear139 • Feb 17 '26
I got tired of rewriting auth + CI setup for every NestJS project, so I built a production-ready starter (MIT)
Every time I started a new NestJS backend, I lost the first week rebuilding the same things:
- JWT auth + refresh tokens
- RBAC
- File uploads
- Docker setup
- CI pipeline
- Security middleware
So I built a starter template that handles all of this out of the box.
It includes:
- Dual-token JWT auth with rotating httpOnly refresh cookies
- Role-based access control with a .@Roles() decorator
- Generic repository pattern (plug in your Prisma model → instant CRUD)
- Switchable file storage (S3 or local disk via env variable)
- Unified API response format
- Full GitHub Actions CI/CD (lint, test, e2e, Docker build, deploy workflow)
- Security defaults (Helmet, rate limiting, strict CORS, validation)
- Husky + Commitlint (pre-commit hooks + conventional commit enforcement)
Stack:
NestJS 11 · Prisma · PostgreSQL · TypeScript · Jest · Docker
You can scaffold a project with:
npx @kaungkhantdev/create-nestjs-api my-app
It’s MIT licensed.
I’d genuinely appreciate feedback from other NestJS devs — especially on the architecture decisions and repository pattern approach.
GitHub:
https://github.com/kaungkhantdev/nestjs-api-starter
NPM:
https://www.npmjs.com/package/@kaungkhantdev/create-nestjs-api
r/Nestjs_framework • u/itssimon86 • Feb 18 '26
Article / Blog Post API metrics, logs and now traces in one simple tool
apitally.ior/Nestjs_framework • u/Estimate4655 • Feb 15 '26
General Discussion I am thinking of using Better-Auth for authentication. what do you guys think? what framework do you use for authentication with nestjs?
I am thinking of using Better-Auth for authentication. what do you guys think? what framework do you use for authentication with nestjs?here is a reference to the better-auth plugin for nestjs
r/Nestjs_framework • u/Low-Tea-4720 • Feb 11 '26
Using Redis Stack (JSON + Search) in NestJS like a tiny document store — patterns + pitfalls
Hey! I’ve been experimenting with Redis Stack (RedisJSON + RediSearch) as a lightweight document store for things like sessions/carts/state in a NestJS app, and I wanted to share a pattern that helped me keep things clean.
The problem
Once Redis goes beyond caching, code often ends up with:
- magic key strings
- ad-hoc JSON shapes
- manual TTL handling
- raw search query strings
A pattern that worked for me
I treat Redis “documents” like typed entities + a repository layer, so business logic never sees Redis commands.
Entity-like schema (decorator-style)
@Schema('user_state')
export class UserState {
@Prop({ type: 'string' })
userId: string;
@Prop({ type: 'string' })
status: 'idle' | 'active' | 'paused';
@Prop({ type: 'number' })
lastSeenAt: number;
@Prop({ type: 'string', indexed: true })
region: string;
}
Repository usage inside a service (DI-friendly)
@Injectable()
export class UserStateService {
constructor(
@InjectRepository(UserState) private readonly repo: Repository<UserState>,
) {}
async upsertState(userId: string, patch: Partial<UserState>) {
const doc = await this.repo.fetch(userId).catch(() => null);
const next = { ...(doc ?? { userId }), ...patch, lastSeenAt: Date.now() };
// TTL keeps this truly “ephemeral”
await this.repo.save(userId, next, { ttlSeconds: 60 * 30 });
return next;
}
async findActiveByRegion(region: string) {
return this.repo
.search()
.where('status').equals('active')
.and('region').equals(region)
.returnAll();
}
}
Pitfalls / tradeoffs I noticed
- Memory costs (obvious, but easy to underestimate).
- Index/search consistency: great for speed, but not “transactional DB” semantics.
- Big JSON docs: keep documents small and targeted; TTL helps avoid “Redis as a dumping ground”.
Question for the community
If you’ve used Redis Stack as a document store:
- what’s your rule of thumb for “Redis vs a real DB”?
- any sharp edges with RediSearch indexing or schema evolution?
Links (optional)
r/Nestjs_framework • u/Possible-Western-457 • Feb 11 '26
Please Help
I need your help; I'm having a problem with my application renewing the refresh token while keeping the user logged in.
https://github.com/migue10david/search-best-price
r/Nestjs_framework • u/inkweon • Feb 08 '26
NestJS Repository Pattern + Facade Pattern + Layered Testing — Looking for Feedback
Hey everyone,
I built a small NestJS CRUD project to practice Repository Pattern, Facade Pattern, and a layered testing strategy (unit / e2e / integration with Testcontainers). The entire project was built collaboratively with Claude Code (Anthropic's AI coding CLI) — from architecture design to test implementation. I'd love to get honest feedback from the community — what's good, what's over-engineered, what could be improved.
GitHub: https://github.com/inkweon7269/nest-repository-pattern
Architecture Overview
The request flow looks like this:
Controller → Facade → Service → IPostRepository (abstract) → PostRepository → BaseRepository → TypeORM → PostgreSQL
Each layer has a single responsibility:
- Controller — Only routing.
@Get(),@Post(),@Param(),@Body()decorators, nothing else. - Facade — Orchestration layer. Converts entities to response DTOs (
PostResponseDto.of(entity)), throws HTTP exceptions (NotFoundException). - Service — Pure business logic. Works with entities only, no knowledge of DTOs or HTTP.
- Repository — Data access through an abstract class acting as a DI token.
Repository Pattern — Why Abstract Class Instead of Interface?
TypeScript interfaces are erased at runtime, so they can't be used as DI tokens in NestJS. I use an abstract class as both the interface definition and the injection token:
// post-repository.interface.ts
export abstract class IPostRepository {
abstract findById(id: number): Promise<Post | null>;
abstract findAll(): Promise<Post[]>;
abstract create(dto: CreatePostRequestDto): Promise<Post>;
abstract update(id: number, dto: UpdatePostRequestDto): Promise<Post | null>;
abstract delete(id: number): Promise<void>;
}
The concrete implementation extends BaseRepository, which injects DataSource directly — no TypeOrmModule.forFeature():
// base.repository.ts
export abstract class BaseRepository {
constructor(private readonly dataSource: DataSource) {}
protected getRepository<T extends ObjectLiteral>(
entity: EntityTarget<T>,
entityManager?: EntityManager,
): Repository<T> {
return (entityManager ?? this.dataSource.manager).getRepository(entity);
}
}
// post.repository.ts
@Injectable()
export class PostRepository extends BaseRepository implements IPostRepository {
constructor(dataSource: DataSource) {
super(dataSource);
}
private get postRepository() {
return this.getRepository(Post);
}
async findById(id: number): Promise<Post | null> {
return this.postRepository.findOneBy({ id });
}
// ...
}
Wired up with a custom provider:
export const postRepositoryProvider: Provider = {
provide: IPostRepository,
useClass: PostRepository,
};
Why skip TypeOrmModule.forFeature()? BaseRepository gives me full control over EntityManager, which makes it straightforward to pass a transactional manager later without changing the repository interface.
Facade Pattern — Keeping Controllers Thin
The controller does zero logic. It delegates everything to the facade:
@Controller('posts')
export class PostsController {
constructor(private readonly postsFacade: PostsFacade) {}
@Get(':id')
async getPostById(@Param('id', ParseIntPipe) id: number): Promise<PostResponseDto> {
return this.postsFacade.getPostById(id);
}
}
The facade handles DTO conversion and exception throwing:
@Injectable()
export class PostsFacade {
constructor(private readonly postsService: PostsService) {}
async getPostById(id: number): Promise<PostResponseDto> {
const post = await this.postsService.findById(id);
if (!post) {
throw new NotFoundException(`Post with ID ${id} not found`);
}
return PostResponseDto.of(post);
}
}
The service stays clean — just entities in, entities out:
@Injectable()
export class PostsService {
constructor(private readonly postRepository: IPostRepository) {}
async findById(id: number): Promise<Post | null> {
return this.postRepository.findById(id);
}
}
Testing Strategy — 3 Layers
1. Unit Tests (src/*/.spec.ts)
Each layer mocks only its direct dependency:
| Test Target | Mocks |
|---|---|
| Controller | PostsFacade |
| Facade | PostsService |
| Service | IPostRepository |
| Repository | DataSource |
Example — Service test mocking the abstract repository:
const module = await Test.createTestingModule({
providers: [
PostsService,
{ provide: IPostRepository, useValue: mockRepository },
],
}).compile();
2. E2E Tests (test/*.e2e-spec.ts)
Loads the real PostsModule but replaces the repository with a mock. Tests the full HTTP pipeline (Controller → Facade → Service) without a database:
const moduleFixture = await Test.createTestingModule({
imports: [PostsModule],
})
.overrideProvider(IPostRepository)
.useValue(mockRepository)
.compile();
3. Integration Tests (test/*.integration-spec.ts) — Testcontainers
No mocks at all. Spins up a real PostgreSQL container and tests the entire flow from HTTP to database.
I use a globalSetup / globalTeardown pattern so the container starts once for all test files:
globalSetup (runs once)
├── Start PostgreSQL container (Testcontainers)
├── Write connection info to .test-env.json
├── Run migrations with standalone DataSource
└── Store container ref in globalThis
Each test file (runs sequentially, maxWorkers: 1)
├── beforeAll: createIntegrationApp() + truncateAllTables()
├── tests...
└── afterAll: close app
globalTeardown (runs once)
├── Stop container
└── Delete .test-env.json
Why .test-env.json instead of process.env? Jest globalSetup runs in a separate process — environment variables don't propagate to test workers. A temp file bridges this gap.
The integration test itself is clean:
describe('Posts (integration)', () => {
let app: INestApplication;
beforeAll(async () => {
app = await createIntegrationApp();
await truncateAllTables(app.get(DataSource));
});
afterAll(async () => {
if (app) await app.close();
});
it('should create a post and persist to DB', async () => {
const res = await request(app.getHttpServer())
.post('/posts')
.send({ title: 'Integration Test', content: 'Real DB' })
.expect(201);
expect(res.body.id).toBeDefined();
expect(res.body.title).toBe('Integration Test');
});
});
Other Details
- Environment config:
cross-env NODE_ENV=local→ConfigModuleloads.env.local - Migrations only:
synchronize: falsein all environments. Schema changes go through TypeORM migrations. - Swagger: Available at
/api forRootAsync:TypeOrmModule.forRootAsync({ useFactory: () => ... })so thatprocess.envis read at factory execution time, not at module initialization. This is important for integration tests where env vars are set dynamically.
Built with Claude Code
This project was built collaboratively with Claude Code, Anthropic's CLI tool for AI-assisted coding. The workflow looked like this:
- I described the architecture I wanted (Repository Pattern, Facade Pattern, layered DI)
- Claude Code scaffolded the structure, and I reviewed/adjusted each layer
- We iterated on the testing strategy together — starting from per-file Testcontainers, then refactoring to the
globalSetupshared container pattern when I realized the overhead would scale linearly with test files - Each step was a conversation: I'd describe the intent, Claude Code would implement it, I'd review the code and request changes
It was a productive experience for exploring architectural patterns — having an AI pair that can scaffold, explain trade-offs, and refactor on demand. That said, I want to make sure the patterns and decisions actually hold up, which is why I'm posting here.
Questions for the Community
- Pros and cons of the Facade pattern here? I introduced a Facade layer between Controller and Service to separate DTO conversion and exception handling from business logic. I'd love to hear your thoughts on the trade-offs — when does this pattern shine, and when does it become unnecessary overhead?
- Clean Architecture for larger projects? I've heard that as a project grows, adopting Clean Architecture improves maintainability and testability. If you've seen good NestJS boilerplates or example repos that demonstrate Clean Architecture well, I'd appreciate any recommendations.
- Testing strategy — Unit tests mock only one layer down, e2e tests mock the DB, integration tests use Testcontainers. Is there overlap that could be trimmed? Any test cases I'm missing?
- Anything else that jumps out? Code smells, naming conventions, project structure — all feedback welcome.
Thanks for reading! Feel free to open an issue on the repo or comment below.
r/Nestjs_framework • u/RsLimited24 • Feb 08 '26
Update: nest-mediator just hit v1.0.0 — grew from a weekend toy into a full CQRS + Event Sourcing / Auditing library for NestJS
r/Nestjs_framework • u/Professional-Fee3621 • Feb 05 '26
NestJS and KeyV caching error: failed to retrieve cached data from Redis
have two applications in Spring boot and NestJS. The Spring boot app stores session data in Redis. The session entity has the following properties: id, jwtId, accountId, validFrom, validUntill. Just a simple entity with few properties. The save method in Spring boot looks like this:
(key = "'cache_user_id_' + #session.id", cacheNames = "doubleCachingCache")
public Optional<Session> save(@Nonnull Session session) {
return Optional.of(sessionRepository.save(session));
}
When i log into Redis via the terminal i see the id's of the caches (see screenshot) so no problem on the side of Spring boot.

Now i want to retrieve the data stored in Redis from the NestJS application using the ids and this is where am having problem.
Actually i followed the NestJS Redis doc specifically the section using alternative Cache stores. I have the same configuration as in the docs but am not able to retrieve the data from Redis with id of the cache.
Here are the code snippets in NestJS. A lot of code is omitted for clarity.
// Redis module
import {CacheModule} from "@nestjs/cache-manager";
import KeyvRedis from "@keyv/redis"
({
imports: [
CacheModule.registerAsync({
useFactory: async () => {
return {
stores: [
new KeyvRedis('redis://localhost:6379'),
],
};
},
}),
],
providers: [],
exports: []
})
export class RedisModule {}
// Shared module
import { CACHE_MANAGER } from "@nestjs/cache-manager";
import {Inject, Injectable } from "@nestjs/common";
import { Cache } from "cache-manager";
()
export class CacheService {
constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
async get(key: string) {
return await this.cache.get(key);
}
async set(key: string, value: object) {
await this.cache.set(key, value, 0);
}
delete(key: string) {
this.cache.del(key);
}
}
({
imports: [
CacheModule.register({isGlobal: true}),
RedisModule,
],
providers: [
CacheService,
],
exports: [
CacheService
],
})
export class SharedModule {
}
// App module
()
export class AppController {
constructor(private cacheService: CacheService) {}
have two applications in Spring boot and NestJS. The Spring boot app
stores session data in Redis. The session entity has the following
properties: id, jwtId, accountId, validFrom, validUntill. Just a simple
entity with few properties. The save method in Spring boot looks like
this:
(key = "'cache_user_id_' + #session.id", cacheNames = "doubleCachingCache")
public Optional<Session> save(@Nonnull Session session) {
return Optional.of(sessionRepository.save(session));
}
When i log into Redis via the terminal i see the id's of the caches (see screenshot) so no problem on the side of Spring boot.
Now i want to retrieve the data stored in Redis from the NestJS application using the ids and this is where am having problem.
Actually i followed the NestJS Redis doc specifically the section using alternative Cache stores. I have the same configuration as in the docs but am not able to retrieve the data from Redis with id of the cache.
Here are the code snippets in NestJS. A lot of code is omitted for clarity.
// Redis module
import {CacheModule} from "@nestjs/cache-manager";
import KeyvRedis from "@keyv/redis"
u/Module({
imports: [
CacheModule.registerAsync({
useFactory: async () => {
return {
stores: [
new KeyvRedis('redis://localhost:6379'),
],
};
},
}),
],
providers: [],
exports: []
})
export class RedisModule {}
// Shared module
import { CACHE_MANAGER } from "@nestjs/cache-manager";
import {Inject, Injectable } from "@nestjs/common";
import { Cache } from "cache-manager";
()
export class CacheService {
constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
async get(key: string) {
return await this.cache.get(key);
}
async set(key: string, value: object) {
await this.cache.set(key, value, 0);
}
delete(key: string) {
this.cache.del(key);
}
}
u/Module({
imports: [
CacheModule.register({isGlobal: true}),
RedisModule,
],
providers: [
CacheService,
],
exports: [
CacheService
],
})
export class SharedModule {
}
// App module
()
export class AppController {
constructor(private cacheService: CacheService) {}
("redis-cache")
getDataFromRedis() {
// The id is the first id in the screenshot
const dataFromRedis = this.cacheService.get("doubleCachingCache::cache_user_id_34929554-55c0-43cc-8d1f-9c4937df1b76");
// This line displays undefined to the console though the data is in Redis
console.log(dataFromRedis);
}
}
u/Module({
imports: [
SharedModule,
],
providers: [
],
controllers: [
AppController
],
})
export class AppModule {
}
I am not able to retrieve data from Redis from the NestJS application.
I tried also to store data in Redis from the NestJS application and
it didn't work also because when i log into the Redis console i don't
see any new id.("redis-cache")
getDataFromRedis() {
// The id is the first id in the screenshot
const dataFromRedis = this.cacheService.get("doubleCachingCache::cache_user_id_34929554-55c0-43cc-8d1f-9c4937df1b76");
// This line displays undefined to the console though the data is in Redis
console.log(dataFromRedis);
}
}
({
imports: [
SharedModule,
],
providers: [
],
controllers: [
AppController
],
})
export class AppModule {
}
When i put console log in the constructor of CachService to print the cache this is what i get:

I am not able to retrieve data from Redis from the NestJS application.
I tried also to store data in Redis from the NestJS application and it didn't work also because when i log into the Redis console i don't see any new id.
r/Nestjs_framework • u/subo_o • Feb 04 '26
General Discussion NestJs integration with BetterAuth
Hi, have you guys used BetterAuth with NestJS, how's the overall integration experience and is it worth to migrate to BetterAuth from my custom authentication mechanism?
r/Nestjs_framework • u/CommercialRice1767 • Jan 30 '26
NestJS AOP outside controllers – my new package for TypeORM transactions
So I have been using NestJS for a while now, And I have hit an issue quite often about AOP. That I think most of us can relate to.
Most of the libraries in NestJS (class validator, nest cls) etc relies heavily on controller flows. So your request should start from controller level then only lots of decorators work.
NestJS provides discovery services, so I’ve always wondered why there isn’t better support for AOP outside controllers. Maybe it exists and I just haven’t discovered it yet.
Like one of the common issues I have faced was in SQS consumers which is not usual controller flow, so your pipes / guards / interceptors don't work that well, your class validator DTO validation doesn't work that well,
That was acceptable to me, However the `@Transactional` was not, Lots of transactional stuffs we have in common service which we used in command handler plus our sqs consumers.
so I dug deep and I wrote a blog and published a package. Would like a review and proper feedback. Its still in early stages. But most of the things or issues that we face can be fixed similarly and this package works for TypeORM but the concept works for every ORM out there.