Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn What Is Middleware | Middleware in Express.js
Express.js Essentials for Backend Development

What Is Middleware

Swipe to show menu

Middleware is a core concept in Express.js that refers to functions which have access to the request and response objects, as well as the next function in the application’s request-response cycle. Middleware functions can perform a range of tasks, such as executing code, modifying the request or response objects, ending the request-response cycle, or passing control to the next middleware function. The execution flow of middleware is sequential: when a request is received, Express.js passes it through each middleware function in the order they are defined until a response is sent or the request is passed to the next handler.

There are several types of middleware in Express.js:

  • Application-level middleware: attached to an instance of the express application and applies to all or specific routes;
  • Router-level middleware: attached to an instance of express.Router() and applies to routes handled by that router;
  • Error-handling middleware: functions with four arguments, used to handle errors that occur in the application.
function logRequest(req, res, next) {
  console.log(req.method, req.url);
  next();
}

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

app.use(logRequest);

app.get('/', (req, res) => {
  res.send('Home page');
});

In this example, the logRequest middleware function receives the request (req), response (res), and next function. It logs the request method and URL, then calls next() to continue to the next middleware or route handler. By using app.use(logRequest), you ensure this middleware runs for every incoming request, demonstrating the sequential and layered flow of middleware in Express.js.

question mark

Which statement best describes middleware in Express.js?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 3. Chapter 1
some-alt