Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Node.js Roadmap: A Complete Guide
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
Node.js Roadmap: A Complete Guide

F

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

Similar Reads

  • 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 Use MERN Stack: A Complete Guide
    The MERN stack, comprising MongoDB, ExpressJS, ReactJS, and NodeJS, is a powerful framework for building modern web applications. MongoDB offers a scalable NoSQL database, ExpressJS simplifies server-side development, ReactJS creates dynamic user interfaces, and NodeJS enables server-side JavaScript
    9 min read
  • Edge Functions and Middleware in Next JS
    Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO
    4 min read
  • Implementing Csurf Middleware in Node.js
    Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSR
    4 min read
  • Next JS File Conventions: middleware.js
    In Next.js, the middleware.js file is one powerful tool to add custom functionality through the request/response cycle of the application. It is able to run some code before finalizing a request, which may involve actions such as authentication, logging, or even rewriting of URLs. Middleware can be
    7 min read
  • How to skip a middleware in Express.js ?
    If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init
    1 min read
  • How to add new functionalities to a module in Node.js ?
    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 how to add new functi
    3 min read
  • How to build Node.js Blog API ?
    In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters. Functionalities: Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we
    5 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
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