Using next() function in Express.js

Express JSServer Side ProgrammingProgramming

Express.js is a powerful tool for building web servers to hit API at backend. It has several advantages which makes it popular, however it has got some drawbacks too, for example, one needs to define different routes or middleware to handle different incoming requests from the client.

In this article, we will see how to use the next() function in a middleware of Express.js. There are lots of middleware in Express.js. We will use the app.use() middleware to define the handler of the particular request made by client.

Syntax

app.use(path, (req, res, next) )

Parameters

  • path – This is the path for which the middleware will be called.

  • callback – This is the callback function that will be called in case of any error or to call the next middleware function.

Example 1

Create a file with the name "next.js" and copy the following code snippet. After creating the file, use the command "node next.js" to run this code.

Without next() function

// next() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a Middleware
app.use("/", (req, res, next) => {
   console.log("Welcome to TutorialsPoint");
   // There is no next() function calls here
})

// Creating another middlware
app.get("/", (req, res, next) => {
   console.log("Get Request")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Without the next() function, you can see that only the first function is called and the other function is not.

Output

C:\home\node>> node next.js
Server listening on PORT 3000
Welcome to TutorialsPoint

Example 2

Let’s take a look at one more example

// next() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a Middleware
app.use("/", (req, res, next) => {
   console.log("Welcome to TutorialsPoint");

   // Calling the next() function here
   next();
})

// Creating another middlware
app.get("/", (req, res, next) => {
   console.log("Got Request")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

When the next() function is called, both the first function and the next function are called with the passed API endpoint.

Output

C:\home\node>> node next.js
Server listening on PORT 3000
Welcome to TutorialsPoint
Get Request
raja
Published on 01-Oct-2021 06:52:17
Advertisements