Express Request-Response Cycle and Middleware with Code Examples
If you’re delving into Express development, it’s essential to understand the request-response cycle and the power of middleware. In this article, we’ll demystify these concepts with practical code examples, making it easier for you to grasp the core of Express development.
Setting up an Express Application
Before we dive into the details, let’s set up a basic Express application to work with throughout our examples. Make sure you have Node.js and Express installed.
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); // Middleware for parsing JSON in the request body
// Define a route handler
app.get('/example', (req, res) => {
res.send('Hello from the route handler!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
In this code:
- We create an Express app.
- Set up a basic route handler for the
/example
route that responds with a message. - Use
express.json()
middleware to parse JSON data in the request body.
The Express Request-Response Cycle
Incoming Request
The request-response cycle begins when a user sends a GET request to your server’s /example
route:
// User sends a GET request to /example
Middleware Processing
Middleware is the heart of Express. In our example, express.json()
middleware comes into play first, parsing JSON data from the request body:
app.use(express.json()); // Middleware parses JSON data
// Middleware execution order:
// 1. express.json()
// 2. Route handler for /example
Route Handler as Middleware
The request then reaches the route handler, which is also a form of middleware. It responds with a simple message:
// Route handler (middleware)
app.get('/example', (req, res) => {
res.send('Hello from the route handler!');
});
Completing the Cycle
The response is sent back to the client, concluding the request-response cycle:
// Sending the response
res.send('Hello from the route handler!');
Middleware Stack and Execution Order
To illustrate the concept of the middleware stack and execution order, let’s add a custom middleware function:
// Middleware function
function customMiddleware(req, res, next) {
console.log('Custom middleware executed');
next(); // Move to the next middleware
}
app.use(customMiddleware); // Add custom middleware
app.get('/example', (req, res) => {
res.send('Hello from the route handler!');
});
Here, we’ve introduced customMiddleware
, which logs a message and calls next()
to pass control to the next middleware in the stack.
Middleware Execution Order
With the addition of custom middleware, the middleware execution order becomes:
express.json()
(Parse JSON data)customMiddleware
(Custom middleware)- Route handler for
/example
The order in which middleware is defined (express.json()
before customMiddleware
) determines the execution sequence.
Conclusion
Understanding the Express request-response cycle and the role of middleware is fundamental to mastering Express development. In this article, we’ve demystified these concepts with practical code examples. Middleware functions can process data, modify request or response objects, and control the flow of requests through the stack. Remember that the order of middleware definition is crucial. With these insights, you’re well on your way to becoming an Express expert. Happy coding!