bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Building Applications
Node.js•Building Applications

Node.js Middleware

Concept visual

Node.js Middleware

push / pop from the top({[← top

Introduction to Middleware

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.

Key Characteristics of Middleware:

Executes during the request-response cycle

Can modify request and response objects

Can end the request-response cycle

Can call the next middleware in the stack

Formula

Can be application - level, router - level, or route - specific

It 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 cycle

Middleware functions can perform a variety of tasks:

Execute any code

Modify request and response objects

End the request-response cycle

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.

How Middleware Works in the Request-Response Cycle

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:

Request received by the server

Passed through each middleware in sequence

Route handler processes the request

Response flows back through middleware (in reverse order)

Response sent to client

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!"

Comprehensive Guide to Middleware Types

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.

Choosing the Right Type:

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:

Application-level Middleware

Formula

Application - level middleware is bound to the Express application instance using app.use()

or app.METHOD() functions.

Use Cases:

Logging, authentication, request parsing, and other operations that should run for every request.

Best Practices:

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();
});

Router-level Middleware

Formula

Router - level middleware works similarly to application - level middleware but is bound to an instance of express.Router().

Use Cases:

Formula

Grouping route - specific middleware, API versioning, and organizing routes into logical groups.

Advantages:

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);

Error-handling Middleware

Error-handling middleware is defined with four arguments

(err, req, res, next) and is used to handle errors that occur during request processing.

Key Points:

Previous

Node.js Express.js

Next

Node.js RESTful API