A tutorial server often lives in one file, and that is fine for learning. A real project grows to dozens of routes, and one file becomes painful to read, test and change. This lesson shows a simple structure that you will see in most Express projects. It is usually called MVC, short for model, view and controller, though in an API the view is just JSON. The goal is not to follow a rule. The goal is that each file has one job, so you always know where to look.
Who does what
- Store (model): reads and writes data. It knows nothing about HTTP. Later you can swap it for MongoDB without touching anything else.
- Controller: receives the request values, calls the store, and decides the response and status code.
- Routes: a list that connects a method and a path, such as
GET /api/books/:id, to a controller function. - App: creates the Express app, adds middleware, mounts the routes, and adds the 404 and error handlers.
- Server: a tiny file that calls
app.listen. Keeping it separate lets tests import the app without opening a port.
The separation has a practical payoff: you can test the controller with a fake store, or test the whole app with Supertest and no real port. Both are used later in the course. The example below is a small book API in four files plus a web page.
The store and the controller
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express. - Save the files below in one folder, with the names shown in the comments at the top of each block. Put the web page in a folder called
s19-public.
// s19-store.js
// The "model" layer: knows how books are stored, nothing about HTTP.
export function createBookStore() {
const books = new Map();
let nextId = 1;
return {
list: () => [...books.values()],
find: (id) => books.get(id) ?? null,
add(data) {
const book = { id: nextId++, ...data };
books.set(book.id, book);
return book;
},
remove: (id) => books.delete(id),
};
}
// s19-controller.js
// The "controller" layer: turns a request into a call on the store and a response.
export function bookController(store) {
return {
list: (req, res) => res.json(store.list()),
get(req, res) {
const book = store.find(Number(req.params.id));
if (!book) return res.status(404).json({ error: 'Book not found' });
res.json(book);
},
create(req, res) {
const { title, author } = req.body ?? {};
if (typeof title !== 'string' || !title.trim()) {
return res.status(400).json({ error: 'title is required' });
}
res.status(201).json(store.add({ title: title.trim(), author: author ?? 'Unknown' }));
},
remove(req, res) {
if (!store.remove(Number(req.params.id))) return res.status(404).json({ error: 'Book not found' });
res.status(204).end();
},
};
}
The store keeps books in an array and gives each an id. The controller functions take (req, res) and use the store. Notice that they are factory functions that receive the store as an argument. That is the simplest form of dependency injection: the controller does not create its own store, so a test can pass a different one.
Routes and the app
// s19-routes.js
// The "route" layer: only maps URLs to controller functions.
import { Router } from 'express';
export function bookRoutes(controller) {
const router = Router();
router.get('/', controller.list);
router.post('/', controller.create);
router.get('/:id', controller.get);
router.delete('/:id', controller.remove);
return router;
}
// s19-app.js
import express from 'express';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createBookStore } from './s19-store.js';
import { bookController } from './s19-controller.js';
import { bookRoutes } from './s19-routes.js';
const here = path.dirname(fileURLToPath(import.meta.url));
export function createApp() {
const app = express();
// Application settings
app.disable('x-powered-by');
app.set('trust proxy', 1); // we will sit behind nginx later
app.set('json spaces', 2);
app.use(express.json());
app.use(express.static(path.join(here, 's19-public'))); // serves index.html at /
app.use('/api/books', bookRoutes(bookController(createBookStore())));
// 404 for anything that did not match, then one error handler at the end.
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
return app;
}
Read the app file from the top. app.disable('x-powered-by') removes a header that tells everyone you use Express, which gives attackers a small hint for free. app.set('trust proxy', 1) tells Express that one proxy, such as nginx, sits in front, so req.ip and req.protocol show the real visitor. Without it, every visitor looks like the proxy. json spaces makes JSON replies readable while you develop; remove it in production to save bytes.
express.static serves the files of a folder as they are. A request to / returns s19-public/index.html, and a request to /style.css returns that file if it exists. Static files are meant for your front-end build, images and a favicon. Never point it at a folder that contains code or secrets, because every file inside is public.
404 and the error handler
Express runs middleware in the order you add it. The two functions at the bottom of the app are the safety net. The first has no path, so it catches any request that no route handled, and returns a JSON 404. The second has four parameters, (err, req, res, next). That fourth parameter is how Express recognises an error handler, so keep it even if you do not use next. Any error thrown in a route reaches it, and in Express 5 that includes errors from async functions. The handler logs the real error for you and sends the client a short, safe message. Lesson 33 expands this into a full logging and error system.
Environment settings
The behaviour of the app should change with the environment, not with edited code. process.env.NODE_ENV is production on a live server, and several libraries, including Express, use it to turn on faster, quieter behaviour. Read the port, database address and secrets from environment variables as well. Lesson 31 builds a validated configuration file for this.
The test for this lesson starts the app with Supertest, fetches the home page, creates a book, reads it back, deletes it, and checks that a missing id returns 404. It passes, and you can find it in the course code as s19.test.js.
Your task
- Add a
PATCH /api/books/:idroute that changes only the fields sent. - Add a second store file that saves the books in a JSON file and swap it in without changing the controller.
- Add a route that deliberately throws an error and check that the client sees only the safe message.
How to check it worked
GET /returns the web page.- A wrong URL returns a JSON 404, not an HTML error page.
- You can say which file you would open to change a status code, and which to change where data is saved.