Middleware:

Middleware functions in Express.js are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle. They can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack. Express

Types of Middleware

  1. Application-level Middleware

    const express = require('express');
    const app = express();
    
    app.use((req, res, next) => {
      console.log('Time:', Date.now());
      next();
    });
    
  2. Router-level Middleware

    const express = require('express');
    const router = express.Router();
    
    router.use((req, res, next) => {
      console.log('Request URL:', req.originalUrl);
      next();
    });
    
  3. Error-handling Middleware

    app.use((err, req, res, next) => {
      console.error(err.stack);
      res.status(500).send('Something broke!');
    });
    
  4. Built-in Middleware

  5. Third-party Middleware

    const express = require('express');
    const app = express();
    const cookieParser = require('cookie-parser');
    
    app.use(cookieParser());
    

Writing Custom Middleware

A custom middleware function is a function that takes three arguments: req, res, and next.

const myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
};

app.use(myLogger);

This middleware logs "LOGGED" to the console every time a request is received. It's important to call next() to pass control to the next middleware function. Express+2Express+2Express+2

Middleware Execution Flow

Middleware Chaining