0
0
NestJSframework~5 mins

Creating middleware in NestJS - Quick Revision & Summary

Choose your learning style9 modes available
Recall & Review
beginner
What is middleware in NestJS?
Middleware in NestJS is a function that runs before the route handler. It can modify the request or response objects or end the request-response cycle.
Click to reveal answer
beginner
How do you create a middleware class in NestJS?
Create a class that implements the <code>NestMiddleware</code> interface and define a <code>use(req, res, next)</code> method.
Click to reveal answer
intermediate
How do you apply middleware to routes in NestJS?
Use the configure() method in a module that implements NestModule and call consumer.apply(MiddlewareClass).forRoutes('route').
Click to reveal answer
beginner
What is the role of the next() function in NestJS middleware?
The next() function passes control to the next middleware or route handler. Without calling it, the request will not proceed.
Click to reveal answer
intermediate
Can NestJS middleware be asynchronous? How?
Yes, middleware can be asynchronous by making the use() method async and using await inside it before calling next().
Click to reveal answer
Which interface must a NestJS middleware class implement?
AMiddlewareHandler
BMiddlewareInterface
CNestMiddleware
DRouteMiddleware
Where do you apply middleware in a NestJS application?
AInside a service class
BDirectly inside a controller method
CIn the main.ts bootstrap file only
DIn the configure() method of a module implementing NestModule
What happens if you forget to call next() in middleware?
AThe request will hang and not reach the route handler
BThe request will skip the middleware
CThe server will crash
DThe middleware will run twice
Which of these is NOT a valid way to apply middleware in NestJS?
AAdding middleware directly in the controller decorator
Bconsumer.apply(MyMiddleware).exclude('dogs').forRoutes('cats')
Cconsumer.apply(MyMiddleware).forRoutes('cats')
DApplying middleware globally in main.ts
Can middleware modify the response object before sending it?
ANo, middleware can only read the request
BYes, middleware can modify req and res objects
CNo, only interceptors can modify responses
DYes, but only if it returns a value
Explain how to create and apply middleware in a NestJS module.
Think about the class, interface, and where you connect middleware to routes.
You got /5 concepts.
    Describe the role of the next() function in NestJS middleware and what happens if it is not called.
    Consider how middleware controls the flow of a request.
    You got /4 concepts.