In Express, middleware functions are essential. What is their main purpose?
Think about what happens after a request arrives but before the response is sent.
Middleware functions act like checkpoints that can modify the request or response objects, or perform actions like logging, authentication, or error handling before the final response is sent.
Consider an Express app with multiple middleware functions. How does Express decide the order in which middleware runs?
Think about how you write middleware in your code file.
Express executes middleware in the sequence they are registered. This order controls how requests are processed step-by-step.
Which of the following code snippets correctly defines a middleware function that logs the request method and URL?
app.use( /* your middleware here */ );Middleware needs to call next() to pass control to the next function.
A middleware function must accept three parameters: req, res, and next. It should call next() to continue the chain.
Look at this middleware code:
app.use((req, res, next) => {
console.log('Request received');
// missing next() call
});What is the reason the client never gets a response?
Think about how Express moves from one middleware to the next.
If next() is not called and no response is sent, the request stays open and the client waits forever.
Given this Express app code:
app.use((req, res, next) => {
req.customValue = 1;
next();
});
app.use((req, res, next) => {
req.customValue += 2;
next();
});
app.get('/', (req, res) => {
res.send(`Value is ${req.customValue}`);
});What will the client see when requesting /?
Consider how middleware can add or change properties on the req object.
Each middleware runs in order and can modify req. The first sets customValue to 1, the second adds 2, so the final value is 3.