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
Why: Providers are marked @Injectable.
2What runs first for an incoming request?Asked almost every time
Why: Middleware runs before guards, interceptors and pipes.
3What do guards decide?Asked almost every time
Why: Guards implement CanActivate for authorisation.
4What do DTOs combined with ValidationPipe give you?Asked almost every time
Why: Invalid requests are rejected.
5Where should role checks live?Asked almost every time
Why: Guards know the target handler.
6Which helper reads metadata set by decorators?Asked almost every time
Why: Used by RolesGuard.
7Which pipe validates DTOs with class-validator?Very often asked
Why: ValidationPipe applies class-validator rules.
8Default provider scope is…Very often asked
Why: One instance is shared across the app.
9Interceptors are built on…Very often asked
Why: They wrap the handler's Observable stream.
10Which exception returns HTTP 404?Very often asked
Why: Built-in exceptions map to status codes.
11Which resolves a circular module import?Very often asked
Why: Prefer restructuring.
12Which provider type builds an instance with a function?Very often asked
Why: Can be async and inject deps.
13Which package generates OpenAPI docs?Very often asked
Why: Decorators describe the API.
14Which package handles background job queues?Very often asked
Why: Retries and concurrency.
15A request-scoped provider makes its dependents…Very often asked
Why: Scope bubbles up the chain.
16Which HTTP platforms can NestJS run on?Often asked
Why: Express is default; Fastify is supported.
17Which decorator handles messages in a microservice request/response?Often asked
Why: @EventPattern is for fire-and-forget events.
18Which method builds a module for tests?Often asked
Why: It compiles a module with overridable providers.
19What does whitelist: true in ValidationPipe do?Often asked
Why: Unknown properties are removed.
20Which call lets shutdown hooks run on signals?Often asked
Why: Graceful shutdown.
21Which decorator creates a WebSocket gateway?Often asked
Why: Handle events with @SubscribeMessage.
22Which package adds rate limiting?Often asked
Why: ThrottlerGuard.
23Which decorator hides a field when serialising?Often asked
Why: From class-transformer.
24Which GraphQL approach generates the schema from classes?Often asked
Why: Decorators define types.
25Which package caches responses with interceptors?Often asked
Why: CacheInterceptor.
26Which method makes a configurable module?Sometimes asked
Why: Dynamic modules expose forRoot/register.
27Which package loads environment configuration?Sometimes asked
Why: It provides ConfigService.
28Which decorator catches exceptions in a filter?Sometimes asked
Why: Exception filters use @Catch().
29Which hook runs once a module's dependencies are resolved?Sometimes asked
Why: Lifecycle hook.
30Which CLI command creates a shared library in a monorepo?Sometimes asked
Why: Shared code via path aliases.
Track what you have practised and search every bank in your dashboard.
Start learning