Bird
Raised Fist0
NestJSframework~20 mins

Functional middleware in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Functional Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS functional middleware?
Consider this functional middleware that logs request method and URL. What will be logged when a GET request is made to '/api/data'?
NestJS
import { Request, Response, NextFunction } from 'express';

export function logger(req: Request, res: Response, next: NextFunction) {
  console.log(`${req.method} ${req.url}`);
  next();
}
ALogs nothing and immediately sends a 404 response
BLogs: 'POST /api/data' and stops request processing
CThrows a runtime error because next() is missing
DLogs: 'GET /api/data' and passes control to next middleware
Attempts:
2 left
💡 Hint
Remember that next() passes control to the next middleware or route handler.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a functional middleware in NestJS?
Select the option that correctly defines a functional middleware that adds a custom header 'X-Custom' with value 'NestJS' to the response.
Aexport const customHeader = (req, res, next) => { res.headers['X-Custom'] = 'NestJS'; next(); }
Bexport function customHeader(req, res, next) { res.setHeader('X-Custom', 'NestJS'); next(); }
Cexport function customHeader(req: Request, res: Response, next: NextFunction) { res.setHeader('X-Custom', 'NestJS'); next(); }
Dexport function customHeader(req: Request, res: Response) { res.setHeader('X-Custom', 'NestJS'); }
Attempts:
2 left
💡 Hint
Check for correct TypeScript types and calling next() to continue.
❓ lifecycle
advanced
2:00remaining
When is functional middleware executed in NestJS request lifecycle?
Choose the correct statement about when functional middleware runs during a request in NestJS.
ABefore any route handler or controller method is called
BAfter the controller method but before the response is sent
COnly after all guards and interceptors have run
DOnly after the response is sent to the client
Attempts:
2 left
💡 Hint
Middleware runs early to modify request or response before controllers.
🔧 Debug
advanced
2:00remaining
Why does this functional middleware cause the request to hang?
Examine this middleware and select the reason the request never completes.
NestJS
export function hangMiddleware(req, res, next) {
  console.log('Middleware started');
  // Missing next() call
}
ABecause res.send() is called twice causing an error
BBecause next() is never called, the request never moves forward
CBecause the middleware throws an exception before next()
DBecause the middleware modifies req.url incorrectly
Attempts:
2 left
💡 Hint
Middleware must call next() to continue the request chain.
❓ state_output
expert
3:00remaining
What is the value of req.customData after this functional middleware runs?
Given this middleware that adds a customData property to the request, what will be the value of req.customData in the next middleware?
NestJS
import { Request, Response, NextFunction } from 'express';

interface CustomRequest extends Request {
  customData?: string;
}

export function addCustomData(req: CustomRequest, res: Response, next: NextFunction) {
  req.customData = 'NestJS Rocks!';
  next();
}
A'NestJS Rocks!'
Bnull
Cundefined
DThrows a TypeError because customData is not defined on Request
Attempts:
2 left
💡 Hint
The middleware adds customData property before calling next().

Practice

(1/5)
1. What is the main purpose of functional middleware in NestJS?
easy
A. To run code before the route handler to modify requests or add features
B. To define database models for the application
C. To create UI components for the frontend
D. To compile TypeScript code into JavaScript

Solution

  1. Step 1: Understand middleware role

    Middleware runs before route handlers to process requests or add features like logging or authentication.
  2. Step 2: Identify correct purpose

    Options A, B, and D relate to other parts of development, not middleware.
  3. Final Answer:

    To run code before the route handler to modify requests or add features -> Option A
  4. Quick Check:

    Middleware runs before routes = C [OK]
Hint: Middleware runs before routes to add features [OK]
Common Mistakes:
  • Confusing middleware with database models
  • Thinking middleware creates UI components
  • Believing middleware compiles code
2. Which of the following is the correct way to define a functional middleware in NestJS?
easy
A. function logger(req, res) { console.log(req.url); }
B. class Logger { log(req, res) { console.log(req.url); } }
C. const logger = () => { console.log('log'); }
D. function logger(req, res, next) { console.log(req.url); next(); }

Solution

  1. Step 1: Check middleware signature

    Functional middleware must accept (req, res, next) and call next() to continue.
  2. Step 2: Validate options

    function logger(req, res, next) { console.log(req.url); next(); } matches this pattern. class Logger { log(req, res) { console.log(req.url); } } is a class, not functional middleware. const logger = () => { console.log('log'); } lacks parameters and next call. function logger(req, res) { console.log(req.url); } misses next parameter and call.
  3. Final Answer:

    function logger(req, res, next) { console.log(req.url); next(); } -> Option D
  4. Quick Check:

    Middleware needs (req, res, next) and calls next() [OK]
Hint: Middleware needs (req, res, next) and calls next() [OK]
Common Mistakes:
  • Omitting the next parameter
  • Not calling next() inside middleware
  • Using class instead of function for functional middleware
3. Given this middleware code, what will be logged when a request to '/home' is made?
function logger(req, res, next) {
  console.log('Request URL:', req.url);
  next();
}
medium
A. Request URL: undefined
B. Request URL: /home
C. No output because next() stops logging
D. Error: req.url is not defined

Solution

  1. Step 1: Understand req.url property

    In middleware, req.url contains the path of the incoming request, here '/home'.
  2. Step 2: Analyze console.log output

    The middleware logs 'Request URL:' followed by req.url, so it prints 'Request URL: /home'.
  3. Final Answer:

    Request URL: /home -> Option B
  4. Quick Check:

    req.url logs request path = A [OK]
Hint: req.url holds the request path string [OK]
Common Mistakes:
  • Assuming next() stops console.log
  • Thinking req.url is undefined
  • Confusing middleware with route handler output
4. Identify the error in this functional middleware code:
function auth(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
  }
  next();
}
medium
A. res.status should be res.sendStatus
B. Missing req parameter in function signature
C. next() is called even after sending response, causing errors
D. Authorization header check is incorrect

Solution

  1. Step 1: Analyze flow after sending response

    If authorization header is missing, response is sent with 401, but next() is still called, which can cause errors by continuing the request cycle.
  2. Step 2: Identify correct fix

    To fix, add return before res.status(401).send(...) to stop execution or call next() only if authorized.
  3. Final Answer:

    next() is called even after sending response, causing errors -> Option C
  4. Quick Check:

    Call next() only if no response sent [OK]
Hint: Don't call next() after sending response [OK]
Common Mistakes:
  • Calling next() after res.send causes errors
  • Forgetting to stop middleware after response
  • Misusing res.status vs res.sendStatus
5. You want to create a functional middleware that adds a custom header 'X-App-Version' with value '1.0' to every response. Which code correctly implements this?
hard
A. function addVersion(req, res, next) { res.setHeader('X-App-Version', '1.0'); next(); }
B. function addVersion(req, res) { res.setHeader('X-App-Version', '1.0'); }
C. function addVersion(req, res, next) { next(); res.setHeader('X-App-Version', '1.0'); }
D. function addVersion(req, res, next) { req.setHeader('X-App-Version', '1.0'); next(); }

Solution

  1. Step 1: Confirm middleware signature and header setting

    Middleware must accept (req, res, next) and call next() after setting headers. res.setHeader is correct method.
  2. Step 2: Evaluate options

    function addVersion(req, res, next) { res.setHeader('X-App-Version', '1.0'); next(); } sets header then calls next() correctly. function addVersion(req, res) { res.setHeader('X-App-Version', '1.0'); } misses next parameter and call. function addVersion(req, res, next) { next(); res.setHeader('X-App-Version', '1.0'); } calls next() before setting header, so header may not be sent. function addVersion(req, res, next) { req.setHeader('X-App-Version', '1.0'); next(); } uses req.setHeader which is incorrect because req cannot set response headers.
  3. Final Answer:

    function addVersion(req, res, next) { res.setHeader('X-App-Version', '1.0'); next(); } -> Option A
  4. Quick Check:

    Set header before next() with correct method [OK]
Hint: Set header before next() using res.setHeader [OK]
Common Mistakes:
  • Calling next() before setting headers
  • Omitting next parameter or call
  • Confusing req and res when setting headers
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