Nearby lessons

12 of 14

⚙️ Middleware in Express JS | Application-Level & Router-Level Middleware Explained

📌 What is Middleware?

💡 What Is Middleware in Express?

Express.js is a powerful and flexible Node.js framework used to build web apps and APIs.

One of its most important features is middleware, which allows you to intercept requests, modify them, run logic, and control the application's request-response cycle.

🧠 Definition

🧠 Definition

Middleware functions have access to:

  • req - Request Object
  • res - Response Object
  • next - Function to pass control to the next middleware

If the current middleware does not end the cycle, it must call next().

📌 Tasks Performed by Middleware

  • ✔ Execute any code
  • ✔ Modify req or res objects
  • ✔ End the request-response cycle
  • ✔ Call the next middleware in the stack

If next() is not called or response not sent, the request will hang.

� Types of Middleware

🔧 Types of Middleware

  • Application-Level Middleware - Applied to all routes
  • Router-Level Middleware - Applied to specific routes
  • Built-in Middleware - Express.js built-in middleware
  • Third-Party Middleware - External middleware packages

📝 Example 1: Application-Level Middleware

This middleware logs request details for all routes:

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

// Application-level middleware - runs for all requests
app.use((req, res, next) => {
  console.log(`Request received: ${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});
Browser Output
Server logs

📝 Example 2: Router-Level Middleware

This middleware runs only for specific routes:

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();
const router = express.Router();

// Router-level middleware - runs only for router routes
router.use((req, res, next) => {
  console.log('Router middleware executed');
  next();
});

app.use('/test', router);

router.get('/', (req, res) => {
  res.send('Router Home Page');
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

🚀 1️⃣ Application-Level Middleware

This middleware is attached using app.use(). It runs for every request unless restricted.

Express.js Server
NODE RUNTIME
// Application-Level Middleware Example

const express = require('express');
const app = express();

// 🌟 Middleware 1 - Logs a simple message
app.use((req, res, next) => {
    console.log('📌 Middleware 1 executed');
    next();
});

// 🌟 Middleware 2 - Logs method & URL
app.use((req, res, next) => {
    console.log(`📋 ${req.method} ${req.url}`);
    next();
});

// 🌟 Middleware 3 - Logs date & time
app.use((req, res, next) => {
    const d = new Date();
    console.log(`Date: ${d.toLocaleString()}`);
    next();
});

// 🌟 Custom middleware function
const myMiddleware = (req, res, next) => {
    console.log("⏳ Custom Middleware Executed");
    next();
};

// Register custom middleware globally
app.use(myMiddleware);

// 🌟 Second middleware used only on routes
const secondMiddleware = (req, res, next) => {
    console.log('✅ Second Middleware executed');
    next();
};

// 🚀 Home Route
app.get('/', secondMiddleware, (req, res) => {
    res.send('🏠 Welcome to the Home Page');
});

// 🚀 About Route
app.get('/about', secondMiddleware, (req, res) => {
    res.send('📘 This is the About Page');
});

// Start Server
app.listen(8080, () => {
    console.log('🚀 Server is running at http://localhost:8080');
});

Browser Output
Server logs

📝 Application-Level Middleware Explained

  • app.use() registers middleware globally.
  • secondMiddleware is used only on specific routes.
  • Middleware runs in the order they are defined.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Router Middleware