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
🚂

Express.js

15 / 76 topics
4Routing in Express.js5Middleware Functions6Error Handling in Express.js15Creating Custom Middleware16Handling Asynchronous Operations in Middleware19Route Parameters in Express.js23Error-Handling Middleware
Tutorials/Express.js/Creating Custom Middleware
🚂Express.js

Creating Custom Middleware

Updated 2026-05-15
10 min read

Creating Custom Middleware

Introduction

Middleware functions in Express.js 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 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.

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 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.

Middleware functions are executed sequentially, and each middleware function has the ability to decide whether or not to pass control to the next middleware function in the stack by calling next(). If a middleware function does not call next(), the request will hang indefinitely.

Concept

In Express.js, middleware functions can be created and used in several ways:

  1. Built-in Middleware: Express provides some built-in middleware functions that you can use directly.
  2. Third-party Middleware: There are numerous third-party middleware packages available on npm that you can integrate into your application.
  3. Custom Middleware: You can also create your own custom middleware functions to handle specific tasks.

Creating Custom Middleware

Creating a custom middleware function is straightforward. A middleware function takes three parameters: req, res, and next. Here’s how you can define a simple custom middleware function:

JavaScript
1const myMiddleware = (req, res, next) => {
2console.log('This is my custom middleware!');
3next(); // Pass control to the next middleware function
4};

Using Custom Middleware

Once you have defined a custom middleware function, you can use it in your Express application by calling app.use() and passing the middleware function as an argument. Here’s how you can do that:

JavaScript
1const express = require('express');
2const app = express();
3
4// Define a custom middleware function
5const myMiddleware = (req, res, next) => {
6console.log('This is my custom middleware!');
7next(); // Pass control to the next middleware function
8};
9
10// Use the custom middleware function
11app.use(myMiddleware);
12
13// Define a route
14app.get('/', (req, res) => {
15res.send('Hello World!');
16});
17
18// Start the server
19app.listen(3000, () => {
20console.log('Server is running on port 3000');
21});

When you run this code and navigate to http://localhost:3000, you will see the message "This is my custom middleware!" logged in the console, followed by "Hello World!" as the response from the server.

Practical Example

Let’s create a more practical example of a custom middleware function that checks if a user is authenticated before allowing access to certain routes. We’ll use a simple authentication mechanism where we check for a specific header value.

JavaScript
1const express = require('express');
2const app = express();
3
4// Define an authentication middleware function
5const authenticate = (req, res, next) => {
6const authHeader = req.headers['authorization'];
7if (!authHeader || authHeader !== 'Bearer my-secret-token') {
8 return res.status(401).send('Unauthorized');
9}
10next(); // Pass control to the next middleware function
11};
12
13// Use the authentication middleware for a specific route
14app.get('/protected', authenticate, (req, res) => {
15res.send('This is a protected route!');
16});
17
18// Define a public route
19app.get('/', (req, res) => {
20res.send('Hello World!');
21});
22
23// Start the server
24app.listen(3000, () => {
25console.log('Server is running on port 3000');
26});

In this example, we have defined an authenticate middleware function that checks for a specific authorization header. If the header is missing or incorrect, it returns a 401 Unauthorized response. Otherwise, it calls next() to pass control to the next middleware function.

When you run this code and navigate to http://localhost:3000/protected, you will need to include the correct authorization header (Authorization: Bearer my-secret-token) in your request. If the header is missing or incorrect, you will receive a 401 Unauthorized response.

What's Next?

In the next section, we will explore how to handle asynchronous operations within middleware functions. This is particularly important when dealing with database queries or other I/O operations that require waiting for a response.

Stay tuned!


PreviousAPI Routing and RESTful ServicesNext Handling Asynchronous Operations in Middleware

Recommended Gear

API Routing and RESTful ServicesHandling Asynchronous Operations in Middleware