Home Projects Portfolio Dashboard Export PDF Log in

Implementing Custom Middleware in BACK_DIARIO

The Goal

In the BACK_DIARIO project, we needed a cleaner way to handle cross-cutting concerns like request logging and authentication checks. By integrating custom middleware, we can intercept incoming requests before they reach our route handlers, ensuring that our application logic remains decoupled and modular.

The Implementation

In an Express-based application, middleware acts like a filter in a water pipe. It captures the request, performs an action, and decides whether to let the flow continue to the next step or stop it entirely.

Creating the Middleware

We implemented a simple, reusable middleware function that logs the request method and timestamp. This provides better observability into how users interact with our API:

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

app.use(requestLogger);

This snippet defines a function that receives the req (request), res (response), and next (the callback to trigger the subsequent function). By calling next(), we ensure the Express request lifecycle is not blocked.

Why Middleware Matters

Think of middleware as a security checkpoint at an airport. Every passenger must pass through the metal detector before reaching their gate. If they don't meet the criteria, the process stops. In our code, this pattern allows us to:

  1. Centralize Logic: Keep authentication or validation code in one place.
  2. Improve Debugging: Easily inject logging or error handling without cluttering business logic.
  3. Enhance Modularity: Add or remove features by simply registering or unregistering middleware functions.

Key Takeaway

If you find yourself repeating the same validation or transformation logic across multiple route handlers, it is time to move that code into a custom middleware function. Start by extracting one cross-cutting concern today to simplify your controllers.


Generated with Gitvlg.com

Implementing Custom Middleware in BACK_DIARIO
Zelaya Noelia

Zelaya Noelia

Author

Share: