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:

  • Execute any code.
  • Modify the request and response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack using the next() function.

  • 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:

  • morgan (HTTP request logging)
  • cors (Cross-Origin Resource Sharing)
  • helmet (Security best practices)
  • Example:

    				
    					const morgan = require('morgan');  
    app.use(morgan('dev')); // Logs requests in the 'dev' format
    
    				
    			


    10. Conclusion

    Middleware in Express.js is essential for building robust web applications by streamlining request handling, enabling logging, authentication, data parsing, and error handling. Understanding and utilizing middleware effectively allows developers to create modular, maintainable, and scalable applications in Node.js using Express.

    ×