Building Custom Middleware in Express.js

Middleware Expert 11 min read Framework 890 views
Express.js Middleware Tutorial

What is Middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle.

Types of Middleware

  • Application-level: Bound to app instance using app.use()
  • Router-level: Bound to router instance using router.use()
  • Error-handling: Takes four arguments (err, req, res, next)
  • Built-in: Express built-in middleware like express.json()

Creating Custom Middleware

// Custom middleware
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
    next();
};

Best Practices

  • Always call next() or send a response
  • Handle errors properly
  • Keep middleware focused on a single responsibility
  • Order middleware correctly

Conclusion

Middleware is a powerful concept in Express.js that allows you to add functionality to your application in a modular way. Understanding how to create and use middleware is essential for building robust Express applications.