Middlewares Deep Dive
Middleware functions in [Link] are a core concept that allows you to execute code, make changes to
the request and response objects, end the request-response cycle, or call the next middleware in the
stack.
1. What is Middleware?
Middleware is a function that has access to the request (req), response (res), and the next middleware
function in the application’s request-response cycle.
Middleware Signature
function middlewareFunction(req, res, next) {
// Your middleware logic
next(); // Call the next middleware in the chain
2. Types of Middleware
1. Application-Level Middleware
o Attached to the app instance.
o Handles specific routes or all requests.
2. Router-Level Middleware
o Attached to specific [Link]() instances.
3. Built-In Middleware
o Predefined middleware functions provided by Express, e.g., [Link]() and
[Link]().
4. Third-Party Middleware
o External middleware installed via npm, e.g., morgan, cors.
5. Error-Handling Middleware
o Handles errors in the application.
3. Writing Middleware
Basic Example
const express = require('express');
const app = express();
// Custom Middleware
[Link]((req, res, next) => {
[Link](`${[Link]} request for ${[Link]}`);
next(); // Pass control to the next middleware
});
// Route Handler
[Link]('/', (req, res) => {
[Link]('Hello, Middleware!');
});
[Link](3000, () => [Link]('Server running on [Link]
Attaching to Specific Routes
const logMiddleware = (req, res, next) => {
[Link]('Log middleware called');
next();
};
[Link]('/dashboard', logMiddleware, (req, res) => {
[Link]('Dashboard Page');
});
4. Built-In Middleware
[Link]()
Parses incoming JSON requests.
[Link]([Link]());
[Link]('/api/data', (req, res) => {
[Link](`Received: ${[Link]([Link])}`);
});
[Link]()
Parses application/x-www-form-urlencoded data.
[Link]([Link]({ extended: true }));
5. Third-Party Middleware
CORS (Cross-Origin Resource Sharing)
Allows sharing resources across different origins.
npm install cors
const cors = require('cors');
[Link](cors());
Morgan (Logging HTTP Requests)
npm install morgan
const morgan = require('morgan');
[Link](morgan('tiny'));
6. Error-Handling Middleware
Error-handling middleware has four parameters: err, req, res, next.
Example
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send('Something went wrong!');
});
Usage
[Link]('/error', (req, res, next) => {
next(new Error('This is a forced error'));
});
7. Advanced Middleware Usage
Middleware for Authentication
const authMiddleware = (req, res, next) => {
const { token } = [Link];
if (token === 'secret-token') {
next();
} else {
[Link](403).send('Forbidden');
};
[Link]('/protected', authMiddleware, (req, res) => {
[Link]('You are authorized');
});
Chaining Middleware
const middleware1 = (req, res, next) => {
[Link]('Middleware 1');
next();
};
const middleware2 = (req, res, next) => {
[Link]('Middleware 2');
[Link]('End of middleware chain');
};
[Link]('/chain', middleware1, middleware2);
Dynamic Middleware Logic
[Link]((req, res, next) => {
if ([Link] === '/block') {
[Link](403).send('Blocked');
} else {
next();
});
8. Router-Level Middleware
Router-level middleware works the same as application-level middleware but is bound to an
[Link] instance.
Example
const router = [Link]();
[Link]((req, res, next) => {
[Link](`Request to ${[Link]}`);
next();
});
[Link]('/route1', (req, res) => [Link]('Route 1'));
[Link]('/route2', (req, res) => [Link]('Route 2'));
[Link]('/api', router);
9. Middleware Debugging
Use libraries like debug for enhanced debugging of middleware.
Setup
npm install debug
const debug = require('debug')('app:middleware');
[Link]((req, res, next) => {
debug(`Request URL: ${[Link]}`);
next();
});
10. Best Practices for Middleware
1. Order Matters: Middleware is executed in the order it’s defined.
2. Avoid Blocking: Always call next() unless you want to terminate the request-response cycle.
3. Keep Middleware Reusable: Write generic and reusable functions.
4. Error Handling: Always provide an error-handling middleware for unexpected issues.
Example Application: Middleware for Logging and Error Handling
const express = require('express');
const app = express();
// Logging Middleware
[Link]((req, res, next) => {
[Link](`[${new Date().toISOString()}] ${[Link]} ${[Link]}`);
next();
});
// Route
[Link]('/', (req, res) => {
[Link]('Middleware Deep Dive');
});
// Error-Handling Middleware
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send('Internal Server Error');
});
// Start Server
[Link](3000, () => [Link]('Server running on [Link]
Middleware is essential for creating robust and maintainable [Link] applications. It can handle a wide
range of functionalities like authentication, logging, error handling, and much more.