Bird
Raised Fist0
Node.jsframework~10 mins

Building custom middleware in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Building custom middleware
Request received
↓
Middleware function called
↓
Middleware processes request
↓
Modify req/res objects
↓
Perform logic (e.g., logging, auth)
↓
Call next() to pass control
↓
Next middleware or route handler runs
↓
Response sent back
When a request comes in, the middleware runs, can change request or response, then calls next() to continue the flow.
Execution Sample
Node.js
function logger(req, res, next) {
  console.log(`Request: ${req.method} ${req.url}`);
  next();
}
This middleware logs the request method and URL, then passes control to the next handler.
Execution Table
StepActionreq.methodreq.urlConsole Outputnext() calledNext Handler
1Request receivedGET/homeNoNo
2Middleware logger runsGET/homeRequest: GET /homeYesNo
3next() passes controlGET/homeYesYes
4Route handler runsGET/homeYesYes
5Response sentGET/homeYesYes
💡 Middleware calls next(), so control moves to next handler and response is sent.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
req.methodGETGETGETGET
req.url/home/home/home/home
next() calledfalsetruetruetrue
Key Moments - 2 Insights
Why do we need to call next() inside middleware?
Calling next() tells Node.js to continue to the next middleware or route handler. Without it, the request will hang and never complete, as shown in execution_table step 2 where next() is called to proceed.
Can middleware modify the request or response objects?
Yes, middleware can change req or res objects before passing control. This is useful for adding data or headers. The execution_table shows req.method and req.url unchanged here, but they could be modified.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is logged to the console at step 2?
A"Request: GET /home"
B"Request: POST /login"
C"Error: no next() called"
D"Response sent"
💡 Hint
Check the 'Console Output' column at step 2 in execution_table.
At which step is next() first called according to the execution_table?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'next() called' column to see when it changes from No to Yes.
If next() was not called in the middleware, what would happen?
ARequest would continue to next handler
BRequest would hang and never complete
CResponse would be sent immediately
DMiddleware would run twice
💡 Hint
Refer to key_moments explanation about the importance of calling next().
Concept Snapshot
Middleware is a function with (req, res, next).
It runs on each request.
It can modify req or res.
Must call next() to continue.
Without next(), request hangs.
Used for logging, auth, etc.
Full Transcript
When a request arrives, Node.js calls middleware functions in order. Each middleware receives request and response objects and a next function. Middleware can log info, check authentication, or modify data. After its work, middleware must call next() to pass control to the next middleware or route handler. If next() is not called, the request will hang and no response will be sent. This flow ensures modular and reusable processing steps for requests.

Practice

(1/5)
1. What is the main purpose of custom middleware in a Node.js Express app?
easy
A. To directly send HTML pages to the client
B. To add extra processing steps between receiving a request and sending a response
C. To replace the Express router completely
D. To store data permanently in a database

Solution

  1. Step 1: Understand middleware role

    Middleware functions run between receiving a request and sending a response, allowing extra processing.
  2. Step 2: Identify correct purpose

    Custom middleware adds steps like logging, authentication, or modifying requests before response.
  3. Final Answer:

    To add extra processing steps between receiving a request and sending a response -> Option B
  4. Quick Check:

    Middleware = extra processing steps [OK]
Hint: Middleware adds steps between request and response [OK]
Common Mistakes:
  • Thinking middleware sends responses directly always
  • Confusing middleware with routing
  • Assuming middleware stores data permanently
2. Which of the following is the correct syntax to define a simple middleware function in Express?
easy
A. app.use = function(req, res, next) { console.log('Hi'); next(); }
B. app.middleware(req, res, next) { console.log('Hi'); next(); }
C. app.use(req, res, next) => { console.log('Hi'); next(); }
D. app.use((req, res, next) => { console.log('Hi'); next(); });

Solution

  1. Step 1: Recall Express middleware syntax

    Middleware is added using app.use() with a function taking (req, res, next).
  2. 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.
  3. Final Answer:

    app.use((req, res, next) => { console.log('Hi'); next(); }); -> Option D
  4. Quick Check:

    app.use + (req, res, next) function = correct [OK]
Hint: Middleware uses app.use with (req, res, next) function [OK]
Common Mistakes:
  • Missing parentheses around parameters
  • Assigning app.use instead of calling it
  • Using arrow function without parentheses for multiple params
3. Consider this middleware code snippet:
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 '/'?
medium
A. Value is 42
B. Value is undefined
C. Error: req.customValue is not defined
D. Empty response

Solution

  1. 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.
  2. Step 2: Check route handler usage

    The route handler reads req.customValue and sends it in the response string.
  3. Final Answer:

    Value is 42 -> Option A
  4. Quick Check:

    Middleware sets req.customValue = 42 [OK]
Hint: Middleware can add properties to req used later [OK]
Common Mistakes:
  • Assuming req.customValue is lost after middleware
  • Thinking next() stops execution
  • Expecting error without setting property
4. Identify the error in this middleware code:
app.use((req, res, next) => {
  if (!req.headers['x-auth']) {
    res.status(401).send('Unauthorized');
  }
  next();
});
medium
A. Calling next() after sending a response causes error
B. Missing call to next() inside the if block
C. Headers should be accessed as req.header, not req.headers
D. Middleware must always send a response

Solution

  1. Step 1: Analyze middleware flow

    If 'x-auth' header is missing, response is sent with 401 status, ending the request.
  2. Step 2: Check next() call after response

    Calling next() after sending a response causes Express to continue processing, leading to errors.
  3. Final Answer:

    Calling next() after sending a response causes error -> Option A
  4. Quick Check:

    Do not call next() after res.send [OK]
Hint: Don't call next() after sending response [OK]
Common Mistakes:
  • Calling next() after res.send causing double response
  • Assuming headers property name is wrong
  • Thinking middleware must always send response
5. You want to create middleware that logs request method and URL only for POST requests. Which code correctly implements this?
hard
A. app.use((req, res, next) => { if (req.method = 'POST') console.log(req.method, req.url); next(); });
B. app.use((req, res, next) => { if (req.method === 'post') console.log(req.method, req.url); next(); });
C. app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); });
D. app.use((req, res, next) => { if (req.method === POST) console.log(req.method, req.url); next(); });

Solution

  1. Step 1: Check condition for POST method

    Correct comparison uses '===' and string 'POST' in uppercase.
  2. 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.
  3. Final Answer:

    app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); }); -> Option C
  4. Quick Check:

    Use strict equality and uppercase 'POST' [OK]
Hint: Use === 'POST' to check method string correctly [OK]
Common Mistakes:
  • Using single = instead of === for comparison
  • Using lowercase 'post' instead of uppercase
  • Using undefined POST variable without quotes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard