Express Middleware Type
Built-in Middleware: Included with Express, performs common tasks, such as parsing request bodies, handling cookies, and serving static files.
Third-Party Middleware: External modules providing additional functionality, integrated into Express applications using
app.use()
. Examples includebody-parser
for parsing request bodies andmorgan
for logging.Router Middleware: Allows modular route handling by creating separate routers using
express.Router()
. These routers can be mounted at specific paths, enhancing code organization.Error-Handling Middleware: Specialized middleware for handling errors in Express applications. Utilized through a function with four parameters (err, req, res, next).
Custom Middleware: Application-specific middleware created using functions. Added to the request-response cycle using
app.use()
. Enables developers to inject custom logic at different points in the request processing pipeline.Application-Level Middleware: Bound to the
app
object and applied to every route in the application. Defined usingapp.use()
.Route-Level Middleware: Specific to particular routes, added using
app.use()
before defining the route. Useful for route-specific tasks.Error-Handling Middleware (app.use): Catches errors that occur in the application, irrespective of the route. Defined at the end of the middleware stack after all other route and middleware definitions.
Built-in Express Middleware Examples:
express.json()
: Parses incoming JSON requests.express.urlencoded()
: Parses incoming requests with URL-encoded payloads.express.static()
: Serves static files.