Open In App

Middleware in Express

Improve
Improve
Like Article
Like
Save
Share
Report

Express serves as 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 and access to the request object, responses object, and next, it can process the request before the server sends a response. An Express-based application is a series of middleware function calls. In this article, we will discuss what is middleware in express.js.

middleware working

Middleware working

What is Middleware in Express JS

Middleware is a request handler that allows you to intercept and manipulate requests and responses before they reach route handlers. They are the functions that are invoked by the Express.js routing layer.

It is a flexible tool that helps in adding functionalities like logging, authentication, error handling, and more to Express applications. 

Middleware Syntax

The basic syntax for the middleware functions is:

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.

Using Middleware in Express

Follow the steps below to use Middleware in Express.js:

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

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:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.18.2",
}

Step 5: 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:

middleware output

Example

Creating a Middleware in the app.get() function, modify accordingly to the following code.

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:

middleware example output

Middleware

Types of Middleware

Express JS offers different types of middleware and you should choose the middleware on the basis of functionality required.

  • Application-level middleware: Bound to the entire application using app.use() or app.METHOD() and executes for all routes.
  • Router-level middleware: Associated with specific routes using router.use() or router.METHOD() and executes for routes defined within that router.
  • Error-handling middleware: Handles errors during the request-response cycle. Defined with four parameters (err, req, res, next).
  • Built-in middleware: Provided by Express (e.g., express.static, express.json, etc.).
  • Third-party middleware: Developed by external packages (e.g., body-parser, morgan, etc.).

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 processes 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

middleware chaining example

Middleware chaining example

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.

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 with Optimization and better performance.


Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads