0
0
Node.jsframework~3 mins

Middleware vs decorator pattern in Node.js - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how to keep your code neat while adding powerful features effortlessly!

The Scenario

Imagine building a web server where you have to add logging, authentication, and error handling by writing the same code inside every function that handles requests.

The Problem

Manually adding these features everywhere is tiring, easy to forget, and makes your code messy and hard to change later.

The Solution

Middleware and decorator patterns let you add these extra features in one place, so your main code stays clean and you can reuse the added behavior easily.

Before vs After
Before
function handleRequest(req, res) {
  console.log('Request received');
  if (!req.user) { res.status(401).send('Unauthorized'); return; }
  try {
    // main logic
  } catch (e) {
    res.status(500).send('Error');
  }
}
After
app.use(loggingMiddleware);
app.use(authMiddleware);
app.use(errorHandlingMiddleware);
app.get('/data', mainHandler);
What It Enables

You can build flexible, clean, and reusable code that adds features like logging or security without touching your main logic.

Real Life Example

Think of a coffee shop where the barista focuses on making coffee, while other staff handle taking orders, payments, and cleaning separately--each with their own role but working together smoothly.

Key Takeaways

Manual repetition of extra features is slow and error-prone.

Middleware and decorators add behavior cleanly and reuse it.

This keeps your code simple and easier to maintain.