Home >Web Front-end >JS Tutorial >Understanding Middlewares in Express.js and Their Internal Working
In Express.js, middlewares are special functions that have access to the request (req), response (res), and a third parameter called next. Unlike regular route handlers, middlewares play a critical role in controlling the flow of the application by executing external logic before the main business logic.
When an HTTP request hits an Express.js server, it flows through a series of middleware functions. Each middleware can:
If a middleware doesn't call next(), the request-response cycle terminates there, and no further logic (including route handlers) will execute.
Middlewares are perfect for scenarios where we need to add reusable logic before processing a request. For instance:
A middleware function looks like this:
app.use((req, res, next) => { // Logic here next(); // Pass control to the next middleware or route handler });
Middleware order matters! Express executes middlewares sequentially in the order they are defined.
If a middleware is defined after a route, it will not affect that route. This is why middlewares must be declared before routes in your app.js.
Example:
// Middleware to check if the user has admin privileges app.use((req, res, next) => { console.log("Checking for admin role..."); // Simulating a user object attached earlier in the pipeline if (req.user && req.user.role === "admin") { console.log("Access granted"); next(); // Move to the next middleware or route handler } else { console.log("Access denied"); res.status(403).send("You do not have access to this resource."); } }); // Routes app.get("/admin/dashboard", (req, res) => { res.send("Welcome to the admin dashboard!"); }); app.get("/public", (req, res) => { res.send("This is a public page."); });
Here’s what happens step by step:
The above is the detailed content of Understanding Middlewares in Express.js and Their Internal Working. For more information, please follow other related articles on the PHP Chinese website!