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);
- The repository returns raw data, or
nullwhen there is none. Its functions areasynceven thoughnode:sqliteis synchronous. So ifnode:sqliteis later replaced by an async database (PostgreSQL, for example), the layers above it don't have to change. - The service holds the rule "the list is sorted by title" (
localeComparecompares two titles in alphabetical order). So the note titledGroceriescomes beforeStudy. - The controller decides that "none" means 404. The service has no idea what a status code is.
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:
router.get("/")servesGET /api/notes.router.get("/:id")servesGET /api/notes/2.
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:
userService.getById(id): returnusers.find((u) => u.id === id) || null. The service only searches and returns, it prints nothing.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
- SQL in the controller. As soon as two controllers need the same data, the SQL gets copied. Put the SQL in the repository.
reqorresin the service. The service can then no longer be called from a script, a cron job (a program that runs by itself at set times) or a test. Pass just the values, such asservice.getById(Number(req.params.id)).- A service that prints instead of returning. A controller can't use what a
console.login the service prints. Return the data, and let the controller decide the answer. - A wrong
requirepath. From thecontrollers/folder, the service is at../services/notesService. With one dot missing, the result isError: Cannot find module. - Too many layers for a small app. Three routes and one table can stay in one file. Split it when the file starts to feel crowded.
- Secrets in the code. Read settings such as
PORTandJWT_SECRETfrom environment variables (settings outside the code). Put.env, the file where those secrets are written, into.gitignore, the list of files Git doesn't store.
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.