Node JS Tutorial - Middleware

In this tutorial, we will learn about Middleware functions, which have 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.

In Express, we can use two types of middleware: application-level middleware and route-level middleware.

Application-Level Middleware

Let's start with application-level middleware. Open the index.js file and add the middleware to the app:


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

Save the changes and run the application. Switch to the command prompt and run the index.js file:


node index.js

Now, go to the browser and navigate to the URL localhost:3000. You should see the current date and time displayed, indicating that the application-level middleware is applied.

If you change the route to /about or /contact, you will still see the date and time displayed, demonstrating that the middleware is applied to the entire application.

Route-Level Middleware

Next, let's explore route-level middleware. Open the index.js file and add the middleware to the about route:


app.get('/about', function (req, res, next) {
console.log('Time: ' , Date.now())
res.render('about');
});

Run the application again. Switch to the command prompt and re-run the index.js file:


node index.js

Now, go to the browser and navigate to the URL /about. You should see the date and time displayed. However, if you change the URL to /contact, the date and time will not be displayed, demonstrating that the middleware is only applied to the about route.

This is how you can use middleware in Node.js.