Middleware in Express.js – GeeksforGeeks

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. In this article, we will discuss what is middleware in express.js 

Express.js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response. Middleware has the access to the request object, responses object, and next, it can process the request before the server send a response. An Express-based application is a series of middleware function calls.
 

Advantages of using middleware:

  • Middleware can process request objects multiple times before the server works for that request.
  • Middleware can be used to add logging and authentication functionality.
  • Middleware improves client-side rendering performance.
  • Middleware is used for setting some specific HTTP headers.
  • Middleware helps for Optimization and better performance.

Middleware Chaining: Middleware can be chained from one to another, Hence creating a chain of functions that are executed in order. The last function sends the response back to the browser. So, before sending the response back to the browser the different middleware process the request.

The next() function in the express is responsible for calling the next middleware function if there is one.

Modified requests will be available to each middleware via the next function –

In the above case, the incoming request is modified and various operations are performed using several middlewares, and middleware is chained using the next function. The router sends the response back to the browser.

Middleware Syntax: The basic syntax for the middleware functions are as follows –

app.get(path, (req, res, next) => {}, (req, res) => {})

Middleware functions take 3 arguments: the request object, the response object, and the next function in the application’s request-response cycle, i.e., two objects and one function.

Middleware functions execute some code that can have side effects on the app, and usually add information to the request or response objects. They are also capable of ending the cycle by sending a response when some condition is satisfied. If they don’t send the response when they are done, they start the execution of the next function in the stack. This triggers calling the 3rd argument, next().

The middle part (req,res,next)=>{} is the middleware function. Here we generally perform the actions required before the user is allowed to view the webpage or call the data and many other functions. So let us create our own middleware and see its uses.

Let us create our middleware and see that how it executes.

Step 1: Go to your project directory and enter the following command to create a NodeJs project. Make sure that NodeJs is installed in your machine.

npm init -y

It will create a package.json file. 

Step 2: Install two dependencies using the following command.

npm install express nodemon

Step 3: In the scripts section of the package.json file, add the following code line.

"start": "nodemon index.js", 

Step 4: Create an index.js file in the directory. Make sure that it is not inside any subdirectories of the directory you are working in.

Project Structure: It will look like the following. 

Now we will set up our express app and send a response to our server.

Here is the code for the index.js file.

Javascript




const express = require("express");

const app = express();

 

const port = process.env.port || 3000;

app.get("/", (req, res) => {

  res.send(`<div>

    <h2>Welcome to GeeksforGeeks</h2>

    <h5>Tutorial on Middleware</h5>

  </div>`);

});

app.listen(port, () => {

  console.log(`Listening to port ${port}`);

});



Step to run the application: Run the code by entering the following command on the terminal.

npm start

Output:

Create a Middleware: In the app.get() function, modify according to the following code.

index.js

Javascript




app.get(

  "/",

  (req, res, next) => {

    console.log("hello");

    next();

  },

  (req, res) => {

    res.send(`<div>

    <h2>Welcome to GeeksforGeeks</h2>

    <h5>Tutorial on Middleware</h5>

  </div>`);

  }

);



Output:

My Personal Notes

arrow_drop_up