ExpressJS Middleware Explained
Imagine you are at an airport. Before boarding your flight, you go through multiple checkpoints: security check, passport verification, baggage screening. Each checkpoint examines something about you or your luggage before allowing you to proceed. In Express.js, these checkpoints are called middleware.
What is Middleware?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. They can:
- Execute any code
- Make changes to the request and response objects
- End the request-response cycle
- Call the next middleware function in the stack
Simple Analogy
Think of middleware like a series of filters or checkpoints that every request must pass through before reaching its final destination (your route handler). Each checkpoint can:
- Inspect the request (like checking passport)
- Modify the request (like adding a stamp)
- Stop the request if something is wrong (like denying entry)
- Pass it to the next checkpoint (next())
Basic Middleware Example
const express = require('express');
const app = express();
// This is a simple middleware function
app.use((req, res, next) => {
console.log('Time:', Date.now());
next(); // Pass control to the next middleware or route
});
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000);The 'next' Function
The
next() function is crucial in middleware. If a middleware function does not call next() or send a response, the request will hang forever. Always remember to call next() when you want the request to continue to the next middleware or route handler.Types of Middleware
Express has five types of middleware:
- Application-level middleware – Bound to the app object using
app.use()orapp.METHOD() - Router-level middleware – Works like application middleware but bound to an instance of
express.Router() - Error-handling middleware – Takes four arguments (err, req, res, next)
- Built-in middleware – Provided by Express (like express.json, express.static)
- Third-party middleware – Installed via npm (like cors, morgan)
Two Minute Drill
- Middleware functions sit between the request and the final route handler.
- They can modify req/res, execute code, or end the request cycle.
- Always call
next()to pass control to the next middleware. - There are five types: application, router, error-handling, built-in, and third-party.
Need more clarification?
Drop us an email at career@quipoinfotech.com
