Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How To Build A Node.js API For Ethereum
Next article icon

How to Build Middleware for Node JS: A Complete Guide

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application.

Building middleware for Node.js involves creating custom functions to process and manage requests and responses. Middleware can handle tasks like authentication, logging, and error handling, enhancing your application's functionality and modularity.

In this article, we will discuss how to build middleware for NodeJS applications and the following terms.

Table of Content

  • What is Middleware?
  • Key Features of Middleware
  • Steps to Create Your Middleware in Node
  • Middleware Execution Order
  • Handling Errors in Middleware
  • Conclusion

What is Middleware?

Middleware in NodeJS is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it's work is to make the Express framework more powerful and flexible. It allows users to insert additional steps or actions in the process of handling a request and generating a response. It's like having a toolkit that you can use to adapt how your web server works for specific tasks.

Syntax:

const createMiddleware = (req, res, next) => {
console.log('Middleware executed');
// Call next middleware function
next();
};
  • req (request):
    • The message of your server receives from the client.
    • It holds all the details about what the client is asking for, like which URL they want and any data they're sending.
  • res (response):
    • This is like the message your server sends back to the client.
    • You use it to decide what to send back, like web pages, JSON data, or images.
  • next:
    • It's a way to tell your server to move on to the next task.
    • When you're done with one job, you call next() to say, "Okay, go ahead and handle the next thing."

Types of Middleware

Here are the main types of middleware in Node.js:

  1. Application-Level Middleware: These middleware functions are bound to an instance of express() and can handle requests for specific routes or the entire application.
  2. Router-Level Middleware: These middleware functions are bound to an instance of express.Router(). They are used to define middleware for specific routes or sets of routes.
  3. Error-Handling Middleware: These middleware functions are defined with four arguments: (err, req, res, next). They are used to catch and handle errors that occur during the processing of requests.
  4. Built-In Middleware: Express comes with a few built-in middleware functions, such as express.static(), express.json(), and express.urlencoded(), which are used to serve static files, parse JSON bodies, and parse URL-encoded bodies, respectively.
  5. Third-Party Middleware: These are middleware functions provided by third-party libraries, which can be installed via npm and used in your application. Examples include morgan for logging, body-parser for parsing request bodies, and cors for enabling CORS.

Key Features of Middleware

  • Request and Response Handling: Middleware helps manage how your web server interacts with incoming requests and outgoing responses.
  • Orderly Processing: You can set up middleware functions to run one after another, handling different parts of the request as needed.
  • Easy Customization: You can easily add, remove, or change middleware to fit your application's specific needs.
  • Error Management: Middleware can catch and deal with errors that occur during the request-response cycle, making error handling easier.
  • Common Tasks Made Easy: It's great for doing common tasks like user authentication, logging, or data compression, saving you time and effort.
  • Lots of Choices: There are tons of middleware modules available, so you can find one that does what you need without starting from scratch.
  • Works Well with Frameworks: Middleware plays nicely with popular frameworks like ExpressJS, making it easy to build web applications.
  • Good Performance: It's designed to be efficient and not slow your app down, so you can focus on making your app awesome.

Steps to Create Middleware in Node

Step 1: Create a new folder for your project

npm init -y

Step 2: Create and setup a basic server.

let's create a file (i.e server.js) and define a simple middleware that logs information about each incoming request.

JavaScript
// server.js

const http = require('http');
const url = require('url');

// Middleware function
function checkAgeMiddleware(req, res, next) {
	const parsedUrl = url.parse(req.url, true);
	const age = parsedUrl.query.age;

	if (age === '18') {
		// next middleware is called
		next();
	} else {
		res.writeHead(403, { 'Content-Type': 'text/plain' });
		res.end('Access denied. You must be 18 years old.');
	}
}

const PORT = 4000;

const server = http.createServer((req, res) => {
	// use middleware
	checkAgeMiddleware(req, res, () => {
		// Middleware is completed now handle the call.
		res.writeHead(200, { 'Content-Type': 'text/plain' });
		res.end('Welcome! You are allowed access.');
	});
});

server.listen(PORT, () => {
	console.log(`Server is running at http://localhost:${PORT}`);
});

Start your server using the following command.

node server.js

Output:

Screenshot-2024-07-19-234554
output when age = 18


Screenshot-2024-07-19-234538
output when age != 18

Middleware Execution Order

The way you arrange middleware is important. Middleware functions are carried out in the order they are added using 'app.use()' or 'app.METHOD()'. Imagine it like a sequence – if you place your logging middleware after the route handler, it won't log anything because the response would have already been sent. So, the order of adding middleware matters for them to work as expected.

Handling Errors in Middleware

It is used to handle erros in your application. If you pass an error to the next() function, express will skip all remaining middleware and trigger the error-handling middleware.

Example: Below are the example of handling errors in middleware.

JavaScript
const http = require('http');

const PORT = 4000;

const server = http.createServer((req, res) => {
	if (req.url === '/') {
		throw new Error('Oops! Something Went Wrong');
	}
});

server.on('error', (err) => {
	console.error(err.stack);
	// Respond with 500 status and error message
	res.writeHead(500, { 'Content-Type': 'text/plain' });
	res.end('Something went wrong!');
});

server.listen(PORT, () => {
	console.log(`Server is running at http://localhost:${PORT}`);
});

Start your application using the following command.

node server.js

Output:

Screenshot-2024-07-19-234642
output

Conclusion

You've successfully built and implemented middleware for your Node.js application. Middleware plays a crucial role in Express, allowing you to customize and enhance your application's functionality at various stages of the request-response cycle. Experiment with different middleware functions and explore the vast possibilities they offer in building robust and feature-rich web applications with Node.js.


Next Article
How To Build A Node.js API For Ethereum

F

faheemakt6ei
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • NodeJS-Questions

Similar Reads

    How To Build A Node.js API For Ethereum
    Ethereum is a popular blockchain platform that allows developers to build decentralized applications (dApps). It uses a smart contract system that enables the execution of self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code.The
    8 min read
    How To Build A Node.js API For Ethereum
    Ethereum is a popular blockchain platform that allows developers to build decentralized applications (dApps). It uses a smart contract system that enables the execution of self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code.The
    8 min read
    Node.js Roadmap: A Complete Guide
    Node.js has become one of the most popular technologies for building modern web applications. It allows developers to use JavaScript on the server side, making it easy to create fast, scalable, and efficient applications. Whether you want to build APIs, real-time applications, or full-stack web apps
    6 min read
    How to create custom middleware in express ?
    Express.js is the most powerful framework of the node.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. Express.js use different kinds of middleware functions in order to complete the different
    2 min read
    Built-in Middleware Functions in Express.js
    Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when ca
    4 min read
    How to Use Node.js for Backend Web Development?
    In the world of website design nowadays, NodeJS is a supportive tool for making capable backend systems. Whether you are an experienced web designer or just beginning out, NodeJS can upgrade your aptitude and help you in building extraordinary websites. This guide will show you how to use NodeJS to
    8 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences