Middleware helps you add extra steps when your server handles requests. It lets you run code before sending a response.
Building custom middleware in Node.js
function middlewareName(req, res, next) {
// Your code here
next();
}The req is the request object with info about the client request.
The res is the response object used to send data back.
The next is a function you call to move to the next middleware or route.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}function addPoweredBy(req, res, next) {
res.setHeader('X-Powered-By', 'Node.js');
next();
}function checkAuth(req, res, next) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
} else {
next();
}
}This example creates a simple Express server. It uses a custom middleware called logger that prints the HTTP method and URL for every request. Then it responds with 'Hello, world!' on the home page.
import express from 'express'; const app = express(); // Custom middleware to log requests function logger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); } // Use the middleware for all routes app.use(logger); app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always call next() in your middleware unless you send a response directly.
Middleware runs in the order you add it with app.use() or on routes.
You can create middleware to handle errors by defining a function with four arguments: (err, req, res, next).
Middleware lets you add extra steps when handling requests.
It uses three arguments: req, res, and next.
Call next() to continue to the next step or send a response to end.
Practice
Solution
Step 1: Understand middleware role
Middleware functions run between receiving a request and sending a response, allowing extra processing.Step 2: Identify correct purpose
Custom middleware adds steps like logging, authentication, or modifying requests before response.Final Answer:
To add extra processing steps between receiving a request and sending a response -> Option BQuick Check:
Middleware = extra processing steps [OK]
- Thinking middleware sends responses directly always
- Confusing middleware with routing
- Assuming middleware stores data permanently
Solution
Step 1: Recall Express middleware syntax
Middleware is added using app.use() with a function taking (req, res, next).Step 2: Check each option
app.use((req, res, next) => { console.log('Hi'); next(); }); correctly uses app.use with an arrow function and calls next(). Others have syntax errors.Final Answer:
app.use((req, res, next) => { console.log('Hi'); next(); }); -> Option DQuick Check:
app.use + (req, res, next) function = correct [OK]
- Missing parentheses around parameters
- Assigning app.use instead of calling it
- Using arrow function without parentheses for multiple params
app.use((req, res, next) => {
req.customValue = 42;
next();
});
app.get('/', (req, res) => {
res.send(`Value is ${req.customValue}`);
});What will be the response when a client requests '/'?
Solution
Step 1: Understand middleware effect on req object
The middleware adds a property customValue with 42 to the req object and calls next() to continue.Step 2: Check route handler usage
The route handler reads req.customValue and sends it in the response string.Final Answer:
Value is 42 -> Option AQuick Check:
Middleware sets req.customValue = 42 [OK]
- Assuming req.customValue is lost after middleware
- Thinking next() stops execution
- Expecting error without setting property
app.use((req, res, next) => {
if (!req.headers['x-auth']) {
res.status(401).send('Unauthorized');
}
next();
});Solution
Step 1: Analyze middleware flow
If 'x-auth' header is missing, response is sent with 401 status, ending the request.Step 2: Check next() call after response
Calling next() after sending a response causes Express to continue processing, leading to errors.Final Answer:
Calling next() after sending a response causes error -> Option AQuick Check:
Do not call next() after res.send [OK]
- Calling next() after res.send causing double response
- Assuming headers property name is wrong
- Thinking middleware must always send response
Solution
Step 1: Check condition for POST method
Correct comparison uses '===' and string 'POST' in uppercase.Step 2: Verify logging and next call
app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); }); logs method and URL only if method is POST, then calls next() to continue.Final Answer:
app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); }); -> Option CQuick Check:
Use strict equality and uppercase 'POST' [OK]
- Using single = instead of === for comparison
- Using lowercase 'post' instead of uppercase
- Using undefined POST variable without quotes
Ready to prove it?
Pass the test and this pattern moves unknown
