📖 Scenario: You are building a simple web server using Node.js and Express. Middleware functions help your server handle requests step-by-step, like a helpful assistant passing tasks along.
🎯 Goal: Create a basic Express server that uses middleware to log requests and send a response. This will show how middleware works in a real server.
📋 What You'll Learn
Create an Express app instance
Add a middleware function that logs the HTTP method and URL of each request
Add a route handler for GET requests to '/' that sends a welcome message
Start the server listening on port 3000
💡 Why This Matters
🌍 Real World
Middleware is used in real web servers to handle tasks like logging, authentication, and error handling step-by-step.
💼 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
Write import express from 'express' and create a variable called app by calling express().
Node.js
Hint
Use import express from 'express' to bring in Express, then const app = express() to create your app.
2
Add logging middleware
Add a middleware function using app.use that takes req, res, and next parameters. Inside it, log the request method and URL using console.log, then call next().
Node.js
Hint
Middleware functions get req, res, and next. Log the method and URL, then call next() to continue.
3
Add route handler
Add a GET route handler for path '/' using app.get. The handler should send the text 'Welcome to the middleware demo!' using res.send.
Node.js
Hint
Use app.get with path '/' and send the welcome message with res.send.
4
Start the server
Call app.listen with port 3000 and a callback function that logs 'Server running on port 3000'.
Node.js
Hint
Use app.listen(3000, () => { ... }) to start the server and log a message.
Practice
(1/5)
1. What is the main role of middleware in a Node.js application?
easy
A. To run code between receiving a request and sending a response
B. To directly send HTML pages to the client
C. To store data permanently in a database
D. To compile JavaScript code into machine code
Solution
Step 1: Understand middleware position in request flow
Middleware functions run after a request is received but before the response is sent back.
Step 2: Identify middleware purpose
Middleware is used to process or modify requests and responses, like logging or authentication, not to send pages or store data directly.
Final Answer:
To run code between receiving a request and sending a response -> Option A
Quick Check:
Middleware = code between request and response [OK]
Hint: Middleware runs between request and response [OK]
Common Mistakes:
Thinking middleware sends the final response directly
Confusing middleware with database operations
Assuming middleware compiles code
2. Which of the following is the correct way to define a middleware function in Express.js?
easy
A. app.use((req, res, next) => { console.log('Middleware'); next(); });
B. app.get((req, res) => { console.log('Middleware'); });
C. app.listen((req, res, next) => { next(); });
D. app.middleware((req, res, next) => { next(); });
Solution
Step 1: Recall Express middleware syntax
Middleware is added using app.use() with a function that takes req, res, and next parameters.
Step 2: Check each option
app.use((req, res, next) => { console.log('Middleware'); next(); }); uses app.use() correctly and calls next() to pass control. Others use wrong methods or miss next().
5. You want to add middleware that logs request method and URL, then checks if user is authenticated before continuing. Which code correctly combines these tasks?
B. app.use((req, res) => { console.log(req.method, req.url); next(); if (!req.user) res.send('Unauthorized'); });
C. app.use((req, res, next) => { if (!req.user) next(); console.log(req.method, req.url); next(); });
D. app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); });
Solution
Step 1: Log request method and URL first
app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); logs method and URL immediately, which is correct for logging middleware.
Step 2: Check authentication before calling next()
app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); checks if req.user exists; if not, it sends 401 response and stops. Otherwise, it calls next() to continue.
Step 3: Verify other options
The other options misuse next() or res.send(), causing incorrect flow or multiple calls.
Final Answer:
app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); -> Option D
Quick Check:
Log then check auth, call next() only if authorized [OK]
Hint: Log first, then check auth, call next() only if authorized [OK]
Common Mistakes:
Calling next() after sending response
Not stopping middleware on unauthorized access
Logging after next() causing missed logs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.