NestJS Introduction 4 — Questions and Answers
Question 1: Which CLI command generates a new service in NestJS?
- nest make service users
- nest generate service users (Correct answer)
- nestjs add service users
- npm run nest:service users
Correct answer: nest generate service users
'nest generate service users' (or 'nest g s users') creates a service file with @Injectable() and updates the module automatically.
Question 2: What does the @Controller('cats') decorator argument specify?
- The service to inject
- The route prefix for all handlers in that controller (Correct answer)
- The module it belongs to
- The middleware to apply
Correct answer: The route prefix for all handlers in that controller
The string passed to @Controller() sets the path prefix, so @Controller('cats') means all routes in that class are under /cats.
Question 3: In NestJS, where is dependency injection typically performed for a service?
- In a static factory method
- Via the constructor using constructor-based injection (Correct answer)
- By calling app.get() manually
- Through setter methods only
Correct answer: Via the constructor using constructor-based injection
NestJS resolves dependencies declared in the constructor, automatically providing the correct instances at runtime.
Question 4: Which built-in NestJS module provides configuration management and environment variables?
- @nestjs/env
- @nestjs/config (Correct answer)
- @nestjs/settings
- @nestjs/dotenv
Correct answer: @nestjs/config
@nestjs/config wraps dotenv and provides a ConfigService for accessing environment variables in a type-safe way.
Question 5: What is 'middleware' in NestJS and when does it execute?
- A decorator applied to DTOs
- A function that runs before the route handler in the request lifecycle (Correct answer)
- A service that transforms responses
- A guard that blocks unauthorized requests
Correct answer: A function that runs before the route handler in the request lifecycle
Middleware in NestJS functions identically to Express middleware — it has access to req, res, and next() and runs before route handlers.
Question 6: Which interface must a NestJS middleware class implement?
- NestMiddleware (Correct answer)
- MiddlewareConsumer
- UseMiddleware
- HttpMiddleware
Correct answer: NestMiddleware
A middleware class must implement the NestMiddleware interface, which requires a use(req, res, next) method.
Question 7: What is the purpose of the AppModule in a NestJS application?
- It handles all HTTP routing
- It serves as the root module that bootstraps all other feature modules (Correct answer)
- It configures the database connection only
- It defines global exception filters
Correct answer: It serves as the root module that bootstraps all other feature modules
AppModule is the top-level module passed to NestFactory.create(), and it imports all other feature modules to compose the application.
Which CLI command generates a new service in NestJS?