How to write custom middleware for ExpressJS

Middleware in Express.js is a function that gets executed before HTTP response was formed. One of the famous example is using body-parser in express for extracting POST data. In this tutorial we will learn how to write custom middleware for Express.js project.

We will develop sample project using middle-ware which will check HTTP requests and if the type of request is GET, it will stop it and return the response immediately without going further.

Project setup.

Create a new folder and create package.json in it. We recommend using npm init command to generate sample package.json file.

Once it is created. Install express by using following command.

sudo npm install --save express

Basic Server

Here is our sample app.js code with basic route.

app.js
var express =   require('express');
var app =   express();

app.use(function(req,res) {
    res.send('Hello there !');
});

app.listen(3000);

Run the code by using

node app.js

command and visit localhost:3000 to view the app.

Server with Middleware

Let’s write our middleware function which will check the type of each HTTP request. If it is GET we will not proceed further. Basically the fundamental use of Middleware is to execute various validation code like Session verification, data verification which is common across all the application separately.

To begin with create new file and name it middleware.js and the following code into it.

middleware.js
module.exports = function(req,res,next) {
    if(req.method === 'GET') {
        res.end('GET method not supported');
    } else {
        next();
    }
};

Notice that we are passing request,response and next object in the function which is used to handle the HTTP requests. Now let’s see how to include it in our Server file.

app.js
var express         =   require('express');
var requestChecker  =   require('./middleware.js');
var app             =   express();

/* Add the middleware to express app */
app.use(requestChecker);

// Another middleware, will get executed after above one.
// Order of middleware is sequential.

app.use(function(req,res) {
    res.send('Hello there !');
});

app.listen(3000);

We just added the file into our app using .use() which is inbuilt middleware of Express.js. Now try running the code and visit localhost:3000. You should be getting following message.

Node.js middleware function

Now let’s hit request with HTTP method as POST. Use API Simulator ( We recommend POSTMAN ) to hit the request.

Screen Shot 2015-12-05 at 11.42.15 pm

Since it was POST request, it allows it to pass to next ( Yes next() function does same ) middleware.

Usage of Middleware

One of the possible and effective use of Middleware function is Session validation. We have covered Basic session handling and Session handling using external memory store like Redis, but if you look over the code we are validating whether session is valid or not in every Route.

Instead of that, we can write one common function which will do session validation for us on every request.

We can also use it for data validation or security checking of form submitted data. Most of the security code which has to be executed every single time before going to real resource can be put in middleware function.

Conclusion

We covered how to write custom middleware for Express.js and possible uses of it. Middleware are executed in sequential order so be careful of placement of middleware. Middleware can be use as a good way to structure the code and write a clean and simple to understand code.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126