You may have noticed that there is a rather significant security risk in our blog application. That is, anyone could come to our blog to create, edit, and even delete any post they want.
To fix this problem, you need to implement a user authentication system so that only the logged in users are allowed to manage posts, and they should only be allowed to manage their own posts. And to accomplish this, we need to cover two more concepts, middleware and session.
In this lesson, we'll start with the middleware. A middleware is a piece of code that executes after the HTTP request has been received but before a response is returned.
Recall this example when we discussed the route handlers:
1app.get(
2 "/",
3 (req, res, next) => {
4 console.log("First route handler executed.");
5 next();
6 },
7 (req, res, next) => {
8 console.log("Second route handler executed.");
9 next();
10 },
11 (req, res) => {
12 console.log("Third route handler executed.");
13 res.send("Hello, World!");
14 }
15);
This is what a middleware looks like.
Yes, the route handler, controller, and middleware are basically different names for the same thing. It is a function that will be executed when a request is received.
- When this function is placed directly inside the route, we usually call it a route handler.
- When the function gets its own independent file and returns a response, we call it a controller function.
- When the function does not return a response, and instead, it tells JavaScript to go to the next function by executing
next()
, we call it a middleware.
Middleware can be useful in many different scenarios. For instance, you are trying to log all incoming requests. Instead of writing a logging mechanism for every route and every controller, you can create a logging middleware.
1.
2├── .env
3├── controllers
4├── database.sqlite
5├── index.js
6├── libs
7├── middlewares
8│ └── logging.js <===
9├── models
10├── package-lock.json
11├── package.json
12├── prisma
13├── routes
14├── statics
15├── uploads
16└── views