Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Express Middleware
Middleware functions are functions that have access to the Request object, theResponse object, and the next function in the application’s request-response cycle.
The "next()" function: If the current middleware function does not end the request-response cycle, it must call
next() to pass control to the next middleware function. Otherwise, the request will be left hanging.1. Types of Middleware
- Application-level: Bound to the app object using
app.use(). - Router-level: Bound to an instance of
express.Router(). - Built-in: Provided by Express (e.g.,
express.json()). - Third-party: Installed via NPM (e.g.,
morgan,cors).
2. Custom Middleware Example
Let's create a simple logger middleware that prints the time of every request.
const logger = (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Don't forget this!
};
app.use(logger); // Applies to ALL routes3. Built-in Middleware
Most Express apps need some built-in middleware to handle incoming data.
// Parse JSON payloads
app.use(express.json());
// Parse URL-encoded bodies (form data)
app.use(express.urlencoded({ extended: false }));
// Serve static files (images, css, js)
app.use(express.static('public'));4. Middleware Order Matters
Middleware functions are executed in the order they are defined. If you define a logger after a route, it won't run for that route!