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 Objectres- Response Objectnext- 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.secondMiddlewareis used only on specific routes.- Middleware runs in the order they are defined.
π§ Test Your Knowledge
5 QuestionsProgress: 0 / 5