The middlewares are one of the most important features in Express. The middlewares are the function written with request handler function and these function will access to the request and response objects. The middleware functions usually take three arguments, functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. Some middleware only takes two arguments, without the next and some middleware takes four arguments. As in error handling middleware, we have to supply error as the argument along with other three arguments above.
Middleware allows us to break these request handler functions into smaller bits. These smaller functions tend to handle one thing at a time. Express app is usually a web framework that consists of middleware and router. Therefore, an express application works through a series of middleware functions.
Middleware functions can perform the following tasks:
- Execute any code.
- End the request-response cycle.
- Make changes to the request and the response objects.
- Call the next middleware in the stack.
An Express application can use the following types of middleware:
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
Check here, some of the middleware manage by Express team
Express’s static middleware
MORGAN: LOGGING MIDDLEWARE
It’s good practice to log all the errors that happen in our app. In Node, we have many modules to log our user request log. We can create a simple custom log or can use Morgan and advance log module like Winston. Morgan is HTTP request logger for node.js and is express middleware. To install Morgan middleware.
npm install –save morgan
Add the following code in app.js, when we run the app.js we can see in the terminal that Morgan middleware function will console.log the information of IP and some other request information about the user.
To learn on Winston middleware, read this blog.
Error handling in the Express is achieved through middleware. Error handling middleware in the Express has four arguments instead of 3 as (err, req, res, next). It is good practice to handle the unexpected error in Express, as a unhandled error may cause our server to shot down. Express can handle area in two situations, we can handle the error at development and production work.
In this simple example below, we learn how to throw and handle an error while accessing URL with a certain word.