0
0
Node.jsframework~5 mins

Why middleware is fundamental in Node.js

Choose your learning style9 modes available
Introduction

Middleware helps organize code that runs between receiving a request and sending a response. It makes your app easier to build and maintain.

You want to check if a user is logged in before showing a page.
You need to log every request made to your server.
You want to handle errors in one place instead of everywhere.
You want to add headers or modify requests and responses.
You want to serve static files like images or stylesheets.
Syntax
Node.js
function middlewareFunction(req, res, next) {
  // Do something with req or res
  next(); // Pass control to the next middleware
}
Middleware functions take three arguments: request, response, and next.
Calling next() moves to the next middleware or route handler.
Examples
This middleware logs the URL of every request.
Node.js
app.use(function(req, res, next) {
  console.log('Request URL:', req.url);
  next();
});
This middleware checks if a user is logged in before continuing.
Node.js
app.use(function(req, res, next) {
  if (!req.user) {
    res.status(401).send('Not logged in');
  } else {
    next();
  }
});
Sample Program

This example shows two middleware functions: one logs requests, the other adds a header. Then a route sends a welcome message.

Node.js
import express from 'express';

const app = express();

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

// Middleware to add a custom header
app.use((req, res, next) => {
  res.setHeader('X-Custom-Header', 'HelloMiddleware');
  next();
});

// Route handler
app.get('/', (req, res) => {
  res.send('Welcome to middleware demo!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always call next() unless you end the response to avoid hanging requests.

Middleware runs in the order you add it, so order matters.

Summary

Middleware runs code between request and response.

It helps keep your app organized and reusable.

Use middleware for logging, authentication, error handling, and more.