Shoving every route, controller, and raw database query straight into a single index.js file works totally fine when you are hacking something together over a caffeinated weekend. But the moment another engineer pulls down the repo, that setup falls apart fast. Before you know it, a single controller balloons past 2,000 lines, circular imports take turns blowing up your boot process, and you realize you desperately need an architecture that won't crumble the second your app gains traction.
| Architecture | Best used for | Key advantage | Major drawback |
|---|---|---|---|
| MVC | Quick prototypes, solo hobby builds, simple MVPs | Blazing fast to spin up on day one | Degenerates into a tangled mess as scope expands |
| Layered | Mid-sized projects with real business rules | Neatly decouples database queries from core domain logic | Services still risk becoming uncomfortably tangled |
| Feature-based | Growing teams, enterprise codebases, future microservices | Keeps domain contexts contained and slashes merge collisions | Requires extra upfront wiring before you write logic |
We'll assume you're already spinning up a modern Node.js runtime with TypeScript configured and ready to go.
The 3 Biggest Scaling Mistakes in Node.js Architectures
Before we start mapping out folder trees, let’s talk about what actually breaks when a Node backend quietly outgrows its original layout. Most of us don't notice things are sideways until the simplest bug fix suddenly takes an entire afternoon.
Circular Dependencies That Crash the App
You've probably seen this movie before: your UserService needs a quick method from AuthService, but AuthService imports UserService right back to run a permission check. Node tries to resolve both modules while bootstrapping, ends up handing one of them an empty object, and greets you with an infuriating undefined is not a function error right on startup.
Controllers That Do Everything
It almost always starts innocently enough. You toss an automated email trigger directly into a signup handler, then someone tucks a Stripe billing webhook right beneath it. Fast forward a few months, and your user.controller.ts is a 3,000-line monster juggling database queries, external REST calls, and custom JSON payloads, making unit tests an absolute nightmare to write.
Constant Merge Conflicts in Shared Folders
Whenever you have half a dozen engineers shipping separate tickets out of the exact same generic services/ or controllers/ directories, Git conflicts turn into an everyday chore. You waste valuable engineering cycles manually untangling import statements instead of actually building software, which inevitably leads to team members juggling git revert or git reset far more often than anyone would like.
Choosing a Folder Structure That Fits Your Project
Over-engineering a tiny prototype with heavy enterprise patterns will slow you to a crawl, but clinging to a simplistic layout on a fast-growing team will paralyze your releases. The trick is picking a structure that matches the practical reality of what you're building right now.
MVC (Model-View-Controller): For Prototypes and MVPs
Classic MVC organizes your files strictly around their technical jobs. It’s genuinely great when you just need to knock out a basic CRUD interface or spin up a throwaway internal dashboard by Friday.
Models: Define your database tables and house the raw queries or ORM schemas.
Controllers: Intercept incoming HTTP requests and assemble the outbound JSON payload.
Routes: Map your API endpoints directly to specific controller methods.
The friction hits as soon as real-world business logic creeps in. Because classic MVC doesn't have an obvious home for rules that don't map directly to a database row, controllers end up acting as a junk drawer for all that extra logic.
Layered Architecture: For Medium Apps with Complex Logic
A layered design solves this sprawl by introducing a dedicated service tier specifically meant for domain rules that don't belong in your transport layer.
Controllers: Validate user input - like ensuring an email is properly formatted - and hand the data over to the service.
Services: Execute the actual business workflow, like verifying user records, salting passwords, and dispatching notification emails.
Data access / repositories: Focus purely on talking to the database and returning domain objects.
This pattern keeps your HTTP handlers slim and pairs cleanly with common REST API design best practices. The trap here, though, is that everything still ends up tossed into a sprawling src/services folder where your billing, auth, and catalog logic sit side by side. As more teammates contribute, people inevitably start importing across domains until those clean boundaries turn into spaghetti.
Feature-Based Architecture: For Large Teams and Future Microservices
Feature-based architecture ditches generic role folders and instead groups files by business capability - think users, subscriptions, or orders. Everything required to run that specific slice of the product lives right there beside it.
If you are assigned to fix a checkout bug, you just head over to src/features/billing/ and find the routes, business rules, schemas, and models right together. Keeping these domain boundaries strictly isolated also means that if you ever do need to spin that feature off into a standalone service later on, the boundary lines are already drawn for you.
A Modern Feature-Based Structure with TypeScript
This approach really shines when you draw a hard line between core application plumbing, globally shared utilities, and independent business domains. Here is a practical blueprint for laying out your TypeScript backend.
Organizing Core, Domain, and Shared Code in /src
Your src/ directory works best when it keeps foundational infrastructure separate from day-to-day domain code.
/src/core/: Contains app-wide wiring, such as Express instance setup, database connection pools, loggers (like Pino or Winston), and environment variable parsing./src/shared/: Houses cross-cutting helpers, base error classes, and universal middleware like JWT authentication guards./src/features/: Contains your business domains, where each subfolder operates as an isolated vertical slice of the product.
Drop some path aliases directly into your tsconfig.json so you never have to deal with ugly, fragile ../../../../ import chains again:
JSON
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@core/*": ["core/*"],
"@shared/*": ["shared/*"],
"@features/*": ["features/*"]
}
}
}Splitting Routes, Controllers, and Services
Inside a single domain directory like src/features/orders/, you still take advantage of layered thinking, just scoped entirely to that feature:
orders.routes.ts: Maps the HTTP methods to your local controller handlers.orders.controller.ts: Parses request parameters and coordinates standard HTTP responses.orders.service.ts: Runs the heavy business logic, calculations, and domain operations.orders.schema.ts: Holds your runtime schema validators (like Zod or Joi) for incoming payloads.orders.interfaces.ts: Contains types and contracts that only matter to the orders domain.
TypeScript
// orders.service.ts
import { OrdersRepository } from './orders.repository';
import { Order } from './orders.interfaces';
export class OrdersService {
constructor(private repo: OrdersRepository) {}
async createOrder(userId: string, items: Order['items']): Promise<Order> {
const total = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
return this.repo.insert({ userId, items, total, status: 'pending' });
}
}Keeping these files clustered together means anyone jumping into the order flow can see the full picture instantly without hunting through four different root folders. It's the same modular mindset you'd use when deciding whether a utility function should simply be an exported function or packaged into
Refactoring Your Current Project: A Migration Path
The good news is you don’t need to halt the sprint and rewrite your entire codebase just to fix a legacy MVC setup; you can migrate things piecemeal alongside your normal feature work.
Moving from MVC to Feature-Based Folders
Pick whatever domain is currently giving your team the biggest headache - usually something high-traffic like authentication or order fulfillment. Add a fresh src/features/ folder and pull only that domain's routes, controllers, and queries out of the old folders and into their new home.
Tweak the import statements, run your test suite, and verify everything still boots clean. Once that domain is happily walled off in its own space, rinse and repeat for the next one. This gradual approach - often referred to as the strangler fig pattern - lets you steadily modernize the system without the massive risk of an all-at-once rewrite.
Putting TypeScript Types and Interfaces in the Right Place
When migrating, people often dump every single interface into a catch-all src/types/ folder just to get things compiling. Resist doing that, because it immediately blurs your domain boundaries again.
Keep types co-located right next to the code that relies on them. If an interface describes a record from your users table, it belongs in src/features/users/user.interfaces.ts. Reserve a global src/types/ directory strictly for ambient declarations and third-party library patches, like extending the default Express Request type with your authenticated session data.
Ultimately, pick the architecture that solves the problems you are dealing with this week. If you're prototyping solo, classic MVC keeps things moving fast. But if you have multiple devs stepping on each other's toes every time they open a PR, carving things into feature folders will make your lives a whole lot easier.
