Think about the step where the system checks who you are.
Authentication is about confirming who the user is, usually by checking credentials like username and password.
Think about what happens after the system knows who you are.
Authorization decides what an authenticated user can do or see within the system.
function authMiddleware(req, res, next) {
if (!req.user) {
return res.status(401).send('Unauthorized');
}
next();
}Look at the condition checking req.user and the response sent.
If req.user is missing, the middleware responds with 401 and does not call next(), stopping the request.
app.get('/admin', (req, res) => { if (!req.user?.roles.includes('admin')) { return res.status(403).send('Forbidden'); } res.send('Welcome Admin'); });
Check the condition that tests the user's roles.
If the user lacks the 'admin' role, the route sends a 403 Forbidden response and does not proceed.
function auth(req, res, next) {
if (req.headers.authorization === undefined) {
return res.status(401).send('No token');
}
next();
}Consider what happens after res.status(401).send() is called.
After sending a response, calling next() continues processing, which can cause errors because headers are already sent.