r/nestjs

▲ 10 r/nestjs

uWestJS - High performance platform adapter (HTTP & WebSocket) for NestJS.

Sooo, I'm finally done with something on which I was working on for more than a month.

I have finally shipped uWestJS v2.0.0 - A high performance platform adapter (HTTP & WebSocket) for NestJS.

>> It uses raw C++ bindings (μWebSockets) under the hood to provide high throughput and req/s.

>> The benchmarks are insanely good - 4-5x faster than Express and 2-2.5x faster than Fastify server.

>> Works with all the existing NestJS patterns and decorators that you already know.

>> Streaming support with automatic backpressure management.

>> Attracted 15+ contributors organically

Supports:

- Static File

- Multipart/File-upload

- Middlewares

- CORS

- Compression (Gzip, brotli, Deflate)

- Body Parsing

- Req/Res/Routing

Have in my mind to make this a whole platform agnostic tool in the upcoming versions.

If you're building something with NestJS do use uWestJS in your project/application.

Just do `npm install uwestjs`

GitHub - https://github.com/FOSSFORGE/uWestJS

Organization - https://github.com/FOSSFORGE

Discord - https://discord.gg/77wpUFpjDx

Documentation Website - https://uwest.js.org

NPM - https://www.npmjs.com/package/uwestjs

reddit.com
u/SwanCheap9626 — 1 day ago
▲ 7 r/nestjs+1 crossposts

Synchronize: true destroyed a production database: Here's the migration setup that prevents it

I used synchronize: true in a NestJS project for way longer than I should have. It was fine in development. But when I renamed a column in an entity, pushed to production, and TypeORM dropped the old column and created a new one on the next restart., data was gone.

You can fix this with migrations, but the TypeORM + NestJS migration setup is very confusing because the TypeORM CLI doesn't know about NestJS's dependency injection. You end up needing two configs, one for AppModule, one for the CLI, and getting them to share the same values without duplicating everything takes a bit of work.

The piece that finally made it click for me was the data-source.ts file. It's a standalone TypeORM DataSource that reads from your .env directly, no NestJS involved. The CLI uses that. NestJS uses ConfigService in AppModule. Both point to the same database, same entities, same migrations folder.

reddit.com
u/UneditedTips — 4 days ago
▲ 9 r/nestjs

Feedback wanted: did I over-engineer RBAC with CQRS in my first NestJS pet project?

Hi everyone!

I want to get feedback from experienced and not-so-experienced developers on the architecture of the most mature service (AccessControl) in my first pet project. I have a strong feeling that I overloaded the system with patterns. Many things (DDD, CQRS, Mixin, UoW, etc.) I was using for the first time. The project technically works and does its job, but I have no one to show the code to for review, so I came here for independent criticism.

Stack: Node.js, TypeScript, NestJS, MikroORM, PostgreSQL, Redis, Lua, Kafka, Debezium.

The task and the architectural solution

I needed to implement a hierarchical RBAC model and to fully give up storing permissions in tokens. To solve this task on hot-path requests, I introduced CQRS at several levels at once:

  • Database level: classic split into read/write PostgreSQL replicas.
  • Application level: clear separation of operational pipelines into Commands/Queries.
  • Hot-path projection: via CDC (Debezium) and Kafka I stream changes from Postgres into Redis. Redis stores a structure that is symmetric by entities but impoverished in metadata (everything the system doesn't need is removed). On top of that I had to introduce three classes of indexes for fast query handling.

Where the main pain is

This solution is already starting to feel inadequate to me. Yes, it fully covers the task and works fast enough, but the feeling of monstrosity doesn't leave me.

The system grew a thick layer of custom Lua scripts, which I had to sit over for a whole week, and the structure of the Redis storage itself turned out extremely complex because of the need to support a permission hierarchy and an index system.

Questions for the community

  1. Did I choose the right path to solving the task?
  2. Hasn't my solution turned into an ambassador of the word "over-engineering"?
  3. What mistakes did I make in understanding the patterns?

You may also point out other flaws of my pet project not related to the main problem - I'll accept those too.

Repo: https://github.com/LambdiusLab/access-control-service

I'll be glad to get harsh and constructive criticism, but keep in mind the fact that I literally have no education and this is my first pet project. I'm here to learn. Thanks!

u/DuePresent6490 — 4 days ago
▲ 12 r/nestjs

Connecting NestJS to PostgreSQL with TypeORM — including the parts most tutorials skip

The NestJS + TypeORM setup isn’t hard once you’ve done it, but there are a few things nobody tells you upfront that cost you an hour when you hit them.
Here’s a full guide in my article

brandfordtech.com
u/UneditedTips — 5 days ago
▲ 26 r/nestjs+3 crossposts

What I learned applying production patterns to a NestJS modular monolith (side project, ~1 year)

I've been building an open-source e-commerce API since last July. 9 DDD modules, Hexagonal Architecture, SAGA checkout, BullMQ, PostgreSQL, Redis. It's a side project and hasn't been deployed, but I've been applying real production patterns to learn how they actually work, not just read about them.

Last time I posted was at v0.2.0. Since then, I've gone through auth, security, Docker, and observability. Here's what was harder than expected.

For Auth, I migrated from nestjs/passport to raw RSA RS256 with jose. Private key signs, public key verifies, JWKS endpoint for external verification. Then, I added refresh token rotation and ripped out the role enum to build a normalized Role/Permission system backed by the database. The RBAC guard checks the JWT payload; no module imports Auth directly.

And then it comes to Observability, First time doing this.
Winston structured logs → Loki, prom-client → Prometheus, OpenTelemetry → Tempo, all wired to Grafana.
The correlation ID system uses AsyncLocalStorage and propagates through BullMQ by embedding the ID in job payloads and restoring context in workers.

I also implemented Helmet, CORS whitelisting, XSS sanitization interceptor, 4-stage Docker build with tini, graceful shutdown handling for BullMQ workers and WebSocket connections, API versioning, and Redis-backed rate limiting.

Repo: https://github.com/raouf-b-dev/ecommerce-store-api

Would appreciate any technical feedback, especially on the ACL gateway pattern I'm using for cross-module communication and the observability setup.

u/rbdz1 — 8 days ago
▲ 11 r/nestjs

API versioning or dynamic endpoints?

Hello everyone,

weare slowly moving from supabase and database stored procedures from postgres

to a fully manged backend with nestjs and everything was going great at a good pace and the only client was the mobile.

and suddenly the web came up and got a freelancer to build the web UI and boom she added more data to fill up extra spaces.

for example

GET /teams

returns id, name, logo and isAdmin

now the new web UI requires two more information

membersCount, upcomingSession.

then we went on a full two hours "discussion" on what to do to solve this problem

either make /v2/teams that returns the new fields and when the mobile migrates to it, it will be *Over Fetching*

either add some configuration in the service with couple of if statements to return the extras /teams?platform=web or something similar which will cause service layer complexity.

what to do in this delimma ?

reddit.com
u/Desperate_Mode_5340 — 7 days ago
▲ 8 r/nestjs

My authentication system is slow in my backend code.

I am a software engineer and recently started learning some backend development, currently NestJs + Express and NodeJS as runtime.

Right now I had completed the authentication module but when I tested the system the password encryption using bcrypt is quite slow and taking good amount of performance from the CPU, and I am planning some solutions.

Currently it is all asynchronous code using async/await.

But I am thinking how I can offload this heavy cpu workload from main thread

Right now I thought of 2 solutions:

  1. Using service-workers
  2. Using wasm + some low level language code

I will implement both of them as learning but I am curious how in production do these problems are tackled ?

Also did not tried bun due to its non reliability.

reddit.com
u/TheWatcherBali — 7 days ago
▲ 11 r/nestjs

Is NestJS better than Express for AI-driven development?

My theory is that if the framework has more rules, the AI will make fewer mistakes, allowing me to focus on the actual product

to those who have made the switch: did you find that a more structured framework improved your AI workflow and reduced technical debt?

reddit.com
u/Terrible-Winter3616 — 11 days ago
▲ 11 r/nestjs+2 crossposts

I have implemented an EDI (for invoicing) system from scratch in Node.js/ NestJs and integrated it into our enterprise-grade system

I have implemented an EDI (for invoicing) system from scratch in Node.js/ NestJs and integrated it into our enterprise-grade system. I wonder if there is a job market for this to work as a software engineer specialized in the development of EDIFACT systems for enterprise-grade systems. I know that there are a lot of tools to build and map the EDI data fields, but I am not speaking of using these vendor tools like IBM Sterling; I am exclusively referring to implementing the EDIFACT standards from scratch, the EDI file generation, validation, and parsing. Is this a thing? I couldn't even find any libraries to help me generate or parse the EDI files in Node.js, so I had to implement everything from scratch.

reddit.com
u/Sorry-Cow-6642 — 10 days ago
▲ 3 r/nestjs

Authorization: When should I reach for library instead of custom guard?

I'm designing a permission system for a collaborative workspace. Each workspace has its own admins and those admins define permissions for actions members can perform.

My current design is, a custom guard queries the permission table to check if the user has the required permission for the action. If allowed, the controller executes; otherwise, it throws ForbiddenException

This works fine, but I’m wondering when should I reach for an authorization libraries nstead of just sticking with custom Guards? Lik what is the go to approach for authorization?

reddit.com
u/BrangJa — 8 days ago
▲ 8 r/nestjs

How do you run NestJS in a Turborepo monorepo (pnpm) with no pre-build, Docker support, working DI decorators, AND watch mode?

I'm stuck trying to get a clean dev setup for a Turborepo + pnpm monorepo. I have a NestJS app at `apps/api` and many packages in `packages/` The API depends on it.

For context im migrating from nextJS to nest.

I need **all four of these at once** and can't find a setup that satisfies everything:

  1. No pre-build — I don't want to run `turbo build --filter=@repo/package` before starting the API. Changes in `@repo/package/src` should be reflected immediately.
  2. Works in Docker — The dev container starts fresh with no `dist/` folders (gitignored). Any setup that relies on `dist/` existing fails.
  3. NestJS DI works correctly — `@Injectable()`, `@Controller()`, etc. must emit decorator metadata (`emitDecoratorMetadata: true`). Using `tsx` directly breaks this, causing injected services to be `undefined` at runtime.
  4. Watch mode — Changes in both `apps/api/src` AND `@repo/packages/src` should hot-reload the server.

What I've tried:

- `tsx --conditions=development --watch ./src/main.ts` → breaks NestJS DI.

- `nest start --watch` with `NODE_OPTIONS=--conditions=development` → can't import `.ts` files directly, doesn't watch workspace package changes

all my packages exports use a `development` condition pointing to `./src/*.ts` and `production`/`default` pointing to `./dist/*.mjs`.

What's the correct dev setup here? Has anyone solved this combination cleanly?

reddit.com
u/Ezio_rev — 10 days ago
▲ 21 r/nestjs

I built a Vite plugin that lets you run NestJS through Vite. Native ESM, plugin ecosystem, and Swagger metadata out of the box

Hey everyone! I just published vite-plugin-nestjs: a Vite plugin that replaces the NestJS CLI as your dev/build tool.

Why?

The NestJS CLI uses its own compiler pipeline (ts-jest, SWC, etc.), which means you're locked out of the Vite plugin ecosystem. I wanted to use Vite plugins in a NestJS project and couldn't find a clean way to do it, so I built one.

What it does:

  • Runs your NestJS app through Vite's dev server, your controllers are available at localhost:5173 with full Vite support
  • Gives you access to the entire Vite plugin ecosystem in your backend project
  • Automatically detects @nestjs/swagger in your nest-cli.json and generates Swagger metadata before any request is handled, no manual step required
  • vite build bundles your Nest app as an SSR Node.js module you can run with node dist/main.js
  • npm: https://www.npmjs.com/package/vite-plugin-nestjs
  • GitHub: https://github.com/Alan-Gomes/vite-plugin-nestjs

Would love feedback, bug reports, or ideas. Happy to answer any questions!

reddit.com
u/alangomes_ — 12 days ago
▲ 1 r/nestjs+1 crossposts

What do you think about no/low-deps projects?

Talking about Node.js, a big problem we face today is that using the most popular libs like Nest.js and others, we end up with a crazy amount of dependencies we never actually chose to use. And when one of them gets flagged with a vulnerability, it flows up the chain until it hits our installed lib - and boom: update fast or your app is vulnerable.

I know it's basically impossible to avoid this problem while still keeping a decent set of tools that make our lives as devs easier. After all, these libs were created to encapsulate complex problems so we can focus on the actual business logic.

Anyway, this problem still sucks, and an interesting approach is to build no/low-deps projects - or more precisely, projects with minimum and audited dependencies. Like using Fastify instead of NestJS, or Drizzle instead of Prisma.

I started thinking seriously about this after I created a robust [NestJS boilerplate](https://github.com/vinirossa/nest-api-boilerplate-demo) for my future projects, with all the enterprise features I see at work - so I'd never have to start from scratch and debug "foundational" features like RBAC, i18n, caching, etc.

Now I'm thinking about building a similar boilerplate using a low-deps stack - same feature set as much as possible, but with a lighter and more audited dependency footprint. Think Fastify, Drizzle, postgres.js and Zod instead of the heavy hitters. That said, I'm aware this isn't a silver bullet - reimplementing things manually also opens the door to vulnerabilities, and those tend to fly under the radar since there's no CVE tracking or community eyes on your custom code.

What's your experience with no/low-deps projects? I'd love to hear more about it.

u/Worldly-Broccoli4530 — 12 days ago
▲ 1 r/nestjs+1 crossposts

How to share a single Prisma client instance between a NestJS app and a plain Node.js app in a pnpm monorepo?

I have a pnpm monorepo with two apps a NestJS API and a Node.js scraper both using Prisma 7. I want a single PrismaClient instance defined in a shared /myapp/database package so both apps use the same configuration and connection setup.

#folder structure
apps/
  api/          # NestJS app
  node-app/      
packages/
  database/
    src/
      generated/prisma/   
      index.ts            # exports prisma instance + types
    prisma/
      schema.prisma
    package.json
package.json

#packages/database/src/index.ts:
 
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.js';

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! });

export const prisma = new PrismaClient({ adapter });

export * from './generated/prisma/client.js';
, 

The nodejs app imports it directly, no issues. The problem is NestJS the standard pattern is to extend PrismaClient in an Injectable() service, which creates a second instance alongside the one already created in the shared package.

is it actually a problem to have two separate PrismaClient instances here (one per app process)? Since the scraper and API run as separate processes If it is a problem, how do I wrap the existing singleton so NestJS's DI system uses it without creating a new one?

Injectable()
export class PrismaService {
  // somehow wrap/expose the shared singleton here
}

Also, please don’t say “ask AI.” I did, and I’m not sure about its answers. I don’t want to blindly follow it, as this is a strictly no-AI project to improve my knowledge since I’m still a junior developer.

reddit.com
u/iam_batman27 — 13 days ago
▲ 16 r/nestjs

I built nestjs-socket-presence — a drop-in NestJS module for real-time user presence tracking (Socket.IO + Redis). Nothing like this existed on npm, so I made it.

Hey r/nestjs 👋

I've been building omnichannel chat platforms for 5+ years and one thing I always had to implement from scratch on every project was user presence tracking — who's online, who's offline, which agents are available in a room.

There was no dedicated npm package for this in the NestJS ecosystem. So I built one.

---

**nestjs-socket-presence** — https://www.npmjs.com/package/nestjs-socket-presence

Install:

npm install nestjs-socket-presence ioredis

---

**What it does:**

- Automatic online/offline tracking on socket connect/disconnect

- Multi-socket per user (one user, multiple tabs/devices — single presence state)

- Redis TTL expiry — ungraceful disconnects auto-expire (no ghost users ever)

- Heartbeat support — clients refresh TTL on a timer

- Room presence — who's online in a specific room right now

- Bulk presence queries — check hundreds of users in one Redis round-trip

- Multi-instance safe — works behind a load balancer

- register() and registerAsync() — works with ConfigService

---

**Usage is dead simple:**

// app.module.ts

PresenceModule.register({

redis: { host: 'localhost', port: 6379 },

ttl: 30,

})

// Client

const socket = io('http://localhost:3000', {

auth: { userId: 'user-123' }

})

// That's it. User is now tracked as online.

// Inject PresenceService anywhere

const online = await this.presenceService.isOnline('user-123');

const room = await this.presenceService.getRoomPresence('support-room');

const bulk = await this.presenceService.getBulkPresence(['u1', 'u2', 'u3']);

---

**Why Redis?**

So it works across horizontally scaled NestJS pods. One user connects to pod A, another to pod B — presence state is shared via Redis. No ghost users, no split-brain.

---

GitHub: https://github.com/SaifuddinTipu/nestjs-socket-presence

npm: https://www.npmjs.com/package/nestjs-socket-presence

22 unit tests. Full TypeScript types. MIT license.

Feedback and PRs very welcome — this is v1.0.0 and I want to make it production-solid.

reddit.com
u/TemperatureAlive1594 — 14 days ago