0
0
Node.jsframework~5 mins

Middleware vs decorator pattern in Node.js

Choose your learning style9 modes available
Introduction
Middleware and decorator patterns help add extra features to code without changing the main parts. They keep code clean and easy to manage.
When you want to add logging or security checks to web requests.
When you need to modify or extend behavior of functions or objects without rewriting them.
When you want to handle tasks like authentication or error handling in a chain of steps.
When you want to add features like caching or timing to existing functions.
When you want to keep your code organized by separating extra tasks from main logic.
Syntax
Node.js
Middleware example (Express.js):
app.use(function(req, res, next) {
  // do something
  next();
});

Decorator example:
function decorator(originalFunction) {
  return function(...args) {
    // extra work
    return originalFunction(...args);
  };
}
Middleware functions usually take three arguments: request, response, and next.
Decorators wrap a function to add behavior before or after calling the original function.
Examples
Middleware logs each request before moving to the next step.
Node.js
app.use((req, res, next) => {
  console.log('Request received');
  next();
});
Decorator adds a log message every time the wrapped function runs.
Node.js
function logDecorator(fn) {
  return function(...args) {
    console.log('Function called');
    return fn(...args);
  };
}
Middleware checks if user is logged in before continuing.
Node.js
app.use((req, res, next) => {
  if (!req.user) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
});
Decorator measures how long a function takes to run.
Node.js
function timingDecorator(fn) {
  return function(...args) {
    const start = Date.now();
    const result = fn(...args);
    console.log(`Time: ${Date.now() - start}ms`);
    return result;
  };
}
Sample Program

This example shows middleware logging every request to the server. It also shows a decorator that adds extra text to a greeting function.

When you run this, the server logs requests and prints a decorated greeting once at start.

Node.js
import express from 'express';
const app = express();

// Middleware to log requests
app.use((req, res, next) => {
  console.log(`Received ${req.method} request for ${req.url}`);
  next();
});

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

// Decorator to add greeting to a function
function greetDecorator(fn) {
  return function(name) {
    const original = fn(name);
    return original + ' Have a nice day!';
  };
}

function greet(name) {
  return `Hello, ${name}!`;
}

const decoratedGreet = greetDecorator(greet);

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000');
  console.log(decoratedGreet('Alice'));
});
OutputSuccess
Important Notes
Middleware is mainly used in web frameworks to process requests step-by-step.
Decorators are more general and can wrap any function to add features.
Middleware uses a 'next' function to pass control; decorators return a new function.
Summary
Middleware runs in a chain to handle requests or responses.
Decorator wraps a function to add or change behavior.
Both help keep code clean by separating extra tasks from main logic.