Routing & MiddlewareBeginner
1Question 1 of 1
javascriptHow does the Middleware Pattern work in Express.js?
Explanation & Concept
In Express.js, middleware functions have access to the request (`req`), response (`res`), and the `next` function in the application's request-response cycle.
Middleware can execute code, modify request/response objects, end the request cycle, or invoke `next()` to pass control to the next handler.
Code Example
javascript
import express from "express";
const app = express();
// Custom authentication & logging middleware
const authLogger = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: "Missing Authorization Header" });
}
req.userId = "auth_user_99";
next(); // Pass control to the next middleware/route handler
};
app.get("/api/profile", authLogger, (req, res) => {
res.json({ message: "Welcome!", userId: req.userId });
});How It Works & Key Takeaways
Chaining middleware separates orthogonal concerns (authentication, CORS, rate limiting, logging) from route business logic.
Mock Test · 1 Questions · Optional
Ready for Error Handling?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions