惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
月光博客
月光博客
Jina AI
Jina AI
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
博客园 - 叶小钗
人人都是产品经理
人人都是产品经理
博客园 - 司徒正美
腾讯CDC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
Last Week in AI
Last Week in AI
V
V2EX
罗磊的独立博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
NISL@THU
NISL@THU
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
宝玉的分享
宝玉的分享
爱范儿
爱范儿
T
Troy Hunt's Blog
量子位
Project Zero
Project Zero
S
Secure Thoughts
V
Visual Studio Blog
美团技术团队
AI
AI
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Last Watchdog
The Last Watchdog
V
Vulnerabilities – Threatpost
P
Privacy International News Feed
Spread Privacy
Spread Privacy
Schneier on Security
Schneier on Security
博客园_首页
P
Privacy & Cybersecurity Law Blog
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
N
News | PayPal Newsroom

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I extended NestJS's architecture for projects that outgrow the basics
Matteo Tomič · 2026-05-08 · via DEV Community

NestJS ships with a great starting point. The module/controller/service pattern is clean, approachable, and gets you productive fast. For most projects, it's exactly what you need.

But as a project grows - more features, more teammates, more complexity - that foundation benefits from a bit more structure. Not a full rewrite, not a completely different paradigm. Just a few extra layers with clearly defined responsibilities.

This is what I came up with, and why.


The challenge with scaling the default structure

The built-in structure doesn't tell you where shared technical concerns go, how to organize services as they multiply, or where external integrations like email or file storage belong. That's not a flaw - the framework intentionally leaves those decisions to you.

Without deliberate decisions, though, you'll eventually run into familiar growing pains: services that accumulate too many responsibilities, shared utilities scattered without a clear home, and new developers spending their first days just figuring out where things live.

Full Clean Architecture solves these problems - but it also introduces a significant amount of abstraction that can feel heavy for a small or mid-sized project. Interfaces for things that will never change. Layers for layers' sake.

I wanted something in between: structured enough to scale, simple enough to onboard quickly.


Four layers, clear boundaries

I extended the default structure with four top-level groups, each with a clearly defined role:

src/
  common/         ← global technical infrastructure
  core/           ← stable infrastructure services
  integrations/   ← wrappers around external services
  modules/        ← business logic, by domain

Enter fullscreen mode Exit fullscreen mode

The value isn't in the folders themselves - it's in the rules each one follows.


common/ - technical, global, domain-free

Everything the framework needs to function, with zero knowledge of your business domain: global exception filter, response formatting interceptors, guards, custom decorators, global middleware, shared enums, TypeScript extensions for the request object.

The rule: if something in common/ needs to know what "business" means in your application - it doesn't belong in common/.

This is also where the global ValidationPipe lives, configured with whitelist: true. That single option automatically strips any properties not declared in a DTO before they reach your business logic. Security as a default, not something you bolt on later.


core/ - set it up, then forget it

core/ holds the application's internal technical infrastructure - things with no business logic, configured once and rarely touched:

core/
  config/
    env/        ← env validation and typed access to variables
  database/     ← connection, setup
  queue/        ← BullMQ configuration and provider

Enter fullscreen mode Exit fullscreen mode

The key distinction from integrations/: everything in core/ is internal to the application. No API calls to the outside world, no third-party dependencies - just the setup of what the application runs itself.

The env setup deserves a special mention. Rather than accessing process.env.SOMETHING throughout the codebase and discovering at runtime that a variable is missing, env gets validated at startup. Wrong type or missing value - the app won't start. A small investment that saves hours of production debugging.


integrations/ - one place for every external service

This is the layer that's most often missing in NestJS projects, and its absence is felt as soon as the project scales. Every external service the application talks to gets its own module here:

integrations/
  mailer/     ← email sending (SendGrid, SMTP, ...)
  storage/    ← file uploads (S3, local disk, ...)
  stripe/     ← payment processing
  sms/        ← SMS notifications (Bind, ...)

Enter fullscreen mode Exit fullscreen mode

mailer/ isn't just "send an email" - it's a wrapper that owns the SMTP configuration, templates, and retry logic. That logic doesn't belong inside the feature module that happens to use it, but it also doesn't belong in core/ which should stay independent of external services.

The practical payoff: when you swap SendGrid for AWS SES, you change one directory. Every feature module that uses mailer/ is completely unaffected.


modules/ - where the actual work happens

Every feature module follows the same internal structure, whether it's orders, users, products, or anything else:

modules/[feature]/
  dtos/                  ← input DTOs with validation
  repositories/          ← direct database access
  services/
    internal/            ← shared services within the module
    use-cases/           ← one service = one operation
  types/                 ← TypeScript types specific to this module
  [feature].controller.ts
  [feature].module.ts

Enter fullscreen mode Exit fullscreen mode


dtos/ - validation at the entry point

DTOs are classes that define what the controller is allowed to receive, with validation rules declared via class-validator decorators. One DTO per operation:

dtos/
  create-order.dto.ts
  update-order.dto.ts
  cancel-order.dto.ts

Enter fullscreen mode Exit fullscreen mode

Combined with whitelist: true on the global ValidationPipe, anything not explicitly declared in a DTO gets automatically rejected - without writing that check in every controller.


use-cases/ - one service, one operation

This is the most impactful decision in the whole architecture. Each file represents exactly one operation:

use-cases/
  create-order.service.ts
  cancel-order.service.ts
  confirm-order.service.ts
  get-order-summary.service.ts

Enter fullscreen mode Exit fullscreen mode

When a product manager reports a bug in the cancel order flow - you know exactly which file to open. When someone new joins the project and asks where the order creation logic lives - create-order.service.ts answers the question before they finish asking.

But readability isn't the only win here. This structure directly improves testability. Writing a unit test for a service with a single, clear responsibility is straightforward. Writing a unit test for a service with fifteen methods and a tangle of dependencies is the kind of work that always gets pushed to "later" - and later never comes.

With NestJS's DI system, each use-case service can be tested in isolation, mocking only the dependencies it actually needs.


internal/ vs use-cases/ - a distinction worth making

use-cases/ are the services a controller calls directly. One entry point, one responsibility.

internal/ are services used by other services within the module, but never directly by the controller. Example: a service that calculates order pricing with discounts - logic shared across multiple use cases, but not itself an operation the controller triggers. Pulling it into internal/ avoids duplication and gives you one focused place to test that logic.


Deliberate trade-offs

Repositories live inside their module, not in a shared Infrastructure layer. The reason is pragmatic: the orders repository is only ever used by the orders module. Abstracting something that isn't shared adds files and indirection without benefit. If two modules eventually need the same repository, that's the moment to refactor - not a reason to architect for it on day one.

This structure also deliberately skips repository interfaces and ORM abstraction layers. For a smaller project, that flexibility is largely theoretical. The code required to support it is real, and it carries a real maintenance cost.


The test that matters

Architecture should solve the problems a project has today, not imaginary problems it might face in two years. For a small team, this structure delivers predictability, built-in validation safety, and testability - without the overhead of a full Clean Architecture setup.

The question I ask about any architectural decision isn't "is this theoretically correct?" It's "will a new developer understand where things go and where to find them within 30 minutes?"

If the answer is yes - the architecture is doing its job.


How do you approach NestJS architecture on smaller projects? Do you separate external services into a dedicated integrations/ layer, or pull them directly into modules? I'd love to hear what's worked - and what hasn't - from your experience in production.