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
appCreate a middleware function called
authMiddlewareUse
authMiddleware to protect the /dashboard routeSend 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