anantbhandarkar/make-it-right/mir-backend-node-nestjs

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (NestJS module). NestJS 11 + TypeScript specific reliability augmentation. Use alongside mir-backend and mir-backend-node when the target stack is NestJS — it carries the mechanical footguns that the framework-agnostic tiers deliberately omit: singleton DI scope bleeding request state across users, the full execution-order pipeline (middleware → guards → interceptors → pipes → handler → interceptors → exception filters) and why middleware is not a security boundary on the Fastify adapter, ValidationPipe with whitelist and forbidNonWhitelisted to stop mass assignment, ClassSerializerInterceptor as the outbound allow-list, the Express 5 route-syntax break that NestJS 11 inherits, the TypeScript 7 compiler-API break that stops nest build, and offloading durable work to BullMQ rather than running it in a request. TRIGGER only when the Node backend stack is NestJS — building, reviewing, or debugging a NestJS controller, provider, module, guard, pipe, interceptor, or exception filter, on either the Express or the Fastify adapter. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-node (V8 event-loop / process-model concerns: blocking, worker_threads, unhandled rejections, backpressure, timeouts, npm supply chain); this module only adds NestJS library mechanics. SKIP for standalone Express (mir-backend-node-express), standalone Fastify (mir-backend-node-fastify), Hapi, Koa, and for non-Node runtimes.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-node-nestjs

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-node-nestjs.

/mir-backend-node-nestjs · Make It Right (NestJS)

Bottom tier of the chain: mir-backend (generic gates) → mir-backend-node (V8/Node event-loop model) → this (NestJS library mechanics). Run the gates first; load the Node runtime tier for event-loop and process-model concerns; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (blocking the event loop, worker_threads, unhandled rejections, stream backpressure, timeouts, heap limits, npm supply chain) live in `mir-backend-node` — not here.

Stack assumed (npm registry, 13 Aug 2026): @nestjs/core@11.1.29 is latest. NestJS 12 exists only as 12.0.0-alpha.5 on the next tag — a pre-release; do not target it. engines.node says >= 20, but Node 20 is EOL — run on Node 22 or 24 per the runtime tier.

Run 11.1.24 or newer across every `@nestjs/*` package. Older 11.1.x patches carry the middleware-bypass CVEs listed in Security. The packages release in lockstep, so mismatched @nestjs/* versions in a lockfile are themselves the finding.

Adapter pins, which matter when you audit transitive versions: @nestjs/platform-express@11.1.29 pins express@5.2.1, path-to-regexp@8.4.2, multer@2.2.0, cors@2.8.6 — exact, not caret, so you cannot bump them independently without an override. @nestjs/platform-fastify@11.1.29 pins fastify@5.11.0, @fastify/cors@11.3.0, fastify-plugin@6.0.0.

The NestJS footguns AI walks into most

1. Singleton scope stores request state — bleeds across users

All providers in NestJS are SINGLETON by default. The same class instance handles every request for the lifetime of the application. Storing per-request data (current user, tenant ID, request ID, transaction handle) in a singleton service property is a race condition that bleeds one user's data into another's request under concurrent load — a security defect, not a style problem:

ts
// WRONG — singleton; currentUser is shared across all concurrent requests
@Injectable()
export class OrderService {
private currentUser: User; // ← shared mutable state; data bleeds between requests
async getOrders() {
return this.db.findOrders({ userId: this.currentUser.id }); // wrong user under load
}
}

Three correct patterns, in order of preference:

  1. Pass context as method parameters — the cleanest; no scope change needed.
  2. `AsyncLocalStorage` (from mir-backend-node §9) — carries request context without a scope change; nestjs-cls wraps it cleanly.
  3. `REQUEST` scope (@Injectable({ scope: Scope.REQUEST })) — a new instance per request. Fixes the bleed, but propagates up the DI chain: any singleton that injects a request-scoped provider becomes request-scoped too, and so does everything that injects it. Reserve for cases where the other two genuinely don't work.
ts
// RIGHT — pass context explicitly; no scope change
@Injectable()
export class OrderService {
async getOrders(userId: string) { // comes from the controller, which got it from the guard
return this.db.findOrders({ userId });
}
}

The same rule covers module-level let variables and any cache keyed without the tenant ID.

2. Execution order — know where each concern belongs

NestJS has a strict, non-negotiable pipeline. Putting a concern in the wrong slot means it either runs too late to protect or does not run at all on some paths:

Incoming request
│
├── Middleware (adapter-level: logging, cookie parsing, body parsing)
├── Guards (AuthN/AuthZ: may this request proceed?)
├── Interceptors (pre) (cross-cutting: logging, caching, tracing)
├── Pipes (input transform + validation: DTO parsing)
├── Route Handler (controller method)
├── Interceptors (post) (response transform: serialization, timing)
└── Exception Filters (error mapping: exceptions → HTTP responses)

Common misplacements AI makes:

  • Auth logic in a Pipe — pipes run after guards; a pipe cannot block an unauthenticated request.
  • Validation in a Guard — guards return true/false, not validated DTOs.
  • Response transformation in Middleware — middleware runs before the Nest pipeline and cannot see what the handler returned.
  • Final HTTP error mapping in an Interceptor — interceptors can see handler failures (RxJS catchError), so use one when the transformation is genuinely part of the cross-cutting pipeline. But an interceptor does not run for exceptions thrown by guards or pipes, which run outside it. ExceptionFilter is the only slot that catches everything, so that is where the response shape belongs.
  • Authentication in Middleware — see Security. On the Fastify adapter this has been bypassable three separate times. Use Guards.
3. ValidationPipe without whitelist — mass assignment / overposting

ValidationPipe's defaults let extra properties through. Without whitelist: true, a client can send { "email": "a@b.com", "isAdmin": true } and isAdmin reaches your handler even though the DTO never declares it — class-transformer copies every key it finds, and with transform: false you get the raw body object anyway. "My DTO doesn't have that field" is not a defence. With whitelist: true extras are stripped silently; without forbidNonWhitelisted: true you get no error and no signal that a client is probing:

ts
// WRONG — validation is on, but mass assignment still possible
app.useGlobalPipes(new ValidationPipe());
// RIGHT — strip extras and reject requests that send them
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: false }, // see below
}),
);

enableImplicitConversion: true looks convenient and causes silent coercion bugs: "0" becomes 0, "false" becomes true for a boolean property, and a @IsNumber() check can pass on something the client sent as a string. Leave it off and declare @Type(() => Number) where you want conversion.

DTOs are the validation boundary — never bind `@Body()` directly to an entity class. Use separate CreateUserDto / UpdateUserDto with class-validator decorators and explicit allowed fields; derive shared shapes with PartialType / PickType / OmitType from @nestjs/mapped-types:

ts
export class CreateUserDto {
@IsEmail()
email: string;
@IsString() @MinLength(1) @MaxLength(100)
name: string;
// id, isAdmin, role are NOT here
}
@Controller('users')
export class UserController {
@Post()
create(@Body() dto: CreateUserDto) { // ValidationPipe runs first; only safe fields arrive
return this.userService.create(dto);
}
}

Global pipes registered with app.useGlobalPipes() in main.ts cannot inject dependencies. If your pipe needs DI, register it with the APP_PIPE token in a module instead.

4. Object-level authorization — guards check identity, not ownership

NestJS guards are the right place for authentication. They are not the right place for object-level authorization ("does this user own this specific resource?"). AI routinely adds a JwtAuthGuard and ships the feature — any authenticated user can then read any other user's resource (IDOR):

ts
// WRONG — auth guard present but no ownership check
@Get(':id')
@UseGuards(JwtAuthGuard)
async getAccount(@Param('id') id: string) {
return this.accountService.findOne(id); // any authenticated user gets any account
}
// RIGHT — scope the query, don't filter after the fact
@Get(':id')
@UseGuards(JwtAuthGuard)
async getAccount(@Param('id') id: string, @CurrentUser() user: User) {
const account = await this.accountService.findOneForUser(id, user.id);
if (!account) throw new NotFoundException(); // 404, not 403 — don't confirm it exists
return account;
}

Put the ownership predicate in the query (WHERE id = ? AND user_id = ?) rather than loading and then comparing — the load-then-compare form is the one people forget to copy onto the update and delete paths. For richer permission models use a PoliciesGuard or CASL, but the split stands: guards decide "may this user call this endpoint at all"; the service decides "may this user act on this record".

5. Durable work in a request — use BullMQ instead

NestJS makes it easy to call a service method inline in the request cycle. AI routinely puts work that must be reliable (sending email, charging a card, generating a report) directly in the controller. If the process restarts after the response is sent and before the work finishes, the work is lost:

ts
// WRONG — no retry, no durability
@Post('orders')
async createOrder(@Body() dto: CreateOrderDto, @CurrentUser() user: User) {
const order = await this.orderService.create(dto, user);
await this.emailService.sendConfirmation(order); // silent loss on crash
return order;
}
// RIGHT — return the response; enqueue durable work
@Post('orders')
async createOrder(@Body() dto: CreateOrderDto, @CurrentUser() user: User) {
const order = await this.orderService.create(dto, user);
await this.emailQueue.add('send-confirmation', { orderId: order.id });
return order;
}

Use @nestjs/bullmq with BullMQ (bullmq@6.1.0 is the registry latest today). The original bull package and @nestjs/bull are the legacy line — do not start new work there. Jobs persist in Redis and workers retry, which means delivery is at-least-once: job handlers must be idempotent (the idempotency rule from mir-backend lands exactly here). Set attempts, a backoff, and removeOnComplete/removeOnFail limits, or Redis grows without bound.

6. Exception filters — consistent error mapping without leaking internals

Exceptions that are not HttpException subclasses reach the default handler and become a generic 500. Wire a global filter to normalize everything, and make sure it does not echo internal messages:

ts
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(
private readonly logger: Logger,
private readonly httpAdapterHost: HttpAdapterHost, // adapter-neutral send
) {}
catch(exception: unknown, host: ArgumentsHost) {
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const status = exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
if (status >= 500) this.logger.error({ exception }, 'Unhandled exception');
httpAdapter.reply(ctx.getResponse(), {
statusCode: status,
timestamp: new Date().toISOString(),
// exception.message only for 4xx — 5xx messages carry SQL, file paths, driver detail
message: status < 500 && exception instanceof HttpException
? exception.message
: 'Internal server error',
}, status);
}
}
// main.ts — APP_FILTER in a module if the filter needs injected dependencies
app.useGlobalFilters(new AllExceptionsFilter(app.get(Logger), app.get(HttpAdapterHost)));

`ctx.getResponse()` returns the adapter's native object, not a Nest abstraction. On Express that is Response, which has .json(). On Fastify it is FastifyReply, which does not — it has .code()/.status() and .send(). The response.status(status).json(...) form that most NestJS examples show throws response.status(...).json is not a function the moment someone swaps to FastifyAdapter. httpAdapter.reply(res, body, status) is the only form that survives both. ValidationPipe throws BadRequestException, so validation errors go through this same path.

7. NestJS 11 runs Express 5 — the route syntax changed underneath you

@nestjs/platform-express@11.x depends on Express 5, which uses path-to-regexp 8. Unnamed wildcards are gone:

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-node-nestjs/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-node-nestjs)

Something wrong with this skill or its page? Tell us.