Understanding the Differences between Middleware and Controllers in Web Development
Tags: webdev, middleware, controllers, express
Published: 2023-05-27 15:28:45

Not long ago, the YouTube clone coding of Nomad Coders' web basics study finally started. After completing today's assignment, I was revisiting the video late for review, and when Nico Teacher showed us how to modify a function as an example, he mentioned it could become either middleware or a controller. This made me suddenly curious about the difference between middleware and controllers, and I wanted to summarize it briefly. First, I'll ask Teacher GPT4, and then verify whether it's correct or not.

### Middleware

Middleware is a function that runs between a request and a response. Middleware is executed sequentially, and it can perform specific tasks before the controller is executed, or additional tasks after the controller returns a response. Its primary features include modifying the request and response objects, authentication and authorization checks, and error handling.

1. Authentication and Authorization: It performs tasks to verify whether the user is authenticated and to ensure that only users with specific roles can access.
2. Error Handling: If an error occurs, it appropriately handles it and returns a response to the user.
3. Request and Response Logging: It records information about the server's requests and responses, which can be used for later analysis or debugging.
4. Request and Response Data Transformation: It transforms request data received from the client into a form that is easier to process, or transforms response data returned from the server into a form that is easier for the client to use.

For example, there is the following middleware:

```javascript
const authenticationMiddleware = (req, res, next) => {
  // Perform authentication logic
  if (req.isAuthenticated()) {
    // If authentication is successful, move to the next middleware or controller
    next();
  } else {
    // If authentication fails, return an error response
    res.status(401).json({ error: 'Unauthorized' });
  }
};
```

```javascript
// Middleware example: Request logging
const requestLogger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};

// Add middleware to the router
app.use(requestLogger);
```

### Controller

A controller handles the logic between a request and a response in a web application. When it receives a request from a client, it performs the appropriate logic and then returns a response. In this process, it may interact with the database or communicate with other APIs. Controllers are mainly used in routing files, and you can write several controller functions depending on the type of request.

For example, there is the following controller:

```javascript
const getUser = async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json({ error: 'Something went wrong' });
  }
};
```

### Differences between Middleware and Controller

The main differences between controllers and middleware are their roles and execution timings. While controllers primarily handle request logic and return responses, middleware performs additional tasks during the request-response cycle.

To summarize, it's as follows:

||Middleware|Controller|
|---|---|---|
|Role|Performs additional tasks between request and response|Handles request logic and returns response|
|Execution Timing|Runs before, after, or between controller execution and can change the execution order|Runs at a specific timing depending on the request|
|Use|Commonly used across multiple routers|Handles logic for a specific request|

Understanding these differences and properly utilizing controllers and middleware in ExpressJS allows for more effective management and scalability of your web application structure.

### References

- [Express Official Documentation: Using Middleware](https://expressjs.com/ko/guide/using-middleware.html)
- [[MDN]Express Tutorial Part 4: Routes and controllers](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes)