Using Middleware In Express Nodejs

Using Middleware In Express Nodejs

Express is a routing and middleware web framework, it has some functionality of its own: An Express application is a series of middleware function calls.

Middleware functions are functions that have access to the request and response object (res). The next middleware function is commonly used in the named next.

This functions can do the following tasks:

  • Execute any block of code.

  • It can do some changes before the request and the response objects.

  • It will end the request-response cycle.

  • If we used next in any of the middleware function it can execute the next function in the stack of functions.


var express = require('express')
var app = express()

app.get('/', function (req, res, next) {
    console.log('Middleware Basic First Route');
    //res.send('Middleware Basic!')
  next();
},function (req, res, next) {
    console.log('Middleware Basic Next Route');
  // render a regular page
  res.send('Middleware Basic')
})

var server = app.listen(3000, function() {
    console.log('Listening Port : 3000 ');
});

Output


Listening Port : 3000
Middleware Basic First RouteMiddleware Basic Next Route

We can add a middleware to the application, called “myConsole” it will display the console messageg in node terminal when we run the application.

Middleware function myConsole

When a request passed to the path, this middleware will get executed , the function is assigned to a variable “myConsole”

To load middleware function, call app.use(), mention the middleware function. Below code loads the “myConsole” middle-ware function before the route to the root path (‘/’).


var express = require('express')
var app = express()

var myConsole = function (req, res, next) {
  console.log('middleware text')
  next()
}

app.use(myConsole)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

var server = app.listen(3000, function() {
    console.log('Listening Port : 3000 ');
});

What is this next()?

A middleware is basically a function that will the receive the Request and Response objects, just like your route Handlers do. As a third argument you have another function which you should call once your middleware code completed. This means you can wait for asynchronous database or network operations to finish before proceeding to the next step.

next() call inside a middleware invokes the next middleware or route handler depending on whichever is declared next. But next() call inside a route handler invokes the next route handler only. If there is a middleware next then it’s skipped. Therefore middlewares must be declared above all route handlers.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Express provides us app.use() method which is specifically used to define middlewares.


var app = require("express")();
function checkLogin() {
    return true;
}
function logRequest() {
    console.log("New Log request");
}
app.use(function (req, res, next) {
    logRequest();
    next();
})
app.use(function (req, res, next) {

    if (checkLogin()) {
        //Here we can not use res.send , 
        //if we do it will respond the string btu will not execute the next function
        console.log("You are logged in!!!");
        next();
    } else {
        res.send("You are not logged in!!!");
    }
})
app.get("/home", function (req, res, next) {
    res.send("This is the home page");
});
app.get("/about", function (req, res, next) {
    res.send("This is the about page");
});
var server = app.listen(3000, function () {
    console.log('Listening Port : 3000 ');
});

Here the first two defined functions are called as middleware because they are not handling the request rather responsible for pre-processing of the request.

Leave a Reply

Your email address will not be published. Required fields are marked *