Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Interview questions with answers

NestJS interview questions and answers

Modules, providers, DI, guards, pipes, interceptors and microservices. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.

Subjective
30
Objective
30

Subjective questions 30

1What is NestJS and why choose it?Asked almost every time

NestJS is a TypeScript framework for building server-side Node.js applications, structured with modules, controllers and providers and wired by dependency injection, inspired by Angular. It runs on Express or Fastify, and adds a consistent architecture, testing utilities and first-class support for REST, GraphQL, WebSockets, microservices and queues. It suits larger teams that want conventions.

2Explain modules, controllers and providers.Asked almost every time

A module (@Module) groups related code and declares its controllers, providers, imports and exports. Controllers (@Controller) handle incoming requests and map routes to methods. Providers (@Injectable services, repositories, factories) hold business logic and are injected where needed. Exported providers can be used by modules that import the module.

3How does dependency injection work in NestJS?Asked almost every time

Classes declare dependencies in their constructor; Nest's IoC container creates and caches providers (singletons by default) and injects them, resolving the graph at start-up. Custom providers use useClass, useValue, useFactory or useExisting, with tokens for non-class values. Scopes can be request- or transient-scoped when needed.

4Describe the request lifecycle.Asked almost every time

Incoming request → middleware → guards (may this request proceed?) → interceptors (before) → pipes (validate and transform parameters) → the controller method → interceptors (after, transforming the response) → exception filters if anything throws. Each can be global, controller-level or route-level.

5What are DTOs and why use them in NestJS?Asked almost every time

Data transfer objects are classes describing the shape of request or response data. Decorated with class-validator rules and used with ValidationPipe, they validate and transform input at the boundary, document the API (with Swagger) and keep controllers free of manual checks.

6How do you implement authentication with JWT in NestJS?Asked almost every time

Use @nestjs/jwt (and optionally Passport strategies) to issue tokens at login after checking credentials, then a guard that verifies the token on protected routes and attaches the user to the request. Use refresh tokens with rotation, short-lived access tokens and httpOnly cookies for browsers.

7How do you implement role-based authorization?Asked almost every time

Create a @Roles('admin') decorator with SetMetadata (or Reflector.createDecorator), and a RolesGuard that reads the metadata with Reflector and compares it with the authenticated user's roles. Register the guard globally or per controller, after authentication.

8What are guards and how do you protect routes?Very often asked

Guards implement CanActivate and decide whether a request continues, typically for authentication and role checks. Combine AuthGuard('jwt') from @nestjs/passport with a roles guard that reads metadata set by a custom @Roles() decorator through the Reflector.

9How do pipes and validation work?Very often asked

Pipes transform and validate inputs before the handler runs. ValidationPipe with class-validator decorators on DTO classes rejects invalid bodies with 400 errors; whitelist strips unknown properties and transform converts payloads to DTO instances. Built-in pipes such as ParseIntPipe convert route parameters.

10What are interceptors used for?Very often asked

Interceptors wrap the handler with RxJS, running logic before and after it: logging and timing, mapping responses into a standard envelope, caching, timeouts, or transforming errors. They implement NestInterceptor and return an Observable.

11How do you handle errors consistently?Very often asked

Throw built-in HTTP exceptions (NotFoundException, BadRequestException) or custom ones; Nest turns them into JSON responses. Exception filters (@Catch) customise the format, logging or mapping of domain errors, and can be registered globally.

12How do you connect to a database?Very often asked

Use an integration such as @nestjs/typeorm, @nestjs/mongoose or Prisma in a service. Register the connection with forRootAsync reading config from ConfigService, register entities or models per feature module, and inject repositories into services. Keep transactions and queries out of controllers.

13What are middleware in NestJS and how do they differ from guards?Very often asked

Middleware run before route handling with access to raw request and response, like Express middleware: logging, CORS, body parsing. Guards run after middleware, know which handler will run (ExecutionContext) and decide whether to allow it, making them the right place for authorization.

14How do you avoid circular dependencies?Very often asked

Restructure so shared logic moves into a separate module or service. If unavoidable, use forwardRef(() => OtherModule) in imports and @Inject(forwardRef(() => OtherService)) in constructors. Frequent cycles usually signal unclear module boundaries.

15What are custom providers?Very often asked

Providers registered with explicit tokens: useValue for constants or mocks, useClass to swap implementations, useFactory to build instances (possibly async, with injected dependencies), and useExisting for aliases. Inject them with @Inject(TOKEN).

16How do you document a NestJS API?Very often asked

Use @nestjs/swagger: set up a document in main.ts, and annotate DTOs and controllers with @ApiProperty, @ApiTags and @ApiResponse, or enable the CLI plugin to infer much of it automatically. The Swagger UI serves interactive docs.

17How do you schedule jobs and run background work?Very often asked

Use @nestjs/schedule for cron jobs and intervals inside the app, and queues (BullMQ via @nestjs/bullmq) for background jobs with retries and concurrency, running consumers in separate worker processes when the load is heavy.

18How do you build GraphQL APIs in NestJS?Very often asked

Use @nestjs/graphql with Apollo or Mercurius, choosing code-first (TypeScript classes with decorators generate the schema) or schema-first (SDL generates types). Resolvers use the same DI, guards and pipes as REST controllers.

19What is the difference between request-scoped and default-scoped providers?Very often asked

Default providers are singletons shared by all requests. Request-scoped providers are created for each request (useful for per-tenant data), but they make every dependent provider request-scoped too, which costs performance. Prefer passing context explicitly or using AsyncLocalStorage.

20How do you test NestJS code?Often asked

Use Test.createTestingModule to build a module with real or mocked providers (overrideProvider), get instances with module.get(), and unit-test services with Jest. For end-to-end tests, create the app and send requests with Supertest.

21How does configuration management work?Often asked

@nestjs/config loads .env files and environment variables into a ConfigService, with optional schema validation (Joi or Zod) at start-up and typed namespaces via registerAs. Make it global and inject it where needed.

22How do microservices work in NestJS?Often asked

Nest supports transports such as TCP, Redis, NATS, RabbitMQ, Kafka and gRPC. Handlers use @MessagePattern for request/response or @EventPattern for events, and clients send messages with ClientProxy. A hybrid app can serve HTTP and listen to a broker at the same time.

23How do lifecycle hooks work?Often asked

Providers and modules can implement OnModuleInit, OnApplicationBootstrap, OnModuleDestroy, BeforeApplicationShutdown and OnApplicationShutdown. Call app.enableShutdownHooks() so shutdown hooks run on signals, closing connections gracefully.

24How do you handle caching in NestJS?Often asked

Use @nestjs/cache-manager with an in-memory or Redis store, the CacheInterceptor for GET responses, or inject the cache manager to cache specific computations with TTLs and explicit invalidation.

25How do you use WebSockets in NestJS?Often asked

Create a gateway with @WebSocketGateway(), handle events with @SubscribeMessage('event'), and use Socket.IO or ws adapters. Guards, pipes and interceptors work on gateways too, and Redis adapters scale across instances.

26What is a monorepo in NestJS CLI terms?Often asked

The CLI can manage several apps and libraries in one workspace (nest generate app, nest generate library), sharing code through libraries with path aliases. Tools like Nx offer more advanced monorepo features.

27How do you add rate limiting?Often asked

Use @nestjs/throttler: register ThrottlerModule with limits and a TTL, apply the ThrottlerGuard globally, and override with @Throttle() or @SkipThrottle() per route. Use a Redis storage when running multiple instances.

28What are dynamic modules?Sometimes asked

Modules that return their configuration from a static method such as forRoot() or register(), so callers can pass options (database URL, API keys) and the module creates providers from them. forRootAsync lets options come from other providers.

29What are custom decorators?Sometimes asked

Functions that add metadata or extract data, such as a @CurrentUser() parameter decorator built with createParamDecorator, or applyDecorators to combine several decorators like guards and Swagger annotations into one.

30How do you serialise responses and hide fields?Sometimes asked

Use ClassSerializerInterceptor with class-transformer decorators such as @Exclude() on fields like passwords and @Expose() for computed fields, returning class instances from handlers.

Objective questions 30

1Which decorator marks a class that can be injected?Asked almost every time
  1. A@Entity
  2. B@Controller
  3. C@InjectableCorrect answer
  4. D@Module

Why: Providers are marked @Injectable.

2What runs first for an incoming request?Asked almost every time
  1. AException filters
  2. BPipes
  3. CMiddlewareCorrect answer
  4. DInterceptors

Why: Middleware runs before guards, interceptors and pipes.

3What do guards decide?Asked almost every time
  1. ALog levels
  2. BResponse format
  3. CWhether the request may continueCorrect answer
  4. DDatabase schema

Why: Guards implement CanActivate for authorisation.

4What do DTOs combined with ValidationPipe give you?Asked almost every time
  1. ADatabase migrations
  2. BFaster startup
  3. CRouting
  4. DValidated, typed input at the boundaryCorrect answer

Why: Invalid requests are rejected.

5Where should role checks live?Asked almost every time
  1. AIn middleware
  2. BIn a pipe
  3. CIn the entity
  4. DIn a guardCorrect answer

Why: Guards know the target handler.

6Which helper reads metadata set by decorators?Asked almost every time
  1. ALogger
  2. BConfigService
  3. CReflectorCorrect answer
  4. DModuleRef

Why: Used by RolesGuard.

7Which pipe validates DTOs with class-validator?Very often asked
  1. AValidationPipeCorrect answer
  2. BDefaultValuePipe
  3. CJsonPipe
  4. DParseIntPipe

Why: ValidationPipe applies class-validator rules.

8Default provider scope is…Very often asked
  1. ATransient
  2. BSingletonCorrect answer
  3. CSession
  4. DRequest

Why: One instance is shared across the app.

9Interceptors are built on…Very often asked
  1. ACallbacks
  2. BWeb Workers
  3. CPromises only
  4. DRxJS ObservablesCorrect answer

Why: They wrap the handler's Observable stream.

10Which exception returns HTTP 404?Very often asked
  1. ANotFoundExceptionCorrect answer
  2. BForbiddenException
  3. CConflictException
  4. DBadRequestException

Why: Built-in exceptions map to status codes.

11Which resolves a circular module import?Very often asked
  1. AlazyImport
  2. B@Optional
  3. CuseExisting
  4. DforwardRefCorrect answer

Why: Prefer restructuring.

12Which provider type builds an instance with a function?Very often asked
  1. AuseExisting
  2. BuseAlias
  3. CuseFactoryCorrect answer
  4. DuseValue

Why: Can be async and inject deps.

13Which package generates OpenAPI docs?Very often asked
  1. Aswagger-ui only
  2. B@nestjs/openapi-gen
  3. C@nestjs/swaggerCorrect answer
  4. D@nestjs/docs

Why: Decorators describe the API.

14Which package handles background job queues?Very often asked
  1. A@nestjs/schedule only
  2. B@nestjs/events
  3. C@nestjs/jobs
  4. D@nestjs/bullmqCorrect answer

Why: Retries and concurrency.

15A request-scoped provider makes its dependents…Very often asked
  1. ATransient
  2. BGlobal
  3. CRequest-scoped tooCorrect answer
  4. DSingletons

Why: Scope bubbles up the chain.

16Which HTTP platforms can NestJS run on?Often asked
  1. AOnly Koa
  2. BOnly Hapi
  3. COnly Express
  4. DExpress or FastifyCorrect answer

Why: Express is default; Fastify is supported.

17Which decorator handles messages in a microservice request/response?Often asked
  1. A@MessagePatternCorrect answer
  2. B@EventPattern
  3. C@Sub
  4. D@Get

Why: @EventPattern is for fire-and-forget events.

18Which method builds a module for tests?Often asked
  1. ATest.createTestingModuleCorrect answer
  2. BNestFactory.create only
  3. Cjest.mockModule
  4. DModule.test()

Why: It compiles a module with overridable providers.

19What does whitelist: true in ValidationPipe do?Often asked
  1. AStrips properties without validation decoratorsCorrect answer
  2. BDisables validation
  3. CCaches DTOs
  4. DAllows all IPs

Why: Unknown properties are removed.

20Which call lets shutdown hooks run on signals?Often asked
  1. Aprocess.exit()
  2. Bapp.listen()
  3. Capp.enableShutdownHooks()Correct answer
  4. Dapp.close()

Why: Graceful shutdown.

21Which decorator creates a WebSocket gateway?Often asked
  1. A@Socket()
  2. B@Gateway()
  3. C@Ws()
  4. D@WebSocketGateway()Correct answer

Why: Handle events with @SubscribeMessage.

22Which package adds rate limiting?Often asked
  1. Ahelmet
  2. B@nestjs/guard
  3. C@nestjs/throttlerCorrect answer
  4. D@nestjs/limit

Why: ThrottlerGuard.

23Which decorator hides a field when serialising?Often asked
  1. A@Exclude()Correct answer
  2. B@Hidden()
  3. C@Private()
  4. D@Omit()

Why: From class-transformer.

24Which GraphQL approach generates the schema from classes?Often asked
  1. ACode-firstCorrect answer
  2. BSchema-first
  3. CSDL-only
  4. DFederation-only

Why: Decorators define types.

25Which package caches responses with interceptors?Often asked
  1. Alru-cache only
  2. B@nestjs/store
  3. C@nestjs/cache-managerCorrect answer
  4. D@nestjs/redis-only

Why: CacheInterceptor.

26Which method makes a configurable module?Sometimes asked
  1. Abootstrap()
  2. Blisten()
  3. CuseGlobalPipes()
  4. DforRoot()Correct answer

Why: Dynamic modules expose forRoot/register.

27Which package loads environment configuration?Sometimes asked
  1. A@nestjs/env
  2. Bdotenv-nest
  3. C@nestjs/common/env
  4. D@nestjs/configCorrect answer

Why: It provides ConfigService.

28Which decorator catches exceptions in a filter?Sometimes asked
  1. A@Filter
  2. B@OnError
  3. C@Rescue
  4. D@CatchCorrect answer

Why: Exception filters use @Catch().

29Which hook runs once a module's dependencies are resolved?Sometimes asked
  1. AOnApplicationShutdown
  2. BOnRequest
  3. COnDestroy only
  4. DOnModuleInitCorrect answer

Why: Lifecycle hook.

30Which CLI command creates a shared library in a monorepo?Sometimes asked
  1. Anest new lib
  2. Bnest add library
  3. Cnest lib
  4. Dnest generate libraryCorrect answer

Why: Shared code via path aliases.

Track what you have practised and search every bank in your dashboard.

Start learning