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:

Example05
Loading editor…

πŸ“ Example 2: Router-Level Middleware

This middleware runs only for specific routes:

Example06
Loading editor…

πŸš€ 1️⃣ Application-Level Middleware

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

Example07
Loading editor…

πŸ“ 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