What is middleware in Express
· Category: Node.js
Short answer
Middleware functions are functions that have access to the request object, response object, and the next middleware function in Express. They can execute code, modify requests and responses, end the cycle, or call the next middleware.
How it works
When a request hits your Express server, it flows through a pipeline of middleware functions in the order they are defined. Each middleware can either terminate the cycle by sending a response or pass control to the next function using next(). Built-in middleware includes express.json() and express.static().
Example
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => res.send('Hello'));
Why it matters
Middleware is the foundation of Express applications. It enables cross-cutting concerns like authentication, logging, error handling, and body parsing to be separated from route handlers, keeping your code modular and maintainable.