How to Protect Routes in Express: Simple Middleware Guide
To protect routes in
Express, use middleware functions that check user authentication or permissions before allowing access. Apply this middleware to routes you want to secure by passing it as an argument before the route handler.Syntax
In Express, route protection is done by adding a middleware function that runs before the route handler. The middleware checks if the user is allowed to access the route.
Basic syntax:
app.get('/protected-route', middlewareFunction, (req, res) => {
// route handler code
});Here, middlewareFunction decides if the request continues or is blocked.
javascript
function middlewareFunction(req, res, next) { // Check if user is authenticated if (req.isAuthenticated && req.isAuthenticated()) { next(); // allow access } else { res.status(401).send('Unauthorized'); // block access } } app.get('/protected-route', middlewareFunction, (req, res) => { res.send('This is a protected route'); });
Example
This example shows a simple Express app that protects a route by checking if a user is logged in using a custom middleware. If not logged in, it sends a 401 Unauthorized response.
javascript
import express from 'express'; const app = express(); const PORT = 3000; // Simple fake authentication check function isLoggedIn(req) { // For demo, check if header 'x-user' exists return req.headers['x-user'] !== undefined; } // Middleware to protect routes function protectRoute(req, res, next) { if (isLoggedIn(req)) { next(); } else { res.status(401).send('Unauthorized: Please log in'); } } // Public route app.get('/', (req, res) => { res.send('Welcome to the public page'); }); // Protected route app.get('/dashboard', protectRoute, (req, res) => { res.send('Welcome to your dashboard'); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Output
Server running on http://localhost:3000
Common Pitfalls
- Not calling
next()in middleware blocks the request forever. - Applying middleware after the route handler has no effect.
- Forgetting to handle unauthorized access properly can expose sensitive data.
- Using synchronous checks that block the event loop can slow down your app.
javascript
/* Wrong: Missing next() call blocks requests */ function badMiddleware(req, res, next) { if (req.isAuthenticated && req.isAuthenticated()) { // forgot next(); request hangs here } else { res.status(401).send('Unauthorized'); } } /* Right: Always call next() to continue */ function goodMiddleware(req, res, next) { if (req.isAuthenticated && req.isAuthenticated()) { next(); } else { res.status(401).send('Unauthorized'); } }
Quick Reference
Tips to protect routes in Express:
- Use middleware functions to check authentication or roles.
- Apply middleware before route handlers.
- Send proper HTTP status codes like 401 for unauthorized access.
- Keep middleware fast and non-blocking.
- Test routes with and without authentication headers.
Key Takeaways
Use middleware functions to check user authentication before route handlers.
Always call next() in middleware to allow the request to proceed.
Apply route protection middleware before the route handler in Express.
Respond with 401 Unauthorized status when access is denied.
Keep middleware logic simple and non-blocking for better performance.