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. 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. 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-fastify for better performance, keeping most of your code unchanged.

  3. 3. How do you create a new NestJS project?

    Correct answer: npx @nestjs/cli new my-app

    The CLI creates main.ts, a root AppModule, a sample controller and service, plus test setup. nest generate (nest g) adds modules, controllers and services.

  4. 4. What does main.ts usually 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. 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. 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. 7. What does the nest g resource users command do?

    Correct answer: Generates a full CRUD feature for users

    It asks which transport you want (REST, GraphQL, microservice, WebSockets) and wires the new module into the parent module.

  8. 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) and emitDecoratorMetadata, which records constructor parameter types for DI.

  9. 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. 10. OrdersModule needs UsersService from UsersModule. What must be true?

    Correct answer: UsersModule exports it; OrdersModule imports UsersModule

    Listing UsersService in OrdersModule.providers would create a second, separate instance. Export and import share the same one.

  11. 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. 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. 13. Why split an application into feature modules?

    Correct answer: To group related code and keep dependencies explicit

    A typical app has UsersModule, OrdersModule, AuthModule and so on, each with its own controllers, services and exports.

  14. 14. What is a typical way to load environment configuration in Nest?

    Correct answer: ConfigModule.forRoot() and an injected ConfigService

    forRoot loads .env and can validate variables with a schema. isGlobal: true makes ConfigService available everywhere.

  15. 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. 16. Which route does this handler serve?

    @Controller("users")
    export class UsersController {
      @Get(":id")
      findOne(@Param("id") id: string) {}
    }

    Correct answer: GET /users/:id

    The controller prefix and the method path are joined. With app.setGlobalPrefix('api') it becomes /api/users/:id.

  17. 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. 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. 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. 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. 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 ValidationPipe and Swagger use.

  22. 22. How do you read ?page=2 in a controller?

    Correct answer: @Query('page') page: string

    Query values are strings. Convert them with a pipe (ParseIntPipe, DefaultValuePipe) or with ValidationPipe and transform: true.

  23. 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. 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. 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. 26. What does @Injectable() mark?

    Correct answer: A class that the DI container can manage

    Register the class in a module's providers too. Without that, Nest can't resolve it.

  27. 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. Check providers, exports and imports, and circular imports.

  28. 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 useValue and @Inject('APP_CONFIG')

    Custom providers also support useClass, useFactory and useExisting. Tokens can be strings, symbols or classes.

  29. 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, ParseUUIDPipe and ValidationPipe.

  30. 30. What does @Param('id', ParseIntPipe) id: number do 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. 31. How is request body validation usually set up?

    export class CreateUserDto {
      @IsEmail()
      email: string;
    
      @IsString()
      @MinLength(8)
      password: string;
    }

    Correct answer: class-validator rules plus ValidationPipe

    app.useGlobalPipes(new ValidationPipe()) validates every @Body(), @Query() and @Param() typed with a DTO.

  32. 32. What does the whitelist: true option of ValidationPipe do?

    Correct answer: Strips properties without validation decorators

    It protects against clients sending extra fields like isAdmin. forbidNonWhitelisted: true rejects such requests with 400 instead.

  33. 33. What does transform: true in ValidationPipe give 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. 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 HttpException subclasses into JSON responses with the right status code.

  35. 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. 36. Which built-in exceptions map to 400, 401 and 403?

    Correct answer: BadRequestException, UnauthorizedException, ForbiddenException

    There are many more, such as ConflictException (409) and UnprocessableEntityException (422). All extend HttpException.

  37. 37. What is an exception filter?

    Correct answer: A @Catch() class for thrown exceptions

    Filters can be bound to a method, controller or globally with app.useGlobalFilters().

  38. 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 with consumer.apply(LoggerMiddleware).forRoutes('users').

  39. 39. What is the job of a guard?

    Correct answer: Decide whether a request may reach the handler

    A guard implements canActivate() and returns true or false (or throws). Returning false gives 403 Forbidden by default.

  40. 40. How do you protect a route with a guard?

    Correct answer: @UseGuards(AuthGuard) on the route

    Guards can also be global (app.useGlobalGuards() or the APP_GUARD provider). A common pattern is a global auth guard plus a @Public() decorator for open routes.

  41. 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 like map.

  42. 42. Where do you configure CORS in a Nest app?

    Correct answer: app.enableCors() in main.ts

    Pass allowed origins, methods and credentials. Avoid allowing every origin together with credentials.

  43. 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. 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. 45. How is TypeORM typically connected to a Nest app?

    Correct answer: TypeOrmModule.forRoot() plus forFeature([User])

    In a service you then inject @InjectRepository(User) private users: Repository<User>.

  46. 46. How do you use Prisma in Nest?

    Correct answer: Make a PrismaService provider and inject it

    The service can connect in onModuleInit. Export it from a PrismaModule so feature modules can import it.

  47. 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. 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(), then compile()

    The testing module builds a small DI container with just what the test needs.

  49. 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 in providers.

  50. 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.ts that does exactly this with app.getHttpServer().

  51. 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. 52. How is JWT authentication often implemented in Nest?

    Correct answer: With @nestjs/jwt and a guard for the header

    The guard verifies the token and attaches the user to request.user; a custom @User() decorator can read it in handlers.

  53. 53. How can you mark some routes as public when an auth guard is global?

    Correct answer: A @Public() decorator read with Reflector

    Metadata plus Reflector is the standard way for guards and interceptors to read route-level settings.

  54. 54. How do you add rate limiting to a Nest API?

    Correct answer: With the @nestjs/throttler package

    You can set limits per route with @Throttle() or skip them with @SkipThrottle(). Behind a proxy, make sure the real client IP is used.

  55. 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. 56. How do you generate OpenAPI (Swagger) docs in Nest?

    Correct answer: With the @nestjs/swagger package

    Decorators like @ApiProperty() describe DTOs; the Swagger CLI plugin can infer many of them from TypeScript types.

  57. 57. What does app.setGlobalPrefix('api') do?

    Correct answer: Adds /api in front of all routes

    You can exclude some routes, such as health checks, from the prefix with the exclude option.

  58. 58. Which built-in logger does Nest provide?

    Correct answer: The Logger class from @nestjs/common

    Create one per class with new Logger(UsersService.name). For production, many teams plug in Pino or Winston, or use JSON output.

  59. 59. How do you run a method on a schedule, e.g. every night?

    Correct answer: With @nestjs/schedule and @Cron()

    Remember that with several instances each one runs the cron. Use a lock or a queue for jobs that must run once.

  60. 60. What is @nestjs/terminus used for?

    Correct answer: Health check endpoints for dependencies

    Orchestrators like Kubernetes call these endpoints for readiness and liveness probes.

  61. 61. How do you handle file uploads in a Nest app on Express?

    Correct answer: With FileInterceptor and @UploadedFile()

    Validate size and type with ParseFilePipe and validators like MaxFileSizeValidator. Large files are better streamed to object storage.

  62. 62. What does ClassSerializerInterceptor do together with class-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. 63. Which lifecycle hook runs once a module's dependencies are resolved?

    Correct answer: onModuleInit()

    Others include onApplicationBootstrap, onModuleDestroy, beforeApplicationShutdown and onApplicationShutdown.

  64. 64. What must you call so that shutdown hooks run on SIGTERM?

    Correct answer: app.enableShutdownHooks()

    Then onModuleDestroy and onApplicationShutdown can close database connections and finish work gracefully.

  65. 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 common or shared module.

  66. 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. 67. Can Nest serve GraphQL instead of REST?

    Correct answer: Yes, with the @nestjs/graphql package

    You write resolvers with @Resolver(), @Query() and @Mutation(), in a code-first or schema-first style.

  68. 68. What does nest start --watch do?

    Correct answer: Restarts the app when project files change

    Builders can be switched to SWC (--builder swc) for much faster compilation in development.

  69. 69. How do you send a custom header from a handler without using @Res()?

    Correct answer: With the @Header() decorator on the method

    Related decorators: @HttpCode() for status and @Redirect() for redirects.

  70. 70. What is the default TypeScript setting Nest projects need for DI by type?

    Correct answer: emitDecoratorMetadata: true

    This makes TypeScript emit constructor parameter types, which Nest reads through reflect-metadata to know what to inject.

  71. 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-types or @nestjs/swagger and keep validation and docs metadata.

  72. 72. What does @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number do when limit is missing?

    Correct answer: Uses 20, then parses it

    Pipes run in order. DefaultValuePipe fills in a value before ParseIntPipe validates it.

  73. 73. How do you call an external HTTP API from a Nest service in the Nest way?

    Correct answer: Inject HttpService from @nestjs/axios

    HttpService returns Observables; firstValueFrom() turns them into promises. Plain fetch works too. Always set timeouts.

  74. 74. Why use TypeOrmModule.forRootAsync({ useFactory, inject: [ConfigService] }) instead of forRoot({...})?

    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. 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.