0
0
Node.jsframework~30 mins

Building custom middleware in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Building custom middleware
📖 Scenario: You are creating a simple Node.js server using Express. You want to add a custom middleware function that logs the request method and URL for every incoming request.
🎯 Goal: Build a custom middleware function in Express that logs the HTTP method and URL of each request, then use it in your server.
📋 What You'll Learn
Create an Express app
Write a middleware function named logger that logs the request method and URL
Use the logger middleware in the Express app
Add a simple route / that sends a response
💡 Why This Matters
🌍 Real World
Middleware is used in real web servers to add features like logging, authentication, and error handling without changing route code.
💼 Career
Understanding middleware is essential for backend developers working with Node.js and Express to build scalable and maintainable web applications.
Progress0 / 4 steps
1
Set up Express app
Create a variable called express that requires the 'express' module. Then create a variable called app by calling express().
Node.js
Need a hint?

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

2
Create logger middleware
Write a middleware function called logger that takes req, res, and next as parameters. Inside it, log the request method and URL using console.log, then call next().
Node.js
Need a hint?

The middleware function must call next() to pass control to the next middleware.

3
Use logger middleware in app
Use the logger middleware in the Express app by calling app.use(logger).
Node.js
Need a hint?

Use app.use() to add middleware to the Express app.

4
Add a simple route
Add a GET route for / using app.get that sends the text 'Hello World' as the response.
Node.js
Need a hint?

Use app.get with a callback that calls res.send to send the response.