0
0
Expressframework~30 mins

Middleware composition for auth layers in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware Composition for Auth Layers in Express
📖 Scenario: You are building a simple Express server that needs to protect certain routes with authentication and authorization checks. Middleware functions will help you organize these checks step-by-step.
🎯 Goal: Build an Express app that uses composed middleware functions to check if a user is logged in and if they have admin rights before accessing a protected route.
📋 What You'll Learn
Create a middleware function called checkLoggedIn that verifies if req.user exists.
Create a middleware function called checkAdmin that verifies if req.user.role is 'admin'.
Compose these middleware functions in the correct order for a protected route /admin.
Send a success response 'Welcome Admin' if all checks pass.
💡 Why This Matters
🌍 Real World
Middleware composition is a common pattern in web servers to separate concerns like authentication, authorization, logging, and error handling. This makes code easier to read and maintain.
💼 Career
Understanding middleware in Express is essential for backend web development jobs, especially when building secure APIs and web applications.
Progress0 / 4 steps
1
Setup Express app and user data
Create an Express app by requiring express and calling express(). Then create a middleware function called mockUser that adds a user object { name: 'Alice', role: 'admin' } to req.user. Use app.use(mockUser) to apply it globally.
Express
Need a hint?

Start by importing Express and creating the app. Then write a middleware that sets req.user to the given object and call next().

2
Create authentication middleware
Create a middleware function called checkLoggedIn that checks if req.user exists. If it does, call next(). Otherwise, send a 401 status with message 'Not logged in'. Add this function below the mockUser middleware.
Express
Need a hint?

Check if req.user exists. If yes, call next(). Otherwise, respond with 401 and a message.

3
Create authorization middleware
Create a middleware function called checkAdmin that checks if req.user.role is exactly 'admin'. If yes, call next(). Otherwise, send a 403 status with message 'Access denied'. Add this function below checkLoggedIn.
Express
Need a hint?

Check if req.user.role equals 'admin'. If yes, call next(). Otherwise, respond with 403 and a message.

4
Compose middleware for protected route
Create a GET route /admin that uses the middleware functions checkLoggedIn and checkAdmin in that order. The route handler should send the text 'Welcome Admin'. Use app.listen(3000) to start the server.
Express
Need a hint?

Use app.get with the path '/admin' and pass checkLoggedIn and checkAdmin as middleware before the final handler. Then start the server on port 3000.