Middleware Architecture & Custom Hooks

🦁 Express.jsLesson 5Intermediate

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

1 Custom Request Logging Logger

Middleware functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware in the stack:

JavaScript — custom_middleware.js
const express = require("express");
const app = express();

// Custom logging middleware
const requestLogger = (req, res, next) => {
  const method = req.method;
  const url = req.url;
  const time = new Date().toISOString();
  console.log(`[${time}] ${method} request sent to ${url}`);
  
  next(); // Crucial! Calls the next middleware or route handler
};

// Apply middleware globally to all incoming routes
app.use(requestLogger);
2 Middleware Categories
  • Application-level: Bound to an instance of the app object using app.use() or app.METHOD().
  • Router-level: Bound to an instance of express.Router().
  • Built-in: Native express middleware like express.json() and express.static().
  • Third-party: Community modules like cookie-parser, cors, and morgan.
3 Code Challenge
Challenge: Write a custom route-specific authentication middleware requireApiKey that verifies if the header x-api-key equals "secret123". If it does not match, return a 401 Unauthorized JSON error code.