Consider two middleware functions authA and authB used in sequence in an Express route. What will happen if authA calls next() without error, but authB sends a response and does not call next()?
const authA = (req, res, next) => { console.log('authA'); next(); };
const authB = (req, res, next) => { console.log('authB'); res.status(401).send('Unauthorized'); };
app.get('/secure', authA, authB, (req, res) => { res.send('Welcome'); });Think about what happens when a middleware sends a response and does not call next().
When authB sends a response and does not call next(), Express stops processing further middleware or handlers. So the final handler is never called, and the client receives the 'Unauthorized' response.
Given two middleware functions auth1 and auth2, which option correctly applies both to a route /dashboard so that auth1 runs before auth2?
Remember how Express accepts multiple middleware functions as separate arguments.
Express expects middleware functions as separate arguments or as an array. Option B correctly passes them as separate arguments in the desired order. Option B reverses the order, and options A and D use invalid JavaScript expressions.
Examine the following middleware composition. Why does the request to /profile never complete?
const checkToken = (req, res, next) => { if (!req.headers.token) { res.status(401).send('No token'); } else { next(); } };
const verifyUser = (req, res, next) => { if (req.headers.token === 'valid') { next(); } else { res.status(401).send('Invalid token'); } };
app.get('/profile', checkToken, verifyUser, (req, res) => { res.send('User Profile'); });Look at all code paths in verifyUser and see if next() or res.send() is always called.
If verifyUser does not call next() or send a response when the token is invalid, Express waits indefinitely. This causes the request to hang.
Given these two middlewares, what will be the value of req.user in the final handler?
const authA = (req, res, next) => { req.user = { id: 1, role: 'user' }; next(); };
const authB = (req, res, next) => { if (req.user.role === 'user') { req.user.permissions = ['read']; } next(); };
app.get('/data', authA, authB, (req, res) => { res.json(req.user); });Consider how req.user is modified by each middleware.
The first middleware sets req.user with id and role. The second adds a permissions array if the role is 'user'. So the final req.user has id, role, and permissions.
When building layered authentication with multiple middleware functions in Express, which statement is true about their composition and execution?
Think about how Express processes middleware functions sequentially.
Express executes middleware functions one after another in the order they are declared. Each middleware must call next() to continue or send a response to end the request. They do not run in parallel or automatically merge results.