NestJS Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is NestJS?
Correct answer: A Node.js framework for server-side TypeScript apps
Nest gives a structured architecture inspired by Angular. Under the hood it runs on an HTTP framework, Express by default or Fastify, and adds modules, DI, pipes, guards and more.
2. Which HTTP platform does NestJS use by default?
Correct answer: Express
Express is the default adapter. You can switch to Fastify with
@nestjs/platform-fastifyfor better performance, keeping most of your code unchanged.3. How do you create a new NestJS project?
Correct answer:
npx @nestjs/cli new my-appThe CLI creates
main.ts, a rootAppModule, a sample controller and service, plus test setup.nest generate(nest g) adds modules, controllers and services.4. What does
main.tsusually contain in a Nest app?async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(process.env.PORT ?? 3000); } bootstrap();Correct answer: Bootstrap code that creates and starts the app
Global settings also go here:
app.setGlobalPrefix('api'),app.useGlobalPipes(...),app.enableCors(), Swagger setup.5. What language does NestJS primarily use?
Correct answer: TypeScript
Nest relies on TypeScript decorators and type metadata for dependency injection, so TypeScript is the natural choice.
6. Which three building blocks make up most of a Nest feature?
Correct answer: Module, controller and provider
A controller handles requests, a service holds business logic, and a module groups them and declares what is shared with other modules.
7. What does the
nest g resource userscommand do?Correct answer: Generates a full CRUD feature for
usersIt asks which transport you want (REST, GraphQL, microservice, WebSockets) and wires the new module into the parent module.
8. Why does Nest use decorators like
@Controller()and@Injectable()?Correct answer: They attach metadata that Nest reads to wire things up
Nest uses TypeScript's decorator support (
experimentalDecorators) andemitDecoratorMetadata, which records constructor parameter types for DI.9. What does the
@Module()decorator describe?@Module({ imports: [DatabaseModule], controllers: [UsersController], providers: [UsersService], exports: [UsersService], }) export class UsersModule {}Correct answer: Its imports, controllers, providers and exports
Modules are the unit of organization in Nest. Every app has at least one root module, usually
AppModule.10.
OrdersModuleneedsUsersServicefromUsersModule. What must be true?Correct answer:
UsersModuleexports it;OrdersModuleimportsUsersModuleListing
UsersServiceinOrdersModule.providerswould create a second, separate instance. Export and import share the same one.11. What does
@Global()on a module do?Correct answer: Its exports are available without importing it
Use it sparingly, for things like configuration or a database connection. Explicit imports make dependencies easier to follow.
12. Are module providers singletons by default?
Correct answer: Yes, one instance is shared across the app
The default scope is singleton. Request and transient scopes exist but have a performance cost.
13. Why split an application into feature modules?
Correct answer: To group related code and keep dependencies explicit
A typical app has
UsersModule,OrdersModule,AuthModuleand so on, each with its own controllers, services and exports.14. What is a typical way to load environment configuration in Nest?
Correct answer:
ConfigModule.forRoot()and an injectedConfigServiceforRootloads.envand can validate variables with a schema.isGlobal: truemakesConfigServiceavailable everywhere.15. What is the role of a controller?
Correct answer: Handle HTTP requests and delegate logic
Keep controllers thin: map the request to a service call and the result to a response.
16. Which route does this handler serve?
@Controller("users") export class UsersController { @Get(":id") findOne(@Param("id") id: string) {} }Correct answer:
GET /users/:idThe controller prefix and the method path are joined. With
app.setGlobalPrefix('api')it becomes/api/users/:id.17. How do you read the JSON body of a POST request in a controller?
Correct answer: With the
@Body()parameter decorator@Body() dto: CreateUserDto.@Query()reads query strings,@Param()route params,@Headers()headers.18. What status code does a
@Post()handler return by default?Correct answer: 201
Other methods return 200 by default. Change it with
@HttpCode(204)or another code.19. What happens if a controller method returns a plain object?
Correct answer: Nest serializes it to JSON automatically
Returning a value (or a promise) is the standard approach. Injecting the platform response with
@Res()switches you to manual mode, where you must send the response yourself.20. What is a DTO in Nest?
Correct answer: A class describing the shape of transferred data
Classes are used rather than interfaces because they exist at runtime, so pipes can validate and transform them.
21. Why should a DTO be a class rather than a TypeScript interface?
Correct answer: Interfaces disappear after compilation
Classes keep their decorators and metadata at runtime, which
ValidationPipeand Swagger use.22. How do you read
?page=2in a controller?Correct answer:
@Query('page') page: stringQuery values are strings. Convert them with a pipe (
ParseIntPipe,DefaultValuePipe) or withValidationPipeandtransform: true.23. What is a provider in Nest?
Correct answer: Anything injectable, most often a service
Services, repositories, factories and helpers are providers. The DI container creates them and passes them where needed.
24. How does a controller get a service instance?
@Controller("users") export class UsersController { constructor(private readonly usersService: UsersService) {} }Correct answer: Through constructor injection, by parameter type
The service must be a provider in this module (or exported by an imported module). Nest resolves the whole dependency graph.
25. What is the main benefit of dependency injection?
Correct answer: Dependencies are easy to replace, e.g. in tests
In tests you can override a provider with a fake implementation without changing the class under test.
26. What does
@Injectable()mark?Correct answer: A class that the DI container can manage
Register the class in a module's
providerstoo. Without that, Nest can't resolve it.27. What does the error 'Nest can't resolve dependencies of the UsersController (?)' usually mean?
Correct answer: A constructor dependency isn't available
The
?marks the parameter Nest couldn't find. Checkproviders,exportsandimports, and circular imports.28. How do you register a plain value as a provider, e.g. a config object?
providers: [{ provide: "APP_CONFIG", useValue: { retries: 3 } }]Correct answer: With
useValueand@Inject('APP_CONFIG')Custom providers also support
useClass,useFactoryanduseExisting. Tokens can be strings, symbols or classes.29. What does a pipe do in Nest?
Correct answer: Transforms or validates handler arguments
If validation fails, the pipe throws and the handler isn't called. Built-in pipes include
ParseIntPipe,ParseUUIDPipeandValidationPipe.30. What does
@Param('id', ParseIntPipe) id: numberdo with/users/abc?Correct answer: Responds with 400 Bad Request
For valid input the pipe converts the string to a number, so the handler gets the right type.
31. How is request body validation usually set up?
export class CreateUserDto { @IsEmail() email: string; @IsString() @MinLength(8) password: string; }Correct answer:
class-validatorrules plusValidationPipeapp.useGlobalPipes(new ValidationPipe())validates every@Body(),@Query()and@Param()typed with a DTO.32. What does the
whitelist: trueoption ofValidationPipedo?Correct answer: Strips properties without validation decorators
It protects against clients sending extra fields like
isAdmin.forbidNonWhitelisted: truerejects such requests with 400 instead.33. What does
transform: trueinValidationPipegive you?Correct answer: Payloads become instances of the DTO classes
Without it, the handler gets plain objects and strings, even if the parameter is typed as a class or number.
34. How do you return a 404 from a service or controller?
Correct answer:
throw new NotFoundException('User not found')Nest's built-in exception layer turns
HttpExceptionsubclasses into JSON responses with the right status code.35. What does Nest return if a handler throws a plain
Error?Correct answer: 500 Internal Server Error with a generic message
Unknown errors are not exposed to clients. Map expected cases to
HttpExceptions, or write an exception filter.36. Which built-in exceptions map to 400, 401 and 403?
Correct answer:
BadRequestException,UnauthorizedException,ForbiddenExceptionThere are many more, such as
ConflictException(409) andUnprocessableEntityException(422). All extendHttpException.37. What is an exception filter?
Correct answer: A
@Catch()class for thrown exceptionsFilters can be bound to a method, controller or globally with
app.useGlobalFilters().38. What is middleware in Nest?
Correct answer: Code that runs before the route handler
It's configured in a module's
configure(consumer)method withconsumer.apply(LoggerMiddleware).forRoutes('users').39. What is the job of a guard?
Correct answer: Decide whether a request may reach the handler
A guard implements
canActivate()and returnstrueorfalse(or throws). Returningfalsegives 403 Forbidden by default.40. How do you protect a route with a guard?
Correct answer:
@UseGuards(AuthGuard)on the routeGuards can also be global (
app.useGlobalGuards()or theAPP_GUARDprovider). A common pattern is a global auth guard plus a@Public()decorator for open routes.41. What can an interceptor do?
Correct answer: Run logic before and after the handler
Interceptors wrap the handler call.
next.handle()returns an RxJS Observable of the result that you can transform with operators likemap.42. Where do you configure CORS in a Nest app?
Correct answer:
app.enableCors()inmain.tsPass allowed origins, methods and credentials. Avoid allowing every origin together with credentials.
43. Where should business logic live in a Nest app?
Correct answer: In services, not in controllers
Services can be reused by several controllers, scheduled jobs or message handlers, and are easy to unit test.
44. Which ORMs and database tools are commonly used with Nest?
Correct answer: TypeORM, Prisma, MikroORM and Mongoose
Nest has official integration packages for TypeORM, Sequelize and Mongoose, and documented recipes for Prisma and MikroORM.
45. How is TypeORM typically connected to a Nest app?
Correct answer:
TypeOrmModule.forRoot()plusforFeature([User])In a service you then inject
@InjectRepository(User) private users: Repository<User>.46. How do you use Prisma in Nest?
Correct answer: Make a
PrismaServiceprovider and inject itThe service can connect in
onModuleInit. Export it from aPrismaModuleso feature modules can import it.47. Why are async methods common in Nest services?
Correct answer: Database and HTTP calls are asynchronous
Controllers can return a promise or an Observable, and Nest sends the resolved value.
48. How do you create a testing module in Nest?
const moduleRef = await Test.createTestingModule({ controllers: [UsersController], providers: [UsersService], }).compile();Correct answer: With
Test.createTestingModule(), thencompile()The testing module builds a small DI container with just what the test needs.
49. How do you replace a real service with a mock in a Nest test?
Correct answer:
.overrideProvider(UsersService)You can also register
{ provide: UsersService, useValue: mock }directly inproviders.50. What does an e2e test in a Nest project typically do?
Correct answer: Sends real HTTP requests to the full app
The default project includes a
test/app.e2e-spec.tsthat does exactly this withapp.getHttpServer().51. Which test runner does the default Nest project use?
Correct answer: Jest
Jest is configured out of the box. Teams also use Vitest, often with SWC for fast compilation.
52. How is JWT authentication often implemented in Nest?
Correct answer: With
@nestjs/jwtand a guard for the headerThe guard verifies the token and attaches the user to
request.user; a custom@User()decorator can read it in handlers.53. How can you mark some routes as public when an auth guard is global?
Correct answer: A
@Public()decorator read withReflectorMetadata plus
Reflectoris the standard way for guards and interceptors to read route-level settings.54. How do you add rate limiting to a Nest API?
Correct answer: With the
@nestjs/throttlerpackageYou can set limits per route with
@Throttle()or skip them with@SkipThrottle(). Behind a proxy, make sure the real client IP is used.55. Why should password hashes never be returned in API responses?
Correct answer: They help offline password cracking
Returning entities directly is risky. Map to response DTOs or use serialization rules.
56. How do you generate OpenAPI (Swagger) docs in Nest?
Correct answer: With the
@nestjs/swaggerpackageDecorators like
@ApiProperty()describe DTOs; the Swagger CLI plugin can infer many of them from TypeScript types.57. What does
app.setGlobalPrefix('api')do?Correct answer: Adds
/apiin front of all routesYou can exclude some routes, such as health checks, from the prefix with the
excludeoption.58. Which built-in logger does Nest provide?
Correct answer: The
Loggerclass from@nestjs/commonCreate one per class with
new Logger(UsersService.name). For production, many teams plug in Pino or Winston, or use JSON output.59. How do you run a method on a schedule, e.g. every night?
Correct answer: With
@nestjs/scheduleand@Cron()Remember that with several instances each one runs the cron. Use a lock or a queue for jobs that must run once.
60. What is
@nestjs/terminusused for?Correct answer: Health check endpoints for dependencies
Orchestrators like Kubernetes call these endpoints for readiness and liveness probes.
61. How do you handle file uploads in a Nest app on Express?
Correct answer: With
FileInterceptorand@UploadedFile()Validate size and type with
ParseFilePipeand validators likeMaxFileSizeValidator. Large files are better streamed to object storage.62. What does
ClassSerializerInterceptordo together withclass-transformer?export class UserEntity { id: number; email: string; @Exclude() password: string; }Correct answer: Applies rules like
@Exclude()It works on class instances, not plain objects. Return
new UserEntity(...)or map to a response DTO.63. Which lifecycle hook runs once a module's dependencies are resolved?
Correct answer:
onModuleInit()Others include
onApplicationBootstrap,onModuleDestroy,beforeApplicationShutdownandonApplicationShutdown.64. What must you call so that shutdown hooks run on
SIGTERM?Correct answer:
app.enableShutdownHooks()Then
onModuleDestroyandonApplicationShutdowncan close database connections and finish work gracefully.65. How is a typical Nest project organized?
Correct answer: By feature: a folder per module
Feature folders keep related code together. Shared utilities often go into a
commonorsharedmodule.66. What does
@Res()in a handler change?Correct answer: You must send the response yourself
Use
@Res({ passthrough: true })if you only need to set a header or cookie but still want to return a value.67. Can Nest serve GraphQL instead of REST?
Correct answer: Yes, with the
@nestjs/graphqlpackageYou write resolvers with
@Resolver(),@Query()and@Mutation(), in a code-first or schema-first style.68. What does
nest start --watchdo?Correct answer: Restarts the app when project files change
Builders can be switched to SWC (
--builder swc) for much faster compilation in development.69. How do you send a custom header from a handler without using
@Res()?Correct answer: With the
@Header()decorator on the methodRelated decorators:
@HttpCode()for status and@Redirect()for redirects.70. What is the default TypeScript setting Nest projects need for DI by type?
Correct answer:
emitDecoratorMetadata: trueThis makes TypeScript emit constructor parameter types, which Nest reads through
reflect-metadatato know what to inject.71. What does
PartialType(CreateUserDto)give you?export class UpdateUserDto extends PartialType(CreateUserDto) {}Correct answer: The same DTO with all fields optional
Mapped types (
PartialType,PickType,OmitType,IntersectionType) come from@nestjs/mapped-typesor@nestjs/swaggerand keep validation and docs metadata.72. What does
@Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: numberdo whenlimitis missing?Correct answer: Uses 20, then parses it
Pipes run in order.
DefaultValuePipefills in a value beforeParseIntPipevalidates it.73. How do you call an external HTTP API from a Nest service in the Nest way?
Correct answer: Inject
HttpServicefrom@nestjs/axiosHttpServicereturns Observables;firstValueFrom()turns them into promises. Plainfetchworks too. Always set timeouts.74. Why use
TypeOrmModule.forRootAsync({ useFactory, inject: [ConfigService] })instead offorRoot({...})?Correct answer: Options can come from injected services
Async configuration is a common pattern for dynamic modules: the factory runs after its dependencies are ready.
75. Why prefer
@Body(),@Param()and@Query()over@Req()in handlers?Correct answer: They make inputs explicit
With
@Req()you depend on the platform's request object and lose automatic validation of each value.