Node.js Middleware
π Node.js Middleware (Express.js Middleware Explained)
Middleware is one of the core features of Express.js.
It allows you to run functions between the request and the response.
β What is Middleware?
Middleware functions are functions that have access to:
-
req β Request object
-
res β Response object
-
next β Function to pass control to next middleware
π Syntax
π§± Types of Middleware in Express.js
Express supports many types:
-
Application-Level Middleware
-
Router-Level Middleware
-
Built-In Middleware
-
Third-Party Middleware
-
Error-Handling Middleware
Letβs learn each one.
β 1. Application-Level Middleware
Runs for every request or specific routes.
Example: log every request
Apply to a specific route:
β 2. Router-Level Middleware
Works exactly like application middleware but applied on a Router.
β 3. Built-in Middleware
Express provides some built-in middleware:
β Parse JSON
β Parse URL-encoded form data
β Serve Static Files
β 4. Third-Party Middleware
These are installed from npm.
πΉ Example: morgan (HTTP request logger)
πΉ Example: cors (Enable CORS)
πΉ Example: helmet (Security Headers)
β 5. Error-Handling Middleware
Error middleware has 4 arguments:
Example:
Once thrown β automatically sent to error middleware.
𧬠Middleware Order Matters
Middleware is executed in the order it is defined.
Order =
1οΈβ£ middleware1
2οΈβ£ middleware2
3οΈβ£ route
π Multiple Middleware in One Route
π Example: Authentication Middleware
π Organizing Middleware in a Folder
Create /middleware/auth.js:
Use it:
π When to Use Middleware?
Use middleware for:
β Authentication
β Logging
β Validation
β Parsing request body
β Error handling
β Security
β Rate limiting
β Serving static files
π― Final Summary
Middleware is essential in Express.js because it:
-
Controls request flow
-
Adds functionality (logging, auth, security)
-
Keeps code modular
-
Helps structure large applications
