Protecting routes with auth middleware helps keep parts of your app safe. It checks if a user is allowed before they see certain pages.
Protecting routes with auth middleware in Express
Start learning this pattern below
Jump into concepts and practice - no test required
function authMiddleware(req, res, next) {
if (req.user) {
next(); // allow access
} else {
res.status(401).send('Not authorized');
}
}
app.get('/protected-route', authMiddleware, (req, res) => {
res.send('This is protected');
});The middleware function runs before the route handler.
Call next() to continue if the user is allowed.
req.user exists to allow access.function authMiddleware(req, res, next) {
if (req.user) {
next();
} else {
res.status(401).send('Please log in');
}
}app.get('/dashboard', authMiddleware, (req, res) => { res.send('Welcome to your dashboard'); });
/admin with the auth middleware.app.use('/admin', authMiddleware); app.get('/admin/settings', (req, res) => { res.send('Admin settings page'); });
This example shows a simple Express app with a public route and a protected route. The authMiddleware checks if the request has a header x-user. If yes, it allows access to the profile page. Otherwise, it sends a 401 error.
import express from 'express'; const app = express(); // Simple auth middleware function authMiddleware(req, res, next) { // Simulate user logged in if header 'x-user' exists if (req.headers['x-user']) { next(); } else { res.status(401).send('Not authorized'); } } // Public route app.get('/', (req, res) => { res.send('Welcome to the public page'); }); // Protected route app.get('/profile', authMiddleware, (req, res) => { res.send('This is your profile'); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Middleware runs in the order you add it, so place auth middleware before protected routes.
In real apps, auth checks usually look at tokens or sessions, not just headers.
Always send a clear message or redirect when access is denied.
Auth middleware checks if a user can access a route.
Use next() to allow access, or send an error to block.
Protect routes by adding middleware before route handlers.
Practice
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 AQuick Check:
Auth middleware = Access control [OK]
- Confusing auth middleware with logging middleware
- Thinking middleware serves static files
- Assuming middleware formats response data
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.Final Answer:
app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); -> Option AQuick Check:
Middleware before handler = app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); [OK]
- Placing middleware after the handler
- Passing middleware as the first argument instead of path
- Calling middleware inside the handler instead of passing it
function authMiddleware(req, res, next) {
if (req.headers.authorization === 'valid-token') {
next();
} else {
res.status(401).send('Unauthorized');
}
}
app.get('/dashboard', authMiddleware, (req, res) => {
res.send('Welcome to dashboard');
});Solution
Step 1: Analyze authMiddleware logic
If the authorization header equals 'valid-token', next() is called to continue.Step 2: Check behavior when token is missing or invalid
Else block sends 401 Unauthorized response and does not call next(), blocking access.Final Answer:
The user gets a 401 Unauthorized response if token is missing or invalid -> Option CQuick Check:
Invalid token = 401 Unauthorized [OK]
- Assuming next() is always called
- Thinking user always sees dashboard
- Confusing 401 with 404 errors
function authMiddleware(req, res, next) {
if (!req.user) {
res.status(403).send('Forbidden');
}
next();
}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 BQuick Check:
Call next() only if no response sent [OK]
- Calling next() after res.send()
- Not stopping middleware after response
- Using wrong status codes for auth errors
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'?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 DQuick Check:
Use app.use for shared middleware [OK]
- Applying middleware only to some routes inconsistently
- Calling middleware inside handlers manually
- Applying middleware after route handlers
