Middleware in Express Js

  • Middleware in Express.js refers to functions that have access to the request, response, and the next middleware function in the application's request-response cycle. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function in the stack.
  • Middleware functions play a crucial role in Express.js applications, allowing developers to perform various tasks, such as logging, authentication, error handling, and more.
Basic Middleware Example:


    const express = require('express');
    const app = express();

    // Middleware function
    const myMiddleware = (req, res, next) => {
        console.log('Middleware executed!');
        next(); // Call the next middleware in the stack
    };

    // Use the middleware for all routes
    app.use(myMiddleware);

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

    const PORT = 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

  • In this example, `myMiddleware` is a basic middleware function that logs a message. It is used for all routes using `app.use(myMiddleware)`.
Types of Middleware in Express.js:
  • Application-level Middleware: Middleware that is bound to the application instance. It executes for every incoming request.

    app.use(express.json()); // Parses incoming JSON requests
    app.use(express.urlencoded({ extended: true })); // Parses incoming URL-encoded requests
    app.use(myMiddleware); // Custom middleware

  • Router-level Middleware: Middleware that is bound to a specific router. It is similar to application-level middleware but is applied to a specific router instance.

    const router = express.Router();

    router.use(myMiddleware);
    router.get('/', (req, res) => {
        res.send('Router-level Middleware Example');
    });

    app.use('/example', router); // Mount the router at a specific path

  • Error Handling Middleware: Middleware that takes four arguments (err, req, res, next) and is used to handle errors.

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

  • Built-in Middleware: Express.js includes some built-in middleware functions for common tasks, such as serving static files.

    app.use(express.static('public')); // Serve static files from the 'public' directory

  • Third-party Middleware: Middleware provided by third-party packages. Examples include body parsers, authentication middleware, etc.

    npm install helmet



    const helmet = require('helmet');
    app.use(helmet()); // Third-party security middleware

  • Custom Middleware: Developers can create custom middleware functions to perform specific tasks. These functions take three parameters: req, res, and next.

    const myMiddleware = (req, res, next) => {
        console.log('Custom Middleware');
        next();
    };

    app.use(myMiddleware);

  • Error Handling Middleware: Middleware that is specifically designed to handle errors in the application.

    app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).send('Internal Server Error');
    });

  • Middleware Execution Order: The order in which middleware is defined matters. Middleware is executed in the order it is added using `app.use()` or `router.use()`.

    app.use(middleware1);
    app.use(middleware2);
    app.use(middleware3);

  • In the above example, `middleware1` will be executed first, followed by `middleware2`, and then `middleware3`.
Summary:
  • Middleware functions are crucial in Express.js for handling various tasks during the request-response cycle.
  • Application-level middleware is bound to the application instance, while router-level middleware is bound to a specific router.
  • Error handling middleware is used to catch and handle errors in the application.
  • Express.js provides built-in middleware and allows developers to use third-party and custom middleware.
  • The order in which middleware is defined determines the order of execution during the request-response cycle.

No comments:

Post a Comment