AppDividend
Latest Web Development Tutorials

Express Middleware Tutorial Example From Scratch

Express Middleware Tutorial

215

Express Middleware Tutorial Example From Scratch is today’s leading topic.  Express works like when we hit the request on the server; it must return a  response of a webpage like HTML or PHP or send a JSON response to the API call. Express is a very lightweight web framework. It comes with some features like Middleware. Middleware function is a function that has 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.

Middleware function can perform the following tasks.

  • Can execute any code.
  • Can make changes to the request and the response objects.
  • Can end the request-response cycle.
  • Can call the next middleware function in the stack.

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, and you will be stuck on the particular webpage and just loading and loading and so on.

Express Middleware Tutorial

If you are building Node js Express Web Application, then you have already used an express middleware. I will give you an example.

// For serving static files

app.use(express.static('public'));

// For parses incoming post request data

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

As we have discussed earlier, it has next() function is available. If I want to log anything for each incoming request, then I need to write following code.

const logger = function (req, res, next) {
  console.log('Middleware is used first time');
  next();
}

Similarly, there is one Node package called Morgan which is doing the same thing. Log all the request in the console. In actual Node js application, we can use the middleware like following.

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

const logger = function (req, res, next) {
  console.log('caught intrusion');
  next();
}

app.use(logger);

app.get('/', function (req, res) {
  res.send('Express middleware tutorial');
});

app.listen(3000);

Authentication Example

If we have to check whether the user has logged in or not for the current route or try to access authenticated route, then we can write the following tutorial.

router.get('/', isLoggedIn, function(req, res){
  	res.render('pages/index');
});

function isLoggedIn(req, res, next){
    if(req.isAuthenticated()){
        next();
    }
    else{
        res.redirect("/users/login");
    }
}

In above example is also called “Route Middleware.” It checks the request to see if the user is authenticated or not. Based on the function response, it will redirect the user accordingly.



Configurable middleware

If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.

Related Posts
1 of 6
// First.middleware.js

module.exports = function(options) {
  return function(req, res, next) {
    // Implement the middleware function based on the options object
    next();
}

Now, use this middleware in our server.js file or name it as you want.

// server.js

var Fm = require('./First.middleware.js');

app.use(Fm({ option1: 'App', option2: 'Dividend' }));

Types of  Express Middleware

There are mainly five types of middlewares.

Application-level middleware

Bind application-level middleware to an instance of the app object by using the app.use().

This example shows a middleware function with no mount path. Every time user sends a request, the middleware function always runs.

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

const logger = function (req, res, next) {
  console.log('caught intrusion');
  next();
}

app.use(logger);

app.get('/', function (req, res) {
  res.send('Express middleware tutorial');
});

Router-level middleware

Router-level middleware bound to an instance of express.router().

const router = express.Router();

Load router-level middleware by using the router.use() function.

const app = express();
const router = express.Router();

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

Error-handling middleware

Define error-handling middleware functions with four arguments instead of three, specifically with the signature (err, req, res, next).



app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Whoops! Something went wrong');
});

Built-in middleware

Express has the following built-in middleware functions:

Third-party middleware

Install the Node.js package for the required functionality, then load it in your application at the application level or the router level. We have already seen the body-parser middleware, which is third-party middleware.

Finally, our Express Middleware Tutorial is over.

Leave A Reply

Your email address will not be published.