Middleware functions are functions that have the 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". 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.
- Node.js: V8 JavaScript Engine - Day One
- Node.js: Modules - Day Two
- Node.js: Event And Event Emitter - Day Three
- Node.js: Callbacks - Day Four
- Node.js: File System - Day Five
- Node.js: Buffer - Day Six
- Node.js - Prototype Inheritance - Day Seven
- Node.JS - Web Server - Day Eight
- Node.JS - Express - Day Nine
- End the Request Response Cycle
- Execute any code
- Make changes to Request-Response Cycle
- Call next Middleware function.
Let’s take a simple example of middleware function.
Example
- var express = require('express');
- var app = express();
- var fun1 = function (req, res, next) {
- console.log("This is Fun1 Middleare funcion");
- next();
- };
- var fun2 = function (req, res, next) {
- console.log("This is Fun2 Middleare funcion");
- next();
- };
- app.use('/', fun1);
- app.use('/', fun2);
- app.get('/', function (req, res) {
- res.send("Hello! World");
- })
- app.listen(1400);

In this example. we have created two middleware functions that execute or run before the response is sent to the client. Each middleware function contains three parameters. First parameter denotes the request object, second parameter denotes the response object, and the last parameter denotes the next middleware function.
Order of the execution of middleware function will be similar to the order in which they are used or included in file.
Change in Request or Response Objects
As I said, the middleware function can be used to change the request or response object. Let’s take an example.
Example
- var express = require('express');
- var app = express();
- var fun1 = function (req, res, next) {
- console.log("This is Fun1 Middleare funcion");
- req.requestTime = Date.now()
- next();
- };
- app.use('/', fun1);
- app.get('/', function (req, res) {
- res.send("<h2>Requested At: "+ req.requestTime+"</h2>");
- })
- app.listen(1400);

In this example, we have created a middleware function that takes the request object and attaches the requestTime property to request object.
Types of Middleware function
Express supports five types of middleware functions.
- Application Level Middleware function
- Router Level Middleware function
- Exception Handling Middleware function
- Built-In Middleware function
- Third-Party Middleware function
Application Middleware Function
In application level middleware functions, functions are bound to an instance of the app object, by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as, GET, PUT, or POST) in lowercase.
Example
- var express = require('express');
- var app = express();
- var fun1 = function (req, res, next) {
- console.log("This is Fun1 Middleare funcion");
- next();
- };
- var fun2 = function (req, res, next) {
- console.log("This is Fun2 Middleare funcion");
- next();
- };
- var fun3 = function (req, res, next) {
- res.send("Hello! World")
- };
- app.use('/', fun1);
- app.use('/', fun2);
- app.use('/', fun3);
- app.listen(1400);

Router Level Middleware
Router level middleware function works in a similar way to application level middleware, except it binds to the express.Router() object.
Example
Create a router.js file and add the following code into that file.
- var express = require('express')
- var routes = express.Router();
- //Middleware function
- var fun1 = function (req, res, next) {
- console.log("This is Fun1 Middleare funcion");
- next();
- };
- var fun2 = function (req, res, next) {
- console.log("This is Fun2 Middleare funcion");
- next();
- };
- routes.use('/', fun1);
- routes.use('/', fun2);
- //routing
- routes.get('/', function (req, res) {
- res.send("<html><head></head><body><h1>This is demo App</h1></body></html>");
- });
- routes.get('/:id', function (req, res) {
- res.send("Your Id is: " + req.params.id);
- });
- routes.get('/api/:name', function (req, res) {
- res.send("Your Id is: " + req.params.name);
- });
- routes.get('/:name/:id', function (req, res) {
- res.send("Your Id is: " + req.params.id + " and Your Name is : " + req.params.name);
- });
- routes.get('*', function (req, res) {
- res.send("Sorry! URL not found");
- });
- module.exports = routes;
Index.js
- var express_Obj = require('express')
- var express = express_Obj();
- var routes = require('./router.js');
- //Use Router as Middleware
- express.use('/', routes);
- //listener
- express.listen(1400);




Exception Middleware Function
Error handling in Express is done by this kind of middleware. The Error Handling Middleware function takes four parameters. The first parameter defines the error object, the second parameter denotes to the request object, the third parameter denotes to the response object, and the last parameter denotes to the next middleware function.
Example
- var express = require('express');
- var app = express();
- app.get('/', function (req, res) {
- //Create an error and pass it to the next function
- var err = new Error("Something going wrong");
- next(err);
- });
- app.use(function (err, req, res, next) {
- res.status(500);
- res.send("<h2>OOPS, something going wrong.</h2>")
- });
- app.listen(1400);

Built In Middleware Functions
The only built-in middleware function in Express is express.static. This function is based on serve-static, and is responsible for serving static assets such as HTML files, images, and so on.
First create Index.html page and insert the below code in this file.
Index.html
- <!DOCTYPE html>
- <html>
- <head>
- <link rel="stylesheet" href="midStyle.css" />
- </head>
- <body>
- <table>
- <tr>
- <th>Company</th>
- <th>Contact</th>
- <th>Country</th>
- </tr>
- <tr>
- <td>Pankaj</td>
- <td>1234567890</td>
- <td>India</td>
- </tr>
- <tr>
- <td>Rahul</td>
- <td>2345678910</td>
- <td>Mexico</td>
- </tr>
- <tr>
- <td>Sandeep</td>
- <td>6541230789</td>
- <td>Austria</td>
- </tr>
- <tr>
- <td>Sanjeev</td>
- <td>231459870</td>
- <td>UK</td>
- </tr>
- </table>
- </body>
- </html>
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- var express = require('express');
- var fs = require('fs');
- var app = express();
- app.get('/', function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/html' });
- fs.readFile(__dirname + '/index.html', function (err, data) {
- res.end(data.toString());
- })
- });
- app.listen(1400);
Now, run the application in your browser. When you run this application, you will get the below output.

You can see that we get table formatted data that we send as read from the “index.html” page, but it doesn’t contain the style properties that we defined. So, what is going wrong? Let’s check the issue. Now, right click on page and click on “Inspect Element”. In Network section, you will find that for “midStyle.css”, we are getting “404 Not Found” error.


When you save this and run the application, you will get the below output.

You can see that now we get the “200 Ok” status code for “midStyle.css” request. “Express.static” middleware function is used to handle the request for static files, like CSS, JavaScript, images.
Third Party Middleware
Third party middleware functions are used to enhance the functionality of Express. Express uses several types of third party middleware functions like “Body-Parser”, “Cookies_Parser”, “Express-Session”. We will read about these middleware functions in the next articles.
You can get more about third-party middleware here.

Conclusion
In this article, we took a brief introduction about middleware function and how Express handles the request for static files. In the next article, we will cover some more topics of Node.js.

Anu VPosted Nov 21, 2016, 12:26 AM
Nice article.. Thanks for sharing.