0
0
Expressframework~30 mins

Middleware factory pattern in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware Factory Pattern in Express
📖 Scenario: You are building a simple Express server that logs requests differently based on a log level setting.This helps you see only important logs in production and more details during development.
🎯 Goal: Create a middleware factory function that returns a logging middleware configured with a given log level.Use this middleware in your Express app to log requests accordingly.
📋 What You'll Learn
Create a middleware factory function named createLogger that accepts a level parameter.
Inside the factory, return a middleware function that logs the HTTP method and URL.
If level is 'verbose', also log the request headers.
Use the middleware in an Express app for all routes.
Start the Express server on port 3000.
💡 Why This Matters
🌍 Real World
Middleware factories let you create reusable and configurable middleware for web servers, making your code cleaner and easier to maintain.
💼 Career
Understanding middleware patterns is essential for backend developers working with Express or similar frameworks to build scalable and flexible web applications.
Progress0 / 4 steps
1
Setup Express app
Create an Express app by requiring express and calling express(). Store it in a variable called app.
Express
Need a hint?

Use require('express') to import Express and then call it to create the app.

2
Create middleware factory function
Write a function named createLogger that takes one parameter level and returns a middleware function with parameters req, res, and next.
Express
Need a hint?

The factory returns a middleware function that takes req, res, and next.

3
Add logging logic inside middleware
Inside the middleware returned by createLogger, log the HTTP method and URL using console.log. If level is 'verbose', also log req.headers. Then call next().
Express
Need a hint?

Use template strings to log method and URL. Check if level equals 'verbose' to log headers.

4
Use middleware and start server
Use app.use to add the middleware from createLogger with the argument 'verbose'. Then start the server on port 3000 using app.listen.
Express
Need a hint?

Call app.use with the middleware from createLogger('verbose'). Then call app.listen(3000) to start the server.