0
0
NestJSframework~20 mins

Global middleware in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 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.