Express Middleware

A middleware is just like a function and generally takes 3 parameters. These are loaded with code that could manipulate the parameters that are passed. The parameter used in any middleware is the request object,  the response object, and the next function or middleware which are more commonly denoted as req, res, and next respectively.  Generally, middleware is used when we would want to perform some operation before sending the data back to the client.

Now let’s set up our simple server.

const express = require("express");
const app = express();

app.get('/', (req, res, next) => {
    console.log('This is the ROOT');
    res.send('<h1>Root function</h1>');
})

app.listen(3000);

Now let’s create an Application level middleware

These are middleware which binds to the express instance. These are basically for the entire document and not for a particular route.

app.use(function (req, res, next) {
    console.log('Time:', Date.now())
    next()
})

Since there is no path given, it will get executed whenever the app instance is called.

app.get('/user', function (req, res, next) {
    console.log('1st /user');
    next();
})
app.get('/user', (req, res, next) => {
    console.log('2nd /user');
    res.send('<h1>Responce </h1>');
})

If there are multiple middlewares with express instances then they will be executed in the order they are defined.

            *note- if the middleware does not have either a next function call or it does not end the request & response cycle then the application will be stuck.

Now let’s create a router-level middleware

These are very similar to the application-level middleware except instance of binding it with an express instance we bind it to a route. But first we need to declare a route by

var router = express.Router()

If we need to access that route, we need mount that router to the express instance by

app.use('/', router)

Now all we need to do is define a route-level middleware

router.use(function (req, res, next) {
    console.log('This is router level middleware')
    next()
})

Now let’s create an Error-handling middleware

An error handler in Express is just another type middleware. In order to define it, we have to define a function with a 4th parameter. The ‘err’ parameter will get populated with error if it exist.

function errhandler(err, req, res, next){
    if (err){
        console.log('error handler called');
        res.send('<h1>An Error has occured!</h1>');
    }
}

Since we do not have any error let’s just create it in our /user path and call the error handler middleware

app.get('/user', function (req, res, next) {
    console.log('1st /user');
    const errObj = new Error('I am an error.');
    next(errhandler);
})

Now let’s use a third-party middleware

3rd party middleware is a middleware created by other users which you can use in your application. To use their middleware you first need install the files, then import the middleware into your application then you can use it where required.

Let’s try to use the middleware cookie-parser.

To install use the terminal and use any one of the following command

$ npm install cookie-parser
$ npm i cookie-parser

This will install the required files in your node_modules folder and now we need to import those files into our application. To do that we use require method. When to use the middleware in our application we use the following code.

var cookieParser = require('cookie-parser')
app.use(cookieParser())

This is it for now! Enjoy & Comment :), Thank you!