Node.js Q & A

 

What is middleware in Express.js?

Middleware in Express.js refers to a series of functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform tasks such as logging, authentication, data parsing, error handling, and more.

 

Middleware functions in Express.js are executed sequentially in the order they are defined in the application’s middleware stack. Each middleware function can either terminate the request-response cycle by sending a response to the client or pass control to the next middleware function using the next() function.

 

Middleware functions can be used globally for all routes or specific to individual routes or route handlers. They provide a modular and reusable way to add functionality to Express.js applications without modifying the core application logic.

 

Here’s an example of using middleware in Express.js:

javascript
Copy code
const express = require('express');
const app = express();

// Middleware function to log requests
app.use((req, res, next) => {
 console.log(`${req.method} ${req.url}`);
 next(); // Pass control to the next middleware function
});

// Route handler
app.get('/', (req, res) => {
 res.send('Hello, World!');
});

// Start the Express.js server
app.listen(3000, () => {
 console.log('Server is running on port 3000');
});

In this example, the middleware function logs each incoming request before passing control to the route handler. Middleware functions can be used to perform various tasks such as authentication, request validation, error handling, and more, making Express.js highly flexible and extensible.

Previously at
Flag Argentina
Argentina
time icon
GMT-3
Experienced Principal Engineer and Fullstack Developer with a strong focus on Node.js. Over 5 years of Node.js development experience.