DEV Community

Jemarie Baldespiñosa
Jemarie Baldespiñosa

Posted on

Mastering Custom Middlewares in Express.js: Enhancing Your Node.js Apps

Custom middlewares in Express.js allow you to add your own logic and functionality to the request-response cycle of your application. These middlewares are functions that can be executed before or after route handlers, and they can perform tasks such as authentication, authorization, logging, data validation, and more. Here's how to create and use custom middlewares in Express.js:

  1. Creating a Custom Middleware:

To create a custom middleware, define a function that takes three arguments: req (the request object), res (the response object), and next (a function to call the next middleware in the chain). The next function is crucial because it allows the middleware to pass control to the next middleware or route handler in the chain.

Here's an example of a simple custom middleware that logs the current timestamp for every incoming request:

   function logTimestamp(req, res, next) {
     console.log(`Request received at ${new Date()}`);
     next(); // Call the next middleware or route handler
   }
Enter fullscreen mode Exit fullscreen mode
  1. Using the Custom Middleware:

To use the custom middleware, simply pass it as a function to app.use() or specify it for a specific route using app.use() or app.METHOD(). Here's how you can use the logTimestamp middleware:

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

   // Use the custom middleware for all routes
   app.use(logTimestamp);

   // Define your route handlers
   app.get('/', (req, res) => {
     res.send('Home Page');
   });

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

In this example, the logTimestamp middleware is used for all routes. It logs the timestamp before passing control to the route handler.

  1. Order of Middleware Matters:

The order in which you use middlewares is important. Middlewares are executed in the order they are defined. Be mindful of the order to ensure that the middleware functions are called in the desired sequence.

  1. Conditionally Using Middleware:

You can also conditionally use middleware based on specific routes or conditions. For example, you might want to apply authentication middleware only to certain routes. Use app.use() or app.METHOD() as needed to apply middleware selectively.

Custom middlewares in Express.js provide a flexible way to add functionality and logic to your application at various stages of the request-response cycle. You can create as many custom middlewares as needed to suit the requirements of your application.


*TRUE LEARNERS WOUDN'T QUIT *

  1. "Embrace the journey of learning. Every step forward is a step toward greatness."

  2. "Learning is the key that unlocks the doors to a world of possibilities."

  3. "Challenge yourself to learn something new every day, and watch your potential unfold."

  4. "In the world of knowledge, there are no shortcuts. Every lesson learned is a stepping stone to success."

  5. "Don't be afraid to stumble. Every mistake is a lesson, and every lesson makes you stronger."

  6. "Education is your passport to a brighter future. Invest in yourself and watch your dreams take flight."

  7. "Learning is not a destination; it's a lifelong journey. Keep moving forward."

  8. "The pursuit of knowledge is a noble endeavor. Let curiosity be your guide."

  9. "Believe in your ability to learn, grow, and achieve. The sky is not the limit; it's just the beginning."

  10. "Education is the foundation upon which you can build anything. Start today and build your dreams."

-Jemarie Baldespiñosa

Top comments (0)