Architecture & Best Practices — Node.js

Split an Express app into four layers, parts of the code that each have one job. They are: route (a map of URLs, express.Router()), controller (reads req…

A food stall that has just opened is usually run by one person: taking orders, cooking, fetching ingredients from the storeroom and carrying the plates. Once it gets busy, the jobs are split. The cashier takes the order and passes it on, the waiter writes the order down and carries the plate back, the cook cooks to the recipe, the storekeeper fetches the ingredients. The cook doesn't need the table number, and the waiter doesn't need to know where the shelves are.

Code needs the same kind of split once an app grows. How you divide code into several files and layers, so each part has one job, is called architecture. A layer is one part of the code with one job, which only calls the layer below it. In Express, the four workers at the stall become four layers: the cashier becomes the route, the waiter the controller, the cook the service, and the storekeeper the repository.

Before: everything in one handler

In the database lesson, one route of the notes-api project did everything itself:

app.get("/notes/:id", (req, res) => {
  const row = db.prepare("SELECT * FROM notes WHERE id = ?").get(Number(req.params.id));
  if (!row) return res.status(404).json({ error: "Note not found" });
  res.json(row);
});

One handler knows its URL, reads req, writes SQL, picks the status and sends JSON. With two routes, this code still reads fine. With twenty routes, the same SQL is copied into many places, and the business rules (your app's own rules, such as "the list of notes is sorted by title") are spread everywhere.

Four layers and what each may know

Layer File Its job May know Must not know
Route routes/notes.js URL and method to a controller function Express Router data, SQL
Controller controllers/notesController.js read req, call the service, pick the status and JSON req, res, status codes SQL, tables
Service services/notesService.js business rules note data, its rules req, res, status codes, SQL
Repository repositories/notesRepository.js fetch and store data SQL, db HTTP, business rules

Each layer only calls the layer below it: route to controller, controller to service, service to repository.

The refactor, from the bottom up

To refactor means to reorganize code without changing what it does. Here is the /notes/:id route from above, plus a route for the list of notes, split into five files, starting from the lowest layer. The first line of each file names the file and its job:

// repositories/notesRepository.js: data only
const { DatabaseSync } = require("node:sqlite");
const db = new DatabaseSync("notes.db");

async function getAll() {
  return db.prepare("SELECT * FROM notes").all();
}
async function findById(id) {
  return db.prepare("SELECT * FROM notes WHERE id = ?").get(id) ?? null;
}
module.exports = { getAll, findById };
// services/notesService.js: business rules, no req and no res
const repo = require("../repositories/notesRepository");

async function list() {
  const all = await repo.getAll();
  return [...all].sort((a, b) => a.title.localeCompare(b.title)); // rule: sorted by title
}
async function getById(id) {
  return repo.findById(id); // a note, or null when there is none
}
module.exports = { list, getById };
// controllers/notesController.js: HTTP in, HTTP out
const service = require("../services/notesService");

async function list(req, res) {
  res.json(await service.list());
}
async function detail(req, res) {
  const note = await service.getById(Number(req.params.id));
  if (!note) return res.status(404).json({ error: "Note not found" });
  res.json(note);
}
module.exports = { list, detail };
// routes/notes.js: only a map of URLs
const express = require("express");
const controller = require("../controllers/notesController");

const router = express.Router();
router.get("/", controller.list);
router.get("/:id", controller.detail);
module.exports = router;
// app.js: puts it all together
const express = require("express");
const notesRouter = require("./routes/notes");

const app = express();
app.use(express.json());
app.use("/api/notes", notesRouter);
app.listen(3000);

express.Router and app.use: the full address

express.Router() makes a group of routes that can be mounted onto the main app. app.use("/api/notes", notesRouter) puts the prefix /api/notes in front of every route inside that router:

Full address = the prefix in app.use + the path in the router. Another example: a router mounted at /api/students with router.get("/") serves /api/students.

Swap the storage, one file changes

Suppose that, for testing, you want to use data in memory instead of a database. Just replace what's inside repositories/notesRepository.js with this code:

const notes = [
  { id: 1, title: "Groceries", content: "buy 5 kg of rice" },
  { id: 2, title: "Study", content: "Node.js chapter" },
];
async function getAll() {
  return notes;
}
async function findById(id) {
  return notes.find((n) => n.id === id) ?? null;
}
module.exports = { getAll, findById };

The function names and the shape of their results stay the same, so the service, controller and route don't change at all. Only one file changed. Without layers, you would have to find and replace every db.prepare in every handler.

MVC and this pattern

MVC (Model-View-Controller) is an older pattern that separates the data (model), the display (view) and what connects them (controller). In an API, the "view" is the JSON that res.json sends. The route, controller, service and repository pattern is a descendant of MVC: the model is split into a service (rules) and a repository (data).

In the exercise: userService and userController

In the exercise, the starter has users (Budi, Siti, Andi), userService.getAll() and userController.list(). Finish two functions:

  1. userService.getById(id): return users.find((u) => u.id === id) || null. The service only searches and returns, it prints nothing.
  2. userController.detail(id): when the user is found, print "GET /users/" + id + " -> " + JSON.stringify(user). When not, print "GET /users/" + id + " -> 404 Not Found".

⚠️ Signs the layers are split wrong

TL;DR: Split an Express app into four layers, parts of the code that each have one job. They are: route (a map of URLs, express.Router()), controller (reads req, picks the status, sends JSON), service (your app's business rules, no req/res) and repository (SQL and data). Each layer only calls the one below it, so changing where data is stored only changes the repository. app.use("/api/notes", router) mounts a router, and the full address is that prefix plus the path in the router. This pattern descends from MVC (Model-View-Controller). The service returns data or null, and the controller decides on the 404.

⚡ Four layers, one job each

Write:

// services/notesService.js: business rules, no req and no res
async function list() {
  const all = await repo.getAll();
  return [...all].sort((a, b) => a.title.localeCompare(b.title));
}

Meaning: Express code is split into four layers, parts of the code with one job each. The route maps URLs, the controller reads req and picks the status, the service holds the business rules (here: sort the notes by title), and the repository (repo) handles SQL and data. Each layer only calls the one below it, so changing the storage only changes the repository.

⚡ The controller decides on the 404

Write:

async function detail(req, res) {
  const note = await service.getById(Number(req.params.id));
  if (!note) return res.status(404).json({ error: "Note not found" });
  res.json(note);
}

Meaning: The service returns the note, or null when there is none, without knowing what a status code is. The controller turns "none" into a 404.

⚡ Full address = prefix + path

Write:

app.use("/api/notes", notesRouter);
Guess first: this router has router.get("/:id"). Which full address does it serve?

GET /api/notes/:id, for example /api/notes/2. The prefix in app.use goes in front of the path in the router.

Meaning: express.Router() makes a group of routes in its own file, then app.use mounts it onto the main app with one prefix.

What you will learn