Express.js is a popular web application framework for Node.js that simplifies the process of building web servers and APIs. One of its powerful features is middleware, which allows developers to add custom functionality to request handling. Creating custom middleware can help you handle authentication, logging, error handling, and more with ease.

What is Middleware in Express.js?

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. They can execute code, modify request and response objects, end the request-response cycle, or call the next middleware in line.

Steps to Create Custom Middleware

Follow these steps to create and use custom middleware in your Express.js application effectively.

Step 1: Define Your Middleware Function

Create a function that takes three parameters: req, res, and next. Inside this function, add your custom logic.

For example, a simple logging middleware that logs the request method and URL:

function logRequest(req, res, next) {
  console.log(\`Received \${req.method} request for \${req.url}\`);
  next();
}

Step 2: Register Middleware in Your Express App

Use the app.use() method to register your middleware globally or specify routes for targeted middleware.

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

app.use(logRequest);

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

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

Advanced Tips for Custom Middleware

Enhance your middleware by handling errors, managing asynchronous operations, or adding conditional logic.

Handling Errors in Middleware

Define middleware functions with four parameters to catch errors:

function errorHandler(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
}

Asynchronous Middleware

Use async functions for middleware that performs asynchronous operations like database calls:

async function fetchData(req, res, next) {
  try {
    req.data = await database.getData();
    next();
  } catch (err) {
    next(err);
  }
}

Conclusion

Creating custom middleware in Express.js allows you to modularize your application's functionality, improve code reuse, and maintain clean code architecture. By defining middleware functions and registering them appropriately, you can enhance your server's capabilities to handle logging, authentication, error handling, and more efficiently.