Loading lesson path
Concept visual
Middleware is a key part of Node.js web applications, particularly in Express.js. It provides a way to add and reuse common functionality across your application's routes and endpoints.
Can call the next middleware in the stack
Formula
Can be application - level, router - level, or route - specificIt acts as a bridge between the raw request and the final intended route handler. At its core, middleware is a function that has access to: The request object (req) The response object (res)
Formula
The next middleware function in the application's request - response cycleMiddleware functions can perform a variety of tasks:
Call the next middleware function in the stack Think of middleware as a series of processing layers that requests pass through before receiving a response-like an assembly line for HTTP requests.
Middleware functions are executed in the order they are defined, creating a pipeline through which requests flow. Each middleware function can perform operations on the request and response objects and decide whether to pass control to the next middleware or end the request-response cycle. Lifecycle of a Request Through Middleware:
Response flows back through middleware (in reverse order)
The basic pattern of middleware in Express.js follows this structure:
app.use((req, res, next) => {
// Middleware code goes here console.log('Time:', Date.now());
// Call next() to pass control to the next middleware function next();
});
When you call next(), the next middleware in the stack is executed.Formula
If you don't call next(), the request - response cycle ends and no further middleware runs.Example: A Simple Middleware Chain const express = require('express');
const app = express();
// First middleware app.use((req, res, next) => {
console.log('Middleware 1: This always runs');
next();
});
// Second middleware app.use((req, res, next) => {
console.log('Middleware 2: This also always runs');
next();
});
// Route handler app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(8080, () => {
console.log('Server running on port 8080');
});
When a request is made to the root path ('/'), the following happens:
Middleware 1 logs a message and calls next()
Middleware 2 logs a message and calls next()
The route handler responds with "Hello World!"Understanding the different types of middleware helps in organizing your application's logic effectively. Middleware can be categorized based on its scope, purpose, and how it's mounted in the application.
The type of middleware you use depends on your specific needs, such as whether the middleware should run for all requests or specific routes, and whether it needs access to the router instance. In Node.js applications, especially with Express.js, there are several types of middleware:
Formula
Application - level middleware is bound to the Express application instance using app.use()or app.METHOD() functions.
Logging, authentication, request parsing, and other operations that should run for every request.
Formula
Define application - level middleware before defining routes to ensure they run in the correct order.Bound to the application instance using app.use() or app.METHOD()
const express = require('express');
const app = express();
// Application-level middleware app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});Formula
Router - level middleware works similarly to application - level middleware but is bound to an instance of express.Router().Formula
Grouping route - specific middleware, API versioning, and organizing routes into logical groups.Better code organization, modular routing, and the ability to apply middleware to specific route groups. Bound to an instance of express.Router()
const express = require('express');
const router = express.Router();
// Router-level middleware router.use((req, res, next) => {
console.log('Router specific middleware');
next();
});
router.get('/user/:id', (req, res) => {
res.send('User profile');
});
// Add the router to the app app.use('/api', router);(err, req, res, next) and is used to handle errors that occur during request processing.