codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

19 / 63 topics
19Middleware20Express Framework21Routing22Templates23Handling Forms24Sessions25Authentication26API Development
Tutorials/Node.js/Middleware
🟢Node.js

Middleware

Updated 2026-05-15
10 min read

Middleware

Introduction

In the realm of web development, middleware plays a crucial role. It acts as a bridge between different components in your application, allowing you to handle requests and responses efficiently. Middleware functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack.

Understanding how to use middleware effectively is essential for building robust and scalable Node.js applications. In this tutorial, we'll delve into what middleware is, how it works, and provide practical examples of how to implement and use it in your projects.

Concept

Middleware functions are essentially functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function.

Middleware functions are executed sequentially, one after another. If a middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will hang indefinitely.

Types of Middleware

  1. Application-level middleware: Bound to an instance of the app object using methods like app.use() and app.METHOD().
  2. Router-level middleware: Similar to application-level middleware but bound to an instance of express.Router().
  3. Error-handling middleware: Defined with four arguments instead of three (err, req, res, next).
  4. Built-in middleware: Provided by Express itself, such as express.static and express.json.
  5. Third-party middleware: Middleware functions installed from third-party npm packages.

Examples

Let's explore some practical examples to understand how middleware works in Node.js.

Example 1: Simple Middleware Function

Here’s a simple example of a middleware function that logs the request method and URL:

JavaScript
1const express = require('express');
2const app = express();
3
4// Define a simple middleware function
5function logRequest(req, res, next) {
6 console.log(`${req.method} request for ${req.url}`);
7 next(); // Pass control to the next middleware function
8}
9
10// Use the middleware function
11app.use(logRequest);
12
13// Define a route
14app.get('/', (req, res) => {
15 res.send('Hello World!');
16});
17
18app.listen(3000, () => {
19 console.log('Server is running on http://localhost:3000');
20});
Terminal
Output
Server is running on http://localhost:3000
Error: Something went wrong!
  at /path/to/app.js:7:15
  ...
Something broke!

In this example, the errorHandler middleware function catches errors thrown by routes and sends a 500 status code with an error message.

Example 3: Using Third-Party Middleware

Third-party middleware can be installed via npm and used to enhance your application. For instance, let's use the body-parser middleware to parse JSON request bodies:

JavaScript
1const express = require('express');
2const bodyParser = require('body-parser');
3
4const app = express();
5
6// Use body-parser middleware to parse JSON request bodies
7app.use(bodyParser.json());
8
9// Define a route that accepts POST requests with JSON data
10app.post('/data', (req, res) => {
11 console.log(req.body); // Log the parsed JSON data
12 res.send('Data received');
13});
14
15app.listen(3000, () => {
16 console.log('Server is running on http://localhost:3000');
17});
Terminal
Output
Server is running on http://localhost:3000
POST /data {"name":"John","age":30}
Data received

In this example, the body-parser middleware parses JSON request bodies and makes them available in req.body.

What's Next?

Now that you have a solid understanding of middleware in Node.js, it’s time to dive deeper into the Express Framework. The Express framework provides a robust set of features for building web applications and APIs, including built-in middleware, routing, and templating support.

In the next section, we will explore how to use Express to build more complex applications with ease. Stay tuned!

Info

Remember, middleware is a powerful tool in your Node.js development toolkit. Use it wisely to create efficient and maintainable code.

PreviousError HandlingNext Express Framework

Recommended Gear

Error HandlingExpress Framework