What is a Controller Function in Express.js

We've met the controller already. Recall how we defined a router in one of the previous lessons:

javascript
1import User from "./models/user.js";
2
3app.get("/users/:id", (req, res) => {
4  const id = req.params.id;
5  User.getById(id, (err, user) => {
6    res.json(user);
7  });
8});

The second argument of get() is the route handler, and inside it, you can retrieve data from the database using the corresponding method in the model.

And then, you can use the retrieved data to render an HTML page using a template engine.

That's what a controller is. It connects the model layer and the view layer. Except that in practice, people usually use a dedicated file to store the controller functions.

text
1.
2├── controllers
3│   └── userController.js  <===
4├── database.sqlite
5├── index.js
6├── libs
7├── models
8├── package.json
9├── package-lock.json
10├── routes
11└── views

controllers/userController.js

javascript
1import User from "../models/user.js";
2
3const userController = {
4  getUserById: async function (req, res) {
5    const id = req.params.id;
6    User.getById(id, (err, user) => {
7      res.render("user", {
8        user,
9      });
10    });
11  },
12};
13
14export default userController;

It is customary to use the camel case naming convention for controllers, meaning your controller files should be named userController.js, articleController.js, tagController.js, and so on.

As an example, here is a controller that retrieves a single user from the database, and then use the retrieved data to render the /user page.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉