How to Build Middleware for Node JS: A Complete Guide
Last Updated :
23 Jul, 2024
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.
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:
- Application-Level Middleware: These middleware functions are bound to an instance of
express()
and can handle requests for specific routes or the entire application. - 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. - 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.
- 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. - 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:
output when age = 18
output when age != 18Middleware 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:
outputConclusion
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.
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
How to build Love Calculator using Node.js ?
In this article, we are going to create a Love Calculator. A Love Calculator is used to calculate the love percentage between the partners. Functionality: Take User's NameTake User's Partner NameShow the Love PercentageApproach: We are going to use Body Parser by which we can capture user input valu
5 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 share code between Node.js and the browser?
In this article, we will explore how to write JavaScript modules that can be used by both the client-side and the server-side applications.We have a small web application with a JavaScript client (running in the browser) and a Node.js server communicating with it. And we have a function getFrequency
4 min read
Getting Started With ReactJS: A Complete Guide For Beginners
Every front-end developer and web developer knows how frustrating and painful it is to write the same code at multiple places. If they need to add a button on multiple pages they are forced to do a lot of code. Developers using other frameworks face the challenges to rework most codes even when craf
7 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 Create Modules in Node.js ?
Modules are the building blocks of NodeJS code. They help you break down your project into smaller, manageable pieces, each with its own job. To create a module, just make a JavaScript file and export what you want to share. Other files can then import and use those exports, adding that functionalit
3 min read