Express.js Middleware

Express.js is a web application framework for Node.js, designed for building web applications and APIs. One of its core features is middleware. Middleware functions are 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 code, modify the request and response objects, end the request-response cycle, and call the next middleware function.

What is Middleware?

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

If the current 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 be left hanging.

Types of Middleware

  • Application-level Middleware
  • Router-level Middleware
  • Error-handling Middleware
  • Built-in Middleware
  • Third-party Middleware

Application-level Middleware

Application-level middleware is bound to an instance of the app object using app.use() or app.METHOD(), where METHOD is the HTTP method (GET, POST, etc.).

Example:

				
					const express = require('express');
const app = express();

app.use((req, res, next) => {
    console.log('Time:', Date.now());
    next();
});

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • app.use() is used to define middleware that logs the current timestamp for every request.
  • The next() function is called to pass control to the next middleware function in the stack.

Output:

  • When accessing http://localhost:3000/, the console will log the current timestamp, and the browser will display “Hello World!”.

Router-level Middleware

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

Example:

				
					const express = require('express');
const app = express();
const router = express.Router();

router.use((req, res, next) => {
    console.log('Router Time:', Date.now());
    next();
});

router.get('/', (req, res) => {
    res.send('Hello from Router!');
});

app.use('/router', router);

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • router.use() is used to define middleware for the router instance.
  • The middleware logs the timestamp and passes control to the next middleware.
  • The router is mounted on /router.

Output:

  • When accessing http://localhost:3000/router, the console will log the router timestamp, and the browser will display “Hello from Router!”.

Error-handling Middleware

Error-handling middleware functions have four arguments: (err, req, res, next).

Example:

				
					const express = require('express');
const app = express();

app.get('/', (req, res) => {
    throw new Error('Oops!');
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • The middleware function is defined to handle errors.
  • It logs the error stack and sends a 500 status with an error message.

Output:

  • When accessing http://localhost:3000/, the console will log the error stack, and the browser will display “Something broke!”.

Built-in Middleware

Express comes with built-in middleware functions like express.static(), express.json(), and express.urlencoded().

Example:

				
					const express = require('express');
const app = express();

app.use(express.json());

app.post('/user', (req, res) => {
    res.send(`User name is ${req.body.name}`);
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • express.json() middleware parses incoming JSON requests and puts the parsed data in req.body.

Output:

  • Sending a POST request to http://localhost:3000/user with JSON { "name": "John" } will respond with “User name is John”.

Third-party Middleware

There are many third-party middleware functions for Express, such as morgan for logging and body-parser for parsing request bodies.

Example:

				
					const express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan('dev'));

app.get('/', (req, res) => {
    res.send('Morgan Logger Example');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • morgan('dev') logs HTTP requests in a concise format.

Output:

  • Accessing http://localhost:3000/ logs the request details in the console.

Creating Custom Middleware

Custom middleware functions can be created by defining a function that takes req, res, and next as arguments.

Example:

				
					const express = require('express');
const app = express();

const customMiddleware = (req, res, next) => {
    console.log('Custom Middleware');
    next();
};

app.use(customMiddleware);

app.get('/', (req, res) => {
    res.send('Hello from Custom Middleware!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • A custom middleware function logs a message and calls next().

Output:

  • Accessing http://localhost:3000/ logs “Custom Middleware” and displays “Hello from Custom Middleware!”.

Middleware Order

The order of middleware is important. Middleware functions are executed sequentially.

Example:

				
					const express = require('express');
const app = express();

app.use((req, res, next) => {
    console.log('First Middleware');
    next();
});

app.use((req, res, next) => {
    console.log('Second Middleware');
    next();
});

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Explanation:

  • The middleware functions are executed in the order they are defined.

Output:

  • Accessing http://localhost:3000/ logs “First Middleware” followed by “Second Middleware”.

Middleware is a powerful feature of Express.js, allowing developers to modularize and organize their code. Understanding how to create and use middleware functions is essential for building scalable and maintainable web applications.By leveraging different types of middleware, you can handle various aspects of your application, such as logging, authentication, error handling, and more. Custom middleware functions enable you to implement specific functionality tailored to your application's needs.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India