Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Protecting routes with auth middleware
📖 Scenario: You are building a simple web server using Express.js. Some routes should only be accessible to users who are logged in. To do this, you will create a middleware function that checks if a user is authenticated before allowing access to those routes.
🎯 Goal: Build an Express.js server with a middleware function called authMiddleware that protects a route /dashboard. Only requests with a valid req.user property can access the dashboard. Others get a 401 Unauthorized response.
📋 What You'll Learn
Create an Express app variable called app
Create a middleware function called authMiddleware
Use authMiddleware to protect the /dashboard route
Send a 401 status with message 'Unauthorized' if user is not authenticated
Send a 200 status with message 'Welcome to your dashboard' if authenticated
💡 Why This Matters
🌍 Real World
Web applications often need to restrict access to certain pages or APIs to logged-in users only. Middleware is a common way to check authentication before allowing access.
💼 Career
Understanding how to protect routes with middleware is essential for backend developers working with Express.js or similar web frameworks.
Progress0 / 4 steps
1
Set up Express app and a sample user
Create an Express app by requiring express and calling express(). Also create a sample user object called user with id 1 and name 'Alice'.
Express
Hint
Use const app = express() to create the app. Define user as an object with id and name.
2
Create auth middleware function
Create a middleware function called authMiddleware that takes req, res, and next. Inside, set req.user to the user object you created. Then call next().
Express
Hint
Define authMiddleware as a function with three parameters. Assign req.user = user and call next() to continue.
3
Protect the /dashboard route with authMiddleware
Create a GET route /dashboard on app. Use authMiddleware as the middleware for this route. Inside the route handler, check if req.user exists. If it does, send status 200 with JSON message 'Welcome to your dashboard'. If not, send status 401 with JSON message 'Unauthorized'.
Express
Hint
Use app.get with /dashboard and authMiddleware. Check req.user inside the handler and respond accordingly.
4
Start the Express server
Add code to start the Express server by calling app.listen on port 3000. Inside the callback, log the message 'Server running on port 3000'.
Express
Hint
Use app.listen with port 3000 and a callback that logs the message.
Practice
(1/5)
1. What is the main purpose of auth middleware in an Express app?
easy
A. To check if a user is allowed to access a route
B. To format the response data before sending
C. To log every request made to the server
D. To serve static files like images and CSS
Solution
Step 1: Understand middleware role
Middleware runs before route handlers to process requests.
Step 2: Identify auth middleware function
Auth middleware specifically checks user permissions to allow or deny access.
Final Answer:
To check if a user is allowed to access a route -> Option A
Quick Check:
Auth middleware = Access control [OK]
Hint: Auth middleware controls access to routes [OK]
Common Mistakes:
Confusing auth middleware with logging middleware
Thinking middleware serves static files
Assuming middleware formats response data
2. Which of the following is the correct way to use auth middleware for a route in Express?
easy
A. app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); });
B. app.get(authMiddleware, '/profile', (req, res) => { res.send('Profile'); });
C. app.get('/profile', (req, res) => { authMiddleware(); res.send('Profile'); });
D. app.get('/profile', (req, res) => { res.send('Profile'); }, authMiddleware);
Solution
Step 1: Recall Express route syntax
Middleware functions come before the final route handler in the argument list.
Step 2: Check each option's order
Only app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); places authMiddleware correctly before the handler function.
4. Identify the error in this auth middleware code:
function authMiddleware(req, res, next) {
if (!req.user) {
res.status(403).send('Forbidden');
}
next();
}
medium
A. Missing call to next() inside the if block
B. next() is called even after sending a response, causing an error
C. Status code 403 is incorrect for unauthorized access
D. req.user should be checked with req.auth instead
Solution
Step 1: Understand middleware flow
If !req.user is true, response is sent with status 403.
Step 2: Check what happens after sending response
next() is called unconditionally after the if block, so it runs even after response sent, causing errors.
Final Answer:
next() is called even after sending a response, causing an error -> Option B
Quick Check:
Call next() only if no response sent [OK]
Hint: Do not call next() after sending a response [OK]
Common Mistakes:
Calling next() after res.send()
Not stopping middleware after response
Using wrong status codes for auth errors
5. You want to protect multiple routes with the same auth middleware and also log the user ID if authenticated. Which is the best way to do this?
function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized');
}
req.userId = req.headers.authorization;
next();
}
// How to apply this middleware and log userId for routes '/profile' and '/settings'?
hard
A. Apply authMiddleware after route handlers to log userId
B. Add authMiddleware only to '/profile' route and log userId in '/settings' without middleware
C. Call authMiddleware inside each route handler manually before logging userId
D. Use app.use(authMiddleware) before defining both routes, then log req.userId inside each route handler
Solution
Step 1: Understand middleware application
app.use(authMiddleware) applies middleware to all routes defined after it, protecting multiple routes easily.
Step 2: Logging userId in route handlers
Since authMiddleware sets req.userId, route handlers can access and log it safely after middleware runs.
Final Answer:
Use app.use(authMiddleware) before defining both routes, then log req.userId inside each route handler -> Option D
Quick Check:
Use app.use for shared middleware [OK]
Hint: Use app.use(authMiddleware) to protect many routes [OK]
Common Mistakes:
Applying middleware only to some routes inconsistently