Node.js › Architecture & Design Patterns

What is a layered (n-tier) architecture in a Node.js/Express application, and what are its typical layers?

Advanced

Answer

A layered architecture separates an application into distinct responsibilities, commonly: the routing/controller layer (handling HTTP requests and responses), the service/business-logic layer (implementing the actual application rules), the data-access/repository layer (talking to the database), and the model layer (data shape definitions) -- each layer depends only on the layer below it, which improves testability (business logic can be tested without an HTTP server or a real database) and makes it easier to swap implementations, like changing databases without touching business logic.
// controller
app.post('/users', (req, res) => userService.createUser(req.body).then(u => res.json(u)));

// service (business logic)
async function createUser(data) {
  validateUser(data);
  return userRepository.save(data);
}

// repository (data access)
async function save(userData) { return db.collection('users').insertOne(userData); }
Real-world example A growing Express API refactors from having database queries directly inside route handlers to a proper repository layer, which immediately makes it possible to unit test the business logic against an in-memory fake repository instead of requiring a real database connection for every test.

Common follow-ups: How does this layered approach compare to a more feature-based ('vertical slice') folder structure?;At what point does strict layering start to add more overhead than value for a small project?