JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is middleware in Express.js?

Asked on Oct 02, 2024

Answer

Middleware in Express.js is a function that has access to the request and response objects and can modify them, end the request-response cycle, or call the next middleware function in the stack.
<!-- BEGIN COPY / PASTE -->
        const express = require('express');
        const app = express();

        // Simple middleware function
        function logger(req, res, next) {
            console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
            next(); // Pass control to the next middleware
        }

        // Use the middleware
        app.use(logger);

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

        app.listen(3000, () => {
            console.log('Server is running on port 3000');
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  • Middleware functions can perform a variety of tasks like logging, authentication, and error handling.
  • The "next" function is crucial as it passes control to the next middleware function.
  • Middleware can be applied globally with "app.use()" or to specific routes.
  • The order of middleware is important as it affects the flow of request handling.
✅ Answered with JavaScript best practices.
← Back to All Questions