1. Middleware in Express.js
Middleware is a core concept in Express.js that plays a vital role in handling requests, responses, and executing code in the middle of the request-response cycle. Middleware functions can perform tasks like logging, authentication, error handling, and modifying request/response objects.
2. What is Middleware?
Middleware functions are functions that have access to the request (req), response (res), and the next middleware in the application’s request-response cycle. Middleware can:
3. Middleware Syntax
A middleware function typically follows this structure:
app.use((req, res, next) => {
// Middleware logic
console.log('Middleware executed');
next(); // Passes control to the next middleware
});
4. Types of Middleware in Express.js
1. Application-Level Middleware
2. Router-Level Middleware
3. Built-in Middleware
4. Error-Handling Middleware
5.Third-Party Middleware
5. Application-Level Middleware
This middleware applies to the entire application and can be added using app.use() or app.METHOD().
Example:
const express = require('express');
const app = express();
// Application-level middleware
app.use((req, res, next) => {
console.log(`Request URL: ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Home Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
6. Router-Level Middleware
Router-level middleware works on specific routes and can be attached to an express.Router() instance.
Example:
const express = require('express');
const app = express();
const router = express.Router();
// Router-level middleware
router.use((req, res, next) => {
console.log('Router middleware executed');
next();
});
router.get('/users', (req, res) => {
res.send('Users List');
});
app.use('/api', router);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
7. Built-in Middleware
Express provides built-in middleware for common tasks like parsing JSON, handling static files, and URL-encoded data.
Example:
app.use(express.json()); // Parses JSON data
app.use(express.urlencoded({ extended: true })); // Parses URL-encoded data
8. Error-Handling Middleware
Error-handling middleware is defined with four arguments: (err, req, res, next). It captures errors and provides custom error-handling logic.
Example:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
9. Third-Party Middleware
Express supports third-party middleware packages available through npm. Popular third-party middleware includes:
Example:
const morgan = require('morgan');
app.use(morgan('dev')); // Logs requests in the 'dev' format