Skip to content

Middleware

Middleware in Express.js refers to functions that have access to the request (req) and response (res) objects, and the next middleware function in the application’s request-response cycle. Middleware can execute code, modify the request and response objects, end the request-response cycle, or call the next middleware function. Middleware functions are used to perform various tasks such as logging, authentication, parsing request bodies, and more. They are executed in the order they are defined.

Adding Custom Middleware

You can create custom middleware functions to process requests before they reach the route handlers.

Example: Logging Middleware

const express = require("express");
const app = express();
// Custom logging middleware
const logger = (req, res, next) => {
console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
next(); // Pass control to the next middleware
};
app.use(logger);
app.get("/", (req, res) => {
res.send("Hello, world!");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
  • The custom middleware logs the HTTP method and URL of each incoming request.
  • The next() function passes control to the next middleware or route handler.

Using Built-in Middleware Functions

Express provides several built-in middleware functions to handle common tasks like parsing request bodies.

app.use(express.json()); // Parse JSON request bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded request bodies
  • express.json(): Parses incoming requests with JSON payloads.
  • express.urlencoded(): Parses incoming requests with URL-encoded payloads, typically used for form submissions.