Bird
Raised Fist0
NestJSframework~20 mins

Global middleware in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Global 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 when a global middleware modifies the request object?

Consider a NestJS global middleware that adds a property requestTime to the request object. What will be the output of the controller logging req.requestTime?

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) {
    req['requestTime'] = '2024-06-01T12:00:00Z';
    next();
  }
}

// In main.ts
app.use(new LoggerMiddleware());

// In controller
@Get()
getHello(@Req() req: Request): string {
  console.log(req['requestTime']);
  return 'Hello World';
}
AUndefined is logged because request object is immutable
B'2024-06-01T12:00:00Z' is logged to the console
CAn error is thrown because middleware cannot modify request
DThe middleware does not run, so nothing is logged
Attempts:
2 left
💡 Hint

Think about how middleware can add properties to the request object before it reaches the controller.

❓ lifecycle
intermediate
1:30remaining
When is a global middleware executed in NestJS?

At what point in the request lifecycle does a global middleware run in a NestJS application?

AOnly when a specific route is matched
BAfter the controller returns a response
COnly after guards and interceptors run
DBefore any route handler or controller processes the request
Attempts:
2 left
💡 Hint

Think about middleware as the first step in handling a request.

🔧 Debug
advanced
2:30remaining
Why does this global middleware not run in NestJS?

Given the following code, why does the middleware not run for incoming requests?

NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class MyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Middleware running');
    next();
  }
}

// In main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(new MyMiddleware());
  await app.listen(3000);
}
bootstrap();
AMiddleware must implement OnModuleInit to run
BMiddleware must be registered inside a module, not in main.ts
Capp.use expects an instance, but MyMiddleware class was passed instead
DMiddleware cannot log to console in NestJS
Attempts:
2 left
💡 Hint

Check how middleware is passed to app.use().

📝 Syntax
advanced
1:30remaining
Which option correctly applies a global middleware in NestJS 9+?

Choose the correct syntax to apply a global middleware in NestJS version 9 or later.

Aapp.use(new LoggerMiddleware());
Bapp.useGlobalMiddleware(new LoggerMiddleware());
Capp.useGlobalPipes(new LoggerMiddleware());
Dapp.applyGlobalMiddleware(LoggerMiddleware);
Attempts:
2 left
💡 Hint

Remember how Express middleware is applied in NestJS.

❓ state_output
expert
3:00remaining
What is the final output after multiple global middleware modify the response header?

Two global middleware run in sequence. The first sets header X-First to one. The second sets X-Second to two. What headers will the client receive?

NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class FirstMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    res.setHeader('X-First', 'one');
    next();
  }
}

@Injectable()
export class SecondMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    res.setHeader('X-Second', 'two');
    next();
  }
}

// In main.ts
app.use(new FirstMiddleware());
app.use(new SecondMiddleware());

// Controller returns 'OK'
AHeaders include X-First: one and X-Second: two
BOnly X-Second: two is present, X-First is overwritten
COnly X-First: one is present, X-Second is ignored
DNo custom headers are sent due to middleware conflict
Attempts:
2 left
💡 Hint

Think about how HTTP headers are set and merged in Express response.

Practice

(1/5)
1. What is the main purpose of global middleware in a NestJS application?
easy
A. To define database models for the application
B. To run code on every incoming request before reaching route handlers
C. To create new routes dynamically
D. To handle errors after the response is sent

Solution

  1. Step 1: Understand middleware role

    Middleware runs before route handlers to process requests or add features like logging.
  2. Step 2: Identify global middleware scope

    Global middleware runs on every request, so it applies common logic everywhere.
  3. Final Answer:

    To run code on every incoming request before reaching route handlers -> Option B
  4. Quick Check:

    Global middleware = runs on every request [OK]
Hint: Global middleware runs before routes on all requests [OK]
Common Mistakes:
  • Confusing middleware with route handlers
  • Thinking middleware only runs on some routes
  • Mixing middleware with error handling
2. Which of the following is the correct way to apply a middleware globally in NestJS?
easy
A. app.useGlobalMiddleware(MyMiddleware)
B. consumer.apply(MyMiddleware).forRoutes('users')
C. consumer.apply(MyMiddleware).forRoutes('*')
D. app.applyMiddlewareGlobally(MyMiddleware)

Solution

  1. Step 1: Recall global middleware syntax

    In NestJS, the recommended way to apply middleware globally is using app.useGlobalMiddleware(MyMiddleware).
  2. Step 2: Compare options

    consumer.apply(MyMiddleware).forRoutes('*') applies middleware to all routes but is not truly global middleware; app.useGlobalMiddleware applies middleware globally.
  3. Final Answer:

    app.useGlobalMiddleware(MyMiddleware) -> Option A
  4. Quick Check:

    Global middleware uses app.useGlobalMiddleware [OK]
Hint: Use app.useGlobalMiddleware to apply middleware globally [OK]
Common Mistakes:
  • Using consumer.apply(...).forRoutes('*') for global middleware
  • Trying to call non-existent app methods
  • Confusing middleware registration with guards
3. Given this middleware code, what will be logged for every request?
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    console.log(`Request to: ${req.url}`);
    next();
  }
}

// Applied globally with consumer.apply(LoggerMiddleware).forRoutes('*')
medium
A. Logs the HTTP method only
B. Logs the response status code
C. Logs nothing because next() is missing
D. Logs the URL of every incoming request

Solution

  1. Step 1: Analyze middleware code

    The middleware logs the string 'Request to:' plus the request URL from req.url.
  2. Step 2: Understand global application

    Since applied globally, this log happens on every request URL received by the app.
  3. Final Answer:

    Logs the URL of every incoming request -> Option D
  4. Quick Check:

    LoggerMiddleware logs req.url every request [OK]
Hint: Look for console.log inside middleware use() method [OK]
Common Mistakes:
  • Assuming HTTP method is logged instead of URL
  • Forgetting next() causes no further processing
  • Thinking response status is logged
4. Identify the error in this global middleware setup:
export class AuthMiddleware implements NestMiddleware {
  use(req: Request, res: Response) {
    if (!req.headers.authorization) {
      res.status(401).send('Unauthorized');
    }
  }
}

// Applied with consumer.apply(AuthMiddleware).forRoutes('*')
medium
A. Missing call to next() to continue request processing
B. Middleware should not check headers
C. forRoutes('*') cannot be used for global middleware
D. res.status(401) is invalid syntax

Solution

  1. Step 1: Check middleware method signature

    The use method lacks the next parameter and does not call next(), so request stops here.
  2. Step 2: Understand middleware flow

    Without calling next(), the request will hang or not proceed to route handlers after middleware.
  3. Final Answer:

    Missing call to next() to continue request processing -> Option A
  4. Quick Check:

    Middleware must call next() to proceed [OK]
Hint: Always call next() in middleware to continue [OK]
Common Mistakes:
  • Omitting next() call in middleware
  • Misunderstanding middleware flow control
  • Thinking forRoutes('*') is invalid
5. You want to apply a logging middleware globally but only for HTTP POST requests. Which approach correctly achieves this in NestJS?
hard
A. Use consumer.apply(LoggerMiddleware).forRoutes('*') and check req.method inside middleware
B. Apply middleware only on POST routes manually, no global option
C. Use consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST })
D. Use app.useGlobalMiddleware(LoggerMiddleware) with method filter

Solution

  1. Step 1: Understand route filtering in middleware

    NestJS allows filtering middleware by path and HTTP method using forRoutes with an object.
  2. Step 2: Apply middleware globally but only for POST

    Using forRoutes({ path: '*', method: RequestMethod.POST }) applies middleware to all paths but only POST requests.
  3. Step 3: Evaluate other options

    Use consumer.apply(LoggerMiddleware).forRoutes('*') and check req.method inside middleware applies middleware on all methods, not just POST. Apply middleware only on POST routes manually, no global option is manual, not global. Use app.useGlobalMiddleware(LoggerMiddleware) with method filter is invalid syntax.
  4. Final Answer:

    Use consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST }) -> Option C
  5. Quick Check:

    forRoutes with method filter = selective global middleware [OK]
Hint: Use forRoutes({ path: '*', method: RequestMethod.POST }) for selective global [OK]
Common Mistakes:
  • Applying middleware globally without method filter
  • Trying non-existent app.useGlobalMiddleware method
  • Manually applying middleware on each POST route
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