Express middleware

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.

function logger(req,res,next){
  console.log(new Date(), req.method, req.url);
  next();
}

 

Middleware functions can perform the following tasks:

  1. Execute any code.
  2. End the request-response cycle.
  3. Make changes to the request and the response objects.
  4. 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

Built-in middleware

Express’s static middleware

We can use Express’s built-in middleware called static to serve static file like images, CSS files, and JavaScript file to the client. To read more on serving static file the read this blog

 

 

Third-party 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.

var express = require("express");
var logger = require("morgan");
var http = require("http");

var app = express();

//Use Morgan Middleware
app.use(logger("short"));   

app.use(function(request, response) {
   response.writeHead(200, { "Content-Type": "text/plain" });
   response.end("Hello, world!");
});
http.createServer(app).listen(3000);

To learn on Winston middleware, read this blog.

 

Error-handling middleware: 

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.

// development error handler, will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
  });
}

// Production error handler no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

 

In this simple example below, we learn how to throw and handle an error while accessing URL with a certain word.

var express = require("express");
var morgan = require("morgan");

var app = express();

app.use(morgan("dev"));

app.use(function(req, res, next) {
  if (req.url === "/") {
    next();
  } else if (req.url === "/error") {
    throw new Error("Custom error handler");
  } else {
    next("You didn't visit the root and wrong url");
  }
});

app.use(function(req, res) {
  res.send("Welcome to the homepage.");
});

app.use(function(err, req, res, next) {
  console.error(err);
  res.status(500);
  next(err);
});

app.use(function(err, req, res, next) {
  res.send("Got an error: " + err);
});

app.listen(3000, function() {
  console.log("App started");
});