Module P-1·22 min read

Layered architecture (routes → controllers → services → data), feature folders vs layer folders, the service layer pattern, and dependency injection basics.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module P-1 — Application Architecture and Project Structure

What this module covers: The Blog API in F-8 worked, but it had a problem: route handlers were doing everything — validating input, querying the database, and formatting responses. At fifty routes that becomes unmaintainable. This module introduces the layered architecture pattern that separates concerns cleanly, explains why each layer exists, and gives you a project structure that scales to hundreds of endpoints without becoming a mess. Every production Node.js codebase uses some version of this.


Why Architecture Matters

Consider a route handler that does everything:

javascript

This is 40 lines doing six different jobs. Problems:

  • Untestable in isolation — to test the "banned user" rule you must mock HTTP, the database, email, and inventory
  • Impossible to reuse — if a mobile app and a webhook both need to place orders, this logic is duplicated or copy-pasted
  • Opaque — reading it you cannot tell where HTTP ends and business logic begins

The solution is layers.


The Four-Layer Architecture

text

Analogy: think of the four layers like a restaurant: the waiter (route) takes the order and never touches a pan, the line cook (controller) plates what the kitchen produces, the executive chef (service) decides the recipe and the rules, and the pantry runner (repository) is the only one allowed into the walk-in fridge.

Each layer has one job and knows only about the layer below it. A service never reads req.body. A route handler never writes SQL.


Project Structure

text

This is the feature-based slice vs layer-based choice. The structure above groups by layer (all services together). For large apps you may prefer grouping by feature (users/users.route.js, users/users.service.js, etc.). Either works — the important thing is the layer separation, not the folder names.


Layer 1: Routes

Routes are pure wiring. They register a URL pattern, apply middleware, and delegate to a controller. Nothing else.

javascript

No logic. No database calls. Just: middleware chain → controller.


Layer 2: Controllers

Controllers handle the HTTP boundary. They read from req, call services, and write to res. They contain no business logic — they orchestrate.

javascript

Notice: the controller knows about req, res, and next. The service knows nothing about them.


Layer 3: Services

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.