0
0
Expressframework~30 mins

Protecting routes with auth middleware in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.listen with port 3000 and a callback that logs the message.