0
0
Expressframework~10 mins

Protecting routes with auth middleware in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Protecting routes with auth middleware
Incoming Request
Auth Middleware
Auth OK
Next Route
Response
The request first passes through auth middleware which checks credentials. If valid, it proceeds to the route handler; if not, it sends a 401 Unauthorized response.
Execution Sample
Express
function auth(req, res, next) {
  if (req.user) next();
  else res.status(401).send('Unauthorized');
}

app.get('/dashboard', auth, (req, res) => {
  res.send('Welcome!');
});
This code checks if a user is logged in before allowing access to the /dashboard route.
Execution Table
StepRequest URLreq.userMiddleware ActionRoute Handler CalledResponse Sent
1/dashboardundefinedCheck req.user -> falseNo401 Unauthorized
2/dashboard{id:1}Check req.user -> trueYesWelcome!
💡 Execution stops after sending response either from middleware (401) or route handler (Welcome!)
Variable Tracker
VariableStartAfter Step 1After Step 2
req.userundefinedundefined{id:1}
next calledfalsefalsetrue
response statusnone401200
response bodynone'Unauthorized''Welcome!'
Key Moments - 2 Insights
Why does the route handler not run when req.user is undefined?
Because the middleware sends a 401 response and does not call next(), stopping further execution as shown in execution_table step 1.
What does calling next() inside middleware do?
Calling next() passes control to the next middleware or route handler, allowing the request to continue as shown in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response is sent when req.user is missing?
A401 Unauthorized
BWelcome!
C404 Not Found
D500 Internal Server Error
💡 Hint
Check execution_table row 1 under 'Response Sent'
At which step does the route handler get called?
AStep 1
BStep 2
CNeither step
DBoth steps
💡 Hint
Look at 'Route Handler Called' column in execution_table
If middleware always calls next() without checking req.user, what happens?
AMiddleware blocks all requests
BServer crashes
CUnauthorized users access the route
DResponse is always 401
💡 Hint
Think about what happens if middleware never sends 401 and always calls next()
Concept Snapshot
Protect routes by adding auth middleware before route handlers.
Middleware checks if user is logged in (req.user).
If yes, call next() to continue.
If no, send 401 Unauthorized response.
This stops unauthorized access simply and clearly.
Full Transcript
In Express, protecting routes means checking if a user is logged in before allowing access. We write a middleware function that looks at req.user. If req.user exists, it calls next() to let the request continue to the route handler. If not, it sends a 401 Unauthorized response and stops. This way, only authorized users reach the route. The execution table shows two cases: one where req.user is missing and the middleware sends 401, and one where req.user exists and the route handler sends a welcome message. Key points are that calling next() passes control forward, and not calling next() stops the request. If middleware always calls next() without checking, unauthorized users can access protected routes. This pattern keeps routes safe with simple checks.