0
0
Node.jsframework~5 mins

Middleware concept and execution flow in Node.js

Choose your learning style9 modes available
Introduction

Middleware helps your app handle requests step-by-step. It lets you add features like logging or checking users before doing the main work.

You want to log every request to see who visits your site.
You need to check if a user is logged in before showing a page.
You want to handle errors in one place instead of everywhere.
You want to add data to requests that later parts of your app can use.
Syntax
Node.js
app.use(function (req, res, next) {
  // your code here
  next();
});
Middleware functions get three things: request (req), response (res), and next function.
Call next() to move to the next middleware or route handler.
Examples
This middleware logs the URL of every request before moving on.
Node.js
app.use(function (req, res, next) {
  console.log('Request URL:', req.url);
  next();
});
This middleware checks if the user is logged in. If not, it stops and sends a message.
Node.js
app.use(function (req, res, next) {
  if (!req.user) {
    res.status(401).send('Please log in');
  } else {
    next();
  }
});
This is error-handling middleware. It catches errors and sends a message.
Node.js
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
Sample Program

This program uses two middleware functions. The first logs the request method and URL. The second adds a message to the request. The route then sends that message back to the browser.

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 property
app.use((req, res, next) => {
  req.customMessage = 'Hello from middleware!';
  next();
});

// Route handler
app.get('/', (req, res) => {
  res.send(req.customMessage);
});

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

Always call next() unless you send a response to avoid hanging requests.

Middleware runs in the order you add it with app.use().

Error-handling middleware has four arguments: (err, req, res, next).

Summary

Middleware lets you run code on requests before reaching routes.

Use next() to pass control to the next middleware.

Order matters: middleware runs in the order you add it.