MIddlewares in Express
What is Middleware?
Middleware in Express is like a security guard or helper that sits between the request (client) and the response (server). It can modify, check, or handle requests before they reach the final destination (route handler).In Express.js, middleware functions are used to handle requests and responses in a structured way. Here are five types of middleware in Express:
-
Application-Level Middleware
- Defined using
app.use()
orapp.METHOD()
. - Used for tasks like authentication, logging, and request modifications.
- Example:
app.use((req, res, next) => { console.log('Request received at:', Date.now()); next(); });
- Defined using
-
Router-Level Middleware
- Similar to application-level middleware but only applies to specific routers.
- Defined using
router.use()
. - Example:
const express = require('express'); const router = express.Router(); router.use((req, res, next) => { console.log('Router Middleware Executed'); next(); }); app.use('/api', router);
-
Built-in Middleware
-
Express provides some built-in middleware for common tasks.
-
Examples include:
express.json()
→ Parses incoming JSON requestsexpress.urlencoded({ extended: true })
→ Parses URL-encoded form dataexpress.static('public')
→ Serves static files
app.use(express.json()); app.use(express.static('public'));
-
-
Error-Handling Middleware
- Handles errors in the application.
- Defined with four parameters:
(err, req, res, next)
. - Example:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
-
Third-Party Middleware
-
Middleware provided by external libraries to add functionalities like authentication, logging, and security.
-
Examples:
morgan
→ Logging requestshelmet
→ Security headerscors
→ Enable CORS
const morgan = require('morgan'); app.use(morgan('dev'));
-
Each middleware plays a crucial role in request processing, security, and performance optimization in an Express application. 🚀
Comments
Post a Comment