Consider this Express middleware that checks for a token in the request headers before allowing access to a route.
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).send('Access denied. No token provided.');
}
next();
}
app.get('/dashboard', authMiddleware, (req, res) => {
res.send('Welcome to your dashboard');
});What will the server respond if a request to /dashboard has no authorization header?
Think about what the middleware does when the token is missing.
The middleware checks if the token exists. If it doesn't, it sends a 401 status with a message and does not call next(). So the route handler is never reached.
Look at this Express middleware code meant to protect routes:
function auth(req, res, next) {
const token = req.headers.authorization
if (!token) {
res.status(401).send('Unauthorized')
} else {
next()
}
}What is the syntax error that will cause this code to fail?
Check if the code syntax matches JavaScript rules.
JavaScript does not require semicolons strictly, and calling next() with parentheses is correct. The code has no syntax errors.
Review this middleware:
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (token) {
next();
}
res.status(401).send('Unauthorized');
}What is the problem with this code?
Consider what happens after next() is called.
The middleware calls next() if token exists, but then continues to send a 401 response anyway. This causes an error because the response is sent twice.
Given this middleware that verifies a token and adds user info:
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).send('No token');
}
// Simulate token verification
if (token === 'valid-token') {
req.user = { id: 123, name: 'Alice' };
next();
} else {
res.status(403).send('Invalid token');
}
}What will req.user be inside the route handler if the request header authorization is valid-token?
Look at where req.user is assigned.
If the token matches 'valid-token', the middleware sets req.user to the user object before calling next(). So the route handler can access it.
You want to protect these routes so only authenticated users can access them:
app.get('/profile', authMiddleware, (req, res) => { res.send('Profile page'); });
app.get('/settings', authMiddleware, (req, res) => { res.send('Settings page'); });Which approach is best to avoid repeating authMiddleware on every route?
Think about grouping routes and applying middleware efficiently.
Using a router with authMiddleware applied once is a clean way to protect multiple routes without repeating middleware on each route. app.use(authMiddleware) applies middleware globally, which may be too broad.