Middleware Introduction in Express.js
Middleware is one of the most important concepts in Express.js. It allows us to execute code during the request-response cycle.
Whenever a client sends a request to an Express.js server, middleware functions can execute before the final response is sent back to the client.
Middleware can perform different tasks, such as logging requests, checking authentication, processing request data, and handling errors. It helps us organize application logic into reusable functions.
1. What Is Middleware?
Middleware is a function that executes during the request-response cycle of an Express.js application.
A middleware function generally receives three parameters:
- req: Contains information about the incoming request.
- res: Used to send a response to the client.
- next: A function that passes control to the next middleware.
function myMiddleware(req, res, next) {
console.log("Middleware executed");
next();
}
In this example, the middleware prints a message and calls
next() to continue processing the request.
next(), the request may remain pending.
2. Why Do We Need Middleware?
Middleware helps us perform common operations before a request reaches its final route handler.
| Purpose | Description |
|---|---|
| Logging | Records details about incoming requests. |
| Authentication | Checks whether a user is authenticated. |
| Request Parsing | Reads JSON or form data from requests. |
| Validation | Checks whether incoming data is valid. |
| Error Handling | Handles errors that occur in the application. |
| Static Files | Serves files such as CSS, JavaScript, and images. |
3. How Middleware Works
Express.js processes middleware according to the order in which it is registered. A middleware can pass control to the next function or finish the request by sending a response.
Client Request
Browser or API client sends a request
Middleware 1
Logs request information
Middleware 2
Checks or processes request data
Route Handler
Processes the requested URL
Server Response
Response is sent to the client
4. Creating Your First Middleware
Let us create a simple Express.js application that displays a message in the terminal whenever a request arrives.
Step 1: Install Express.js
npm init -y
npm install express
Step 2: Create a file named app.js
const express = require('express');
const app = express();
// Middleware function
app.use((req, res, next) => {
console.log('A request was received');
next();
});
// Route handler
app.get('/', (req, res) => {
res.send('Welcome to Express.js Middleware!');
});
// Start server
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Step 3: Run the application
node app.js
Step 4: Open the browser
http://localhost:3000
Browser Output:
Terminal Output:
Server running at http://localhost:3000
A request was received
Whenever you open the URL or refresh the page, the middleware
logs the request message and calls next().
The route handler then sends the response.
5. Understanding app.use()
The app.use() method registers middleware in an
Express.js application. Middleware registered without a path
generally runs for every incoming request that reaches it,
subject to its position in the middleware stack.
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
Here, req.method provides the HTTP method, such as
GET or POST, while req.url provides the requested URL.
Example terminal output:
GET /
GET /about
GET /products
These lines are examples of what may appear when the corresponding URLs are requested.
6. Types of Middleware in Express.js
Express.js middleware can be grouped according to its purpose and how it is registered.
| Type | Purpose |
|---|---|
| Built-in Middleware | Provided by Express.js, such as express.json() and express.static(). |
| Application-Level Middleware | Registered on the application using methods such as app.use(). |
| Router-Level Middleware | Registered on an Express Router using router.use(). |
| Third-Party Middleware | Installed from external packages, such as logging middleware. |
| Error-Handling Middleware | Handles errors using four parameters: err, req, res, next. |
Important Points to Remember
- Middleware executes during the request-response cycle.
- Middleware receives
req,res, andnextin the usual pattern. - Use
next()to pass control to the next middleware. - Middleware registration order matters.
- Middleware can modify request or response objects.
- A middleware can send a response instead of calling
next(). - Error-handling middleware uses four parameters.
Summary
Middleware is a function that runs while an Express.js application processes a request. It is commonly used for logging, authentication, request parsing, validation, and error handling.
The app.use() method registers application
middleware, while next() passes control to
the next middleware or handler.