Middleware functions are used in Node.js web frameworks like Express. What is their main purpose?
Think about how middleware acts between the client request and the final response.
Middleware functions sit between the incoming request and the final route handler. They can modify the request or response, perform checks, or add data before the final response is sent.
Consider this Express middleware chain:
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); next(); });
app.get('/', (req, res) => { res.send('Done'); });What will be printed in the console when a GET request is made to '/'?
Middleware functions run in the order they are added and call next() to continue.
The first middleware logs 'First' and calls next(), then the second logs 'Second' and calls next(), finally the route handler sends 'Done'. The console shows 'First' then 'Second'.
Look at this middleware code snippet:
app.use((req, res, next) => {
if (!req.user) {
res.status(401).send('Unauthorized');
}
next();
});What problem will this cause when a request has no user?
Think about what happens after sending a response in middleware.
After sending a response, calling next() continues to the next middleware or route, which tries to send another response, causing an error.
Given this Express setup:
app.use((req, res, next) => {
req.customData = 'Hello';
next();
});
app.use((req, res, next) => {
req.customData += ' World';
next();
});
app.get('/', (req, res) => {
res.send(req.customData);
});What will the client receive when requesting '/'?
Middleware can add or change properties on the request object.
The first middleware sets req.customData to 'Hello'. The second adds ' World'. The route sends the combined string.
Examine this middleware:
app.use((req, res, next) => {
if (req.path === '/stop') {
return res.send('Stopped');
} else {
next();
}
});Requests to '/stop' hang and never complete. Why?
Think about what happens after res.send() inside an if block.
Without a return after res.send(), the function continues and may cause unexpected behavior. Adding return stops further execution.