0
0
NestJSframework~10 mins

Global middleware in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply a middleware globally in a NestJS app.

NestJS
app.[1](new LoggerMiddleware());
Drag options to blanks, or click blank then click option'
Aapply
Buse
Cregister
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'apply' or 'register' instead of 'use' causes errors.
Trying to call middleware without the 'new' keyword.
2fill in blank
medium

Complete the code to implement a middleware class with the correct method signature.

NestJS
export class LoggerMiddleware implements NestMiddleware {
  [1](req: Request, res: Response, next: Function) {
    console.log('Request logged');
    next();
  }
}
Drag options to blanks, or click blank then click option'
Ause
Brun
Capply
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'handle' or 'apply' instead of 'use' causes NestJS to not recognize the middleware.
Missing the 'next()' call inside the method.
3fill in blank
medium

Complete the code to apply the middleware globally in the bootstrap function.

NestJS
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.[1](new LoggerMiddleware());
  await app.listen(3000);
}
Drag options to blanks, or click blank then click option'
Aregister
Bapply
Cuse
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'apply' which is used in module configuration.
Forgetting the 'new' keyword (though shown here).
4fill in blank
hard

Fill both blanks to correctly configure global middleware in the main module.

NestJS
import { MiddlewareConsumer, Module, [1] } from '@nestjs/common';

@Module({})
export class AppModule implements [2] {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
Drag options to blanks, or click blank then click option'
ANestModule
BNestMiddleware
CMiddlewareModule
DMiddlewareHandler
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'NestMiddleware' instead of 'NestModule' for the module class.
Not importing the interface before implementing it.
5fill in blank
hard

Fill all three blanks to create a middleware that logs request method and URL.

NestJS
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, [1]) {
    console.log(`${req.[2] request to ${req.[3]`);
    next();
  }
}
Drag options to blanks, or click blank then click option'
Anext
Bmethod
Curl
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call next() causes the request to hang.
Using incorrect property names like 'request' instead of 'method' or 'url'.