Bird
Raised Fist0
NestJSframework~20 mins

Creating middleware in NestJS - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
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 middleware logging example?
Consider this NestJS middleware that logs the request method and URL. What will be logged when a GET request is made to '/users'?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`${req.method} ${req.url}`);
    next();
  }
}
APOST /users
BGET /users
CError: req.method is undefined
DGET undefined
Attempts:
2 left
💡 Hint
Look at how req.method and req.url are used inside the middleware.
❓ lifecycle
intermediate
1:30remaining
When is NestJS middleware executed in the request lifecycle?
At what point in the request lifecycle does NestJS middleware run?
AOnly after the response is sent to the client
BAfter the route handler returns a response
CBefore the route handler is called
DOnly during application startup
Attempts:
2 left
💡 Hint
Middleware typically processes requests before controllers handle them.
📝 Syntax
advanced
2:30remaining
Which option correctly applies middleware to a specific route in NestJS?
You want to apply a middleware only to the '/api/products' route. Which code snippet correctly does this in NestJS?
NestJS
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // Choose the correct option below
  }
}
Aconsumer.apply(LoggerMiddleware).forRoutes('/api/products');
Bconsumer.use(LoggerMiddleware).forRoutes('/api/products');
Cconsumer.apply(LoggerMiddleware).toRoutes('/api/products');
Dconsumer.use(LoggerMiddleware).toRoutes('/api/products');
Attempts:
2 left
💡 Hint
Check the NestJS MiddlewareConsumer API for the correct method names.
🔧 Debug
advanced
2:00remaining
Why does this NestJS middleware not log anything?
This middleware is supposed to log request info but logs nothing. What is the cause?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class SilentMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // Missing console.log here
    next();
  }
}
AThe middleware does not call console.log, so nothing is logged
BThe middleware forgot to call next(), so it hangs
CThe middleware is not decorated with @Injectable()
DThe middleware uses wrong parameter types
Attempts:
2 left
💡 Hint
Look inside the use method for logging statements.
🧠 Conceptual
expert
2:00remaining
What happens if NestJS middleware does not call next()?
In NestJS, what is the effect of middleware that does not call the next() function?
AThe request will skip the middleware and go directly to the route handler
BThe middleware will complete and send a default response
CThe middleware will throw a runtime error automatically
DThe request will hang and never reach the route handler
Attempts:
2 left
💡 Hint
Think about how middleware chains work in Express-based frameworks.

Practice

(1/5)
1. What is the main purpose of middleware in a NestJS application?
easy
A. To handle server errors automatically
B. To define database models
C. To run code before the request reaches the route handler
D. To create UI components

Solution

  1. Step 1: Understand middleware role

    Middleware is code that runs before the main route handler processes a request.
  2. Step 2: Compare options

    Only To run code before the request reaches the route handler describes this behavior correctly; others describe unrelated tasks.
  3. Final Answer:

    To run code before the request reaches the route handler -> Option C
  4. Quick Check:

    Middleware runs before routes [OK]
Hint: Middleware always runs before route handlers [OK]
Common Mistakes:
  • Confusing middleware with controllers
  • Thinking middleware handles UI rendering
  • Assuming middleware manages database models
2. Which of the following is the correct way to define a middleware class in NestJS?
easy
A. const MyMiddleware = (req, res, next) => { next(); }
B. class MyMiddleware { handle(req, res, next) { next(); } }
C. function MyMiddleware(req, res, next) { next(); }
D. class MyMiddleware { use(req, res, next) { next(); } }

Solution

  1. Step 1: Recall NestJS middleware pattern

    Middleware must be a class with a method named use that takes req, res, next.
  2. Step 2: Check options

    Only class MyMiddleware { use(req, res, next) { next(); } } defines a class with a use method correctly. class MyMiddleware { handle(req, res, next) { next(); } } uses handle, which is invalid. Options C and D define functions, not classes.
  3. Final Answer:

    class MyMiddleware { use(req, res, next) { next(); } } -> Option D
  4. Quick Check:

    Middleware class must have use() method [OK]
Hint: Middleware class must have a use() method [OK]
Common Mistakes:
  • Using method name other than use
  • Defining middleware as a function instead of class
  • Forgetting to call next() inside use
3. Given this middleware class, what will be logged when a request to '/some-path' hits the route?
class LoggerMiddleware {
  use(req, res, next) {
    console.log('Request URL:', req.url);
    next();
  }
}
medium
A. Request URL: /some-path
B. Request URL: undefined
C. No output because next() is missing
D. Error: use method not found

Solution

  1. Step 1: Analyze middleware behavior

    The middleware logs the request URL from req.url and then calls next() to continue.
  2. Step 2: Predict output

    When a request to '/some-path' arrives, it logs 'Request URL: /some-path'. No errors occur because use is defined and next() is called.
  3. Final Answer:

    Request URL: /some-path -> Option A
  4. Quick Check:

    Middleware logs req.url correctly [OK]
Hint: Middleware logs req.url before calling next() [OK]
Common Mistakes:
  • Forgetting to call next() causing no further processing
  • Assuming req.url is undefined
  • Confusing method name use with handle
4. What is wrong with this middleware code?
class LoggerMiddleware {
  use(req, res, next) {
    console.log('Request received');
  }
}

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('users');
  }
}
medium
A. Missing call to next() inside LoggerMiddleware
B. MiddlewareConsumer must be imported from '@nestjs/common' not '@nestjs/core'
C. The configure method should return a value
D. No semicolon after forRoutes call

Solution

  1. Step 1: Check middleware code

    The registration uses MiddlewareConsumer correctly, but examine the LoggerMiddleware class.
  2. Step 2: Identify the error

    The use method does not call next(), causing the request to hang without reaching the route handler.
  3. Final Answer:

    Missing call to next() inside LoggerMiddleware -> Option A
  4. Quick Check:

    Middleware must call next() to continue [OK]
Hint: Always call next() inside middleware use() method [OK]
Common Mistakes:
  • Forgetting next() call causing request hang
  • Thinking configure must return a value
  • Confusing import sources for MiddlewareConsumer
5. You want to apply a middleware only to POST requests on the '/login' route. How can you achieve this in NestJS?
hard
A. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware
B. Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST })
C. Apply middleware globally and filter POST requests inside middleware
D. NestJS does not support method-specific middleware

Solution

  1. Step 1: Understand method-specific middleware application

    In NestJS, you can specify route and HTTP method using an object with path and method in forRoutes.
  2. Step 2: Evaluate options

    Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) correctly uses { path: '/login', method: RequestMethod.POST }. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware applies middleware to all methods on '/login', requiring manual filtering. Apply middleware globally and filter POST requests inside middleware applies globally, which is less efficient. NestJS does not support method-specific middleware is false.
  3. Final Answer:

    Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) -> Option B
  4. Quick Check:

    Use forRoutes with path and method object [OK]
Hint: Use forRoutes with path and method object for specific HTTP verbs [OK]
Common Mistakes:
  • Applying middleware to all methods unintentionally
  • Not importing RequestMethod enum
  • Assuming method-specific middleware is unsupported
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