Middleware in Express - GeeksforGeeks (2024)

Last Updated : 12 Aug, 2024

Summarize

Comments

Improve

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 in Express - GeeksforGeeks (1)

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.

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.

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.).

Steps to Implement Middleware in Express

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:

Middleware in Express - GeeksforGeeks (2)

Project Structure

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

"dependencies": { "express": "^4.19.2", "nodemon": "^3.1.4"}

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
// Filename - index.jsconst 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 in Express - GeeksforGeeks (3)

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

JavaScript
// Filename - index.jsapp.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 in Express - GeeksforGeeks (4)

Middleware

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 in Express - GeeksforGeeks (5)

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.

Summary

Middleware is a core feature of Express.js, providing a versatile and powerful way to handle requests and responses. Whether you’re implementing custom logging, managing authentication, or handling errors, middleware functions are essential tools for building robust and maintainable web applications.



_mukul_

Middleware in Express - GeeksforGeeks (7)

Improve

Previous Article

Build Your First Router in Node.js with Express

Next Article

Routing Path for ExpressJS

Please Login to comment...

Middleware in Express - GeeksforGeeks (2024)
Top Articles
Emerging Market ETF: Meaning, Pros and Cons
What is the Dissipation of Assets in a Florida Divorce?
Use Copilot in Microsoft Teams meetings
Cranes For Sale in United States| IronPlanet
Dannys U Pull - Self-Service Automotive Recycling
Lost Ark Thar Rapport Unlock
Erskine Plus Portal
Kris Carolla Obituary
CA Kapil 🇦🇪 Talreja Dubai on LinkedIn: #businessethics #audit #pwc #evergrande #talrejaandtalreja #businesssetup…
Erskine Plus Portal
Youtube Combe
The Superhuman Guide to Twitter Advanced Search: 23 Hidden Ways to Use Advanced Search for Marketing and Sales
Chastity Brainwash
Kürtçe Doğum Günü Sözleri
Webcentral Cuny
Why Should We Hire You? - Professional Answers for 2024
Iu Spring Break 2024
Katie Sigmond Hot Pics
Sea To Dallas Google Flights
Airtable Concatenate
Kirsten Hatfield Crime Junkie
2011 Hyundai Sonata 2 4 Serpentine Belt Diagram
Danielle Ranslow Obituary
Skidware Project Mugetsu
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
031515 828
Kleinerer: in Sinntal | markt.de
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Space Marine 2 Error Code 4: Connection Lost [Solved]
Telegram update adds quote formatting and new linking options
Baywatch 2017 123Movies
Wattengel Funeral Home Meadow Drive
Htb Forums
Restored Republic May 14 2023
Busted Newspaper Campbell County KY Arrests
Mugshots Journal Star
Wal-Mart 140 Supercenter Products
Actor and beloved baritone James Earl Jones dies at 93
Bill Manser Net Worth
Pike County Buy Sale And Trade
Television Archive News Search Service
The Bold and the Beautiful
3367164101
A Man Called Otto Showtimes Near Cinemark Greeley Mall
Stoughton Commuter Rail Schedule
Madden 23 Can't Hire Offensive Coordinator
Sams La Habra Gas Price
Wvu Workday
login.microsoftonline.com Reviews | scam or legit check
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5978

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.