What is Middleware in Express.js


In Node.js with Express.js, middleware is a key component that helps manage the request-response cycle of web applications. Here’s a deeper look into how middleware works in this environment:

What is Middleware in Express.js?

Middleware in Express.js is a function or series of functions that have access to the request object (req), the response object (res), and a next function that passes control to the next middleware in the stack. Middleware can modify the request or response, end the request-response cycle, or call the next function to pass control to the next middleware.

How Middleware Works

  1. Request Processing: Middleware functions can inspect, modify, or terminate requests before they reach the route handler.
  2. Response Processing: Middleware functions can modify or handle responses before they are sent to the client.
  3. Error Handling: Middleware can handle errors that occur during request processing, ensuring that proper responses are sent back.

Basic Structure

Here’s a basic example of how middleware is used in an Express.js application:

const express = require('express'); const app = express(); // Middleware function const myMiddleware = (req, res, next) => { console.log('Middleware executed'); next(); // Pass control to the next middleware }; // Use middleware globally app.use(myMiddleware); // Route handler app.get('/', (req, res) => { res.send('Hello, world!'); }); // Start server app.listen(3000, () => { console.log('Server running on port 3000'); });

Types of Middleware

  1. Application-Level Middleware: Defined using app.use() or app.METHOD(), where METHOD is the HTTP method (e.g., app.get()).

    app.use(express.json()); // Built-in middleware for parsing JSON bodies
  2. Router-Level Middleware: Applied to specific routers using router.use().

    const router = express.Router(); router.use((req, res, next) => { console.log('Router-level middleware'); next(); }); router.get('/test', (req, res) => { res.send('Test route'); }); app.use('/api', router); // Use the router with middleware
  3. Built-in Middleware: Express.js provides some built-in middleware functions like express.json() for JSON parsing and express.static() for serving static files.

    app.use(express.static('public')); // Serve static files from the 'public' directory
  4. Third-Party Middleware: Middleware provided by third-party packages, such as morgan for logging and body-parser for parsing request bodies.

    const morgan = require('morgan'); app.use(morgan('tiny')); // Log requests using 'tiny' format
  5. Error-Handling Middleware: Special middleware to handle errors. It takes four arguments: err, req, res, and next.

    app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });

Middleware Order

The order in which middleware functions are added is important. Express executes middleware in the order they are defined. For example:

app.use((req, res, next) => { console.log('First middleware'); next(); }); app.use((req, res, next) => { console.log('Second middleware'); next(); }); app.get('/', (req, res) => { res.send('Hello, world!'); });

In this example, the "First middleware" message will be logged before the "Second middleware" message because of their order.

Key Points

  • Chaining: Middleware functions can call next() to pass control to the next function in the stack.
  • Reusable: Middleware functions can be reused across different routes or even across different applications.
  • Modularity: Middleware allows you to modularize your code, making it easier to manage and maintain.

Middleware in Express.js provides a flexible way to handle various aspects of HTTP requests and responses, making it a powerful feature in web development.