0
0
Expressframework~5 mins

Protecting routes with auth middleware in Express - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of auth middleware in Express?
Auth middleware checks if a user is logged in before allowing access to certain routes. It protects routes from unauthorized users.
Click to reveal answer
beginner
How do you apply auth middleware to a specific route in Express?
You add the middleware function as a second argument in the route definition, like: app.get('/dashboard', authMiddleware, (req, res) => {...}).
Click to reveal answer
beginner
What should auth middleware do if the user is not authenticated?
It should stop the request and respond with a status like 401 Unauthorized or redirect the user to a login page.
Click to reveal answer
intermediate
Why is middleware a good way to protect routes?
Middleware lets you reuse the same auth check on many routes without repeating code. It keeps your code clean and organized.
Click to reveal answer
beginner
Show a simple example of auth middleware in Express.
A simple auth middleware checks if <code>req.user</code> exists. If yes, it calls <code>next()</code> to continue. If no, it sends a 401 response.<br><br><code>function authMiddleware(req, res, next) {<br>  if (req.user) {<br>    next();<br>  } else {<br>    res.status(401).send('Unauthorized');<br>  }<br>}</code>
Click to reveal answer
What does auth middleware typically check before allowing access to a route?
AIf the user is logged in
BIf the server is running
CIf the database is connected
DIf the route exists
How do you add middleware to protect a route in Express?
ACall it inside the route handler
BAdd it as a second argument in the route definition
CAdd it after the route handler
DMiddleware cannot protect routes
What should auth middleware do if the user is not authenticated?
ALog the user in automatically
BCall next() to continue
CIgnore the request
DSend a 401 Unauthorized response
Why is using middleware good for protecting many routes?
AIt repeats code for each route
BIt slows down the server
CIt keeps code clean and reusable
DIt only works for one route
Which Express method is used to continue to the next middleware or route handler?
Anext()
Bres.send()
Capp.use()
Dreq.next()
Explain how auth middleware protects routes in Express and why it is useful.
Think about how middleware acts like a gatekeeper before route handlers.
You got /4 concepts.
    Write a simple auth middleware function for Express and describe what it does.
    Focus on the basic structure and the decision to allow or block access.
    You got /4 concepts.